es6.js 4.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741
  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 given array from the given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given "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 given 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 given 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 given array or Float32Array from the given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given index element of the given 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 given index element of the given 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 given 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 given 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 given vector by the given 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 given vector coordinates by the given 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 given 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 given array or Float32Array from the given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given floats from the current Vector3 coordinates and set the given 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 given 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 given 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 given 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 given 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 given 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 given 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 given one and stores the result in the given 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 given 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 given 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 given ones and stores the result in the given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given vector "result" with the element values from the index "offset" of the given 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 given vector "result" with the element values from the index "offset" of the given 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 given vector "result" with the given 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 given matrix of the given 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 given vector "result" coordinates with the result of the transformation by the given matrix of the given 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 given vector "result" coordinates with the result of the transformation by the given matrix of the given 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 given matrix of the given 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 given vector "result" with the result of the normal transformation by the given matrix of the given 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 given vector "result" with the result of the normal transformation by the given matrix of the given 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 given 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 given 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 given 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 given vector "result" with the normalization of the given 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 given 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 given 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 given array from the given 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 given 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 given 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 given vector "result" with the result of the addition of the current Vector4 and the given 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 given 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 given 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 given vector "result" with the result of the subtraction of the given 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 given 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 given vector "result" set with the result of the subtraction of the given 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 given 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 given 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 given 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 given 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 given 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 given 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 given vector "result" with the multiplication result of the current Vector4 and the given 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 given 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 given 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 given vector "result" with the division result of the current Vector4 by the given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given vector "result" from the starting index of the given 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 given vector "result" from the starting index of the given Float32Array.
  4006. */
  4007. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4008. Vector4.FromArrayToRef(array, offset, result);
  4009. };
  4010. /**
  4011. * Updates the given vector "result" coordinates from the given 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 given 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 given vector "result" from the normalization of the given 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 given matrix of the given 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 given vector "result" with the result of the normal transformation by the given matrix of the given 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 given vector "result" with the result of the normal transformation by the given matrix of the given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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 given 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. /**
  4228. * Class used to store quaternion data
  4229. * @see https://en.wikipedia.org/wiki/Quaternion
  4230. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4231. */
  4232. var Quaternion = /** @class */ (function () {
  4233. /**
  4234. * Creates a new Quaternion from the given floats
  4235. * @param x defines the first component (0 by default)
  4236. * @param y defines the second component (0 by default)
  4237. * @param z defines the third component (0 by default)
  4238. * @param w defines the fourth component (1.0 by default)
  4239. */
  4240. function Quaternion(
  4241. /** defines the first component (0 by default) */
  4242. x,
  4243. /** defines the second component (0 by default) */
  4244. y,
  4245. /** defines the third component (0 by default) */
  4246. z,
  4247. /** defines the fourth component (1.0 by default) */
  4248. w) {
  4249. if (x === void 0) { x = 0.0; }
  4250. if (y === void 0) { y = 0.0; }
  4251. if (z === void 0) { z = 0.0; }
  4252. if (w === void 0) { w = 1.0; }
  4253. this.x = x;
  4254. this.y = y;
  4255. this.z = z;
  4256. this.w = w;
  4257. }
  4258. /**
  4259. * Gets a string representation for the current quaternion
  4260. * @returns a string with the Quaternion coordinates
  4261. */
  4262. Quaternion.prototype.toString = function () {
  4263. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4264. };
  4265. /**
  4266. * Gets the class name of the quaternion
  4267. * @returns the string "Quaternion"
  4268. */
  4269. Quaternion.prototype.getClassName = function () {
  4270. return "Quaternion";
  4271. };
  4272. /**
  4273. * Gets a hash code for this quaternion
  4274. * @returns the quaternion hash code
  4275. */
  4276. Quaternion.prototype.getHashCode = function () {
  4277. var hash = this.x || 0;
  4278. hash = (hash * 397) ^ (this.y || 0);
  4279. hash = (hash * 397) ^ (this.z || 0);
  4280. hash = (hash * 397) ^ (this.w || 0);
  4281. return hash;
  4282. };
  4283. /**
  4284. * Copy the quaternion to an array
  4285. * @returns a new array populated with 4 elements from the quaternion coordinates
  4286. */
  4287. Quaternion.prototype.asArray = function () {
  4288. return [this.x, this.y, this.z, this.w];
  4289. };
  4290. /**
  4291. * Check if two quaternions are equals
  4292. * @param otherQuaternion defines the second operand
  4293. * @return true if the current quaternion and the given one coordinates are strictly equals
  4294. */
  4295. Quaternion.prototype.equals = function (otherQuaternion) {
  4296. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4297. };
  4298. /**
  4299. * Clone the current quaternion
  4300. * @returns a new quaternion copied from the current one
  4301. */
  4302. Quaternion.prototype.clone = function () {
  4303. return new Quaternion(this.x, this.y, this.z, this.w);
  4304. };
  4305. /**
  4306. * Copy a quaternion to the current one
  4307. * @param other defines the other quaternion
  4308. * @returns the updated current quaternion
  4309. */
  4310. Quaternion.prototype.copyFrom = function (other) {
  4311. this.x = other.x;
  4312. this.y = other.y;
  4313. this.z = other.z;
  4314. this.w = other.w;
  4315. return this;
  4316. };
  4317. /**
  4318. * Updates the current quaternion with the given float coordinates
  4319. * @param x defines the x coordinate
  4320. * @param y defines the y coordinate
  4321. * @param z defines the z coordinate
  4322. * @param w defines the w coordinate
  4323. * @returns the updated current quaternion
  4324. */
  4325. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4326. this.x = x;
  4327. this.y = y;
  4328. this.z = z;
  4329. this.w = w;
  4330. return this;
  4331. };
  4332. /**
  4333. * Updates the current quaternion from the given float coordinates
  4334. * @param x defines the x coordinate
  4335. * @param y defines the y coordinate
  4336. * @param z defines the z coordinate
  4337. * @param w defines the w coordinate
  4338. * @returns the updated current quaternion
  4339. */
  4340. Quaternion.prototype.set = function (x, y, z, w) {
  4341. return this.copyFromFloats(x, y, z, w);
  4342. };
  4343. /**
  4344. * Adds two quaternions
  4345. * @param other defines the second operand
  4346. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4347. */
  4348. Quaternion.prototype.add = function (other) {
  4349. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4350. };
  4351. /**
  4352. * Add a quaternion to the current one
  4353. * @param other defines the quaternion to add
  4354. * @returns the current quaternion
  4355. */
  4356. Quaternion.prototype.addInPlace = function (other) {
  4357. this.x += other.x;
  4358. this.y += other.y;
  4359. this.z += other.z;
  4360. this.w += other.w;
  4361. return this;
  4362. };
  4363. /**
  4364. * Subtract two quaternions
  4365. * @param other defines the second operand
  4366. * @returns a new quaternion as the subtraction result of the given one from the current one
  4367. */
  4368. Quaternion.prototype.subtract = function (other) {
  4369. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4370. };
  4371. /**
  4372. * Multiplies the current quaternion by a scale factor
  4373. * @param value defines the scale factor
  4374. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4375. */
  4376. Quaternion.prototype.scale = function (value) {
  4377. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4378. };
  4379. /**
  4380. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4381. * @param scale defines the scale factor
  4382. * @param result defines the Quaternion object where to store the result
  4383. * @returns the unmodified current quaternion
  4384. */
  4385. Quaternion.prototype.scaleToRef = function (scale, result) {
  4386. result.x = this.x * scale;
  4387. result.y = this.y * scale;
  4388. result.z = this.z * scale;
  4389. result.w = this.w * scale;
  4390. return this;
  4391. };
  4392. /**
  4393. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4394. * @param scale defines the scale factor
  4395. * @param result defines the Quaternion object where to store the result
  4396. * @returns the unmodified current quaternion
  4397. */
  4398. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4399. result.x += this.x * scale;
  4400. result.y += this.y * scale;
  4401. result.z += this.z * scale;
  4402. result.w += this.w * scale;
  4403. return this;
  4404. };
  4405. /**
  4406. * Multiplies two quaternions
  4407. * @param q1 defines the second operand
  4408. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4409. */
  4410. Quaternion.prototype.multiply = function (q1) {
  4411. var result = new Quaternion(0, 0, 0, 1.0);
  4412. this.multiplyToRef(q1, result);
  4413. return result;
  4414. };
  4415. /**
  4416. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4417. * @param q1 defines the second operand
  4418. * @param result defines the target quaternion
  4419. * @returns the current quaternion
  4420. */
  4421. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4422. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4423. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4424. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4425. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4426. result.copyFromFloats(x, y, z, w);
  4427. return this;
  4428. };
  4429. /**
  4430. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4431. * @param q1 defines the second operand
  4432. * @returns the currentupdated quaternion
  4433. */
  4434. Quaternion.prototype.multiplyInPlace = function (q1) {
  4435. this.multiplyToRef(q1, this);
  4436. return this;
  4437. };
  4438. /**
  4439. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4440. * @param ref defines the target quaternion
  4441. * @returns the current quaternion
  4442. */
  4443. Quaternion.prototype.conjugateToRef = function (ref) {
  4444. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4445. return this;
  4446. };
  4447. /**
  4448. * Conjugates in place (1-q) the current quaternion
  4449. * @returns the current updated quaternion
  4450. */
  4451. Quaternion.prototype.conjugateInPlace = function () {
  4452. this.x *= -1;
  4453. this.y *= -1;
  4454. this.z *= -1;
  4455. return this;
  4456. };
  4457. /**
  4458. * Conjugates in place (1-q) the current quaternion
  4459. * @returns a new quaternion
  4460. */
  4461. Quaternion.prototype.conjugate = function () {
  4462. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4463. return result;
  4464. };
  4465. /**
  4466. * Gets length of current quaternion
  4467. * @returns the quaternion length (float)
  4468. */
  4469. Quaternion.prototype.length = function () {
  4470. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4471. };
  4472. /**
  4473. * Normalize in place the current quaternion
  4474. * @returns the current updated quaternion
  4475. */
  4476. Quaternion.prototype.normalize = function () {
  4477. var length = 1.0 / this.length();
  4478. this.x *= length;
  4479. this.y *= length;
  4480. this.z *= length;
  4481. this.w *= length;
  4482. return this;
  4483. };
  4484. /**
  4485. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4486. * @param order is a reserved parameter and is ignore for now
  4487. * @returns a new Vector3 containing the Euler angles
  4488. */
  4489. Quaternion.prototype.toEulerAngles = function (order) {
  4490. if (order === void 0) { order = "YZX"; }
  4491. var result = Vector3.Zero();
  4492. this.toEulerAnglesToRef(result, order);
  4493. return result;
  4494. };
  4495. /**
  4496. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4497. * @param result defines the vector which will be filled with the Euler angles
  4498. * @param order is a reserved parameter and is ignore for now
  4499. * @returns the current unchanged quaternion
  4500. */
  4501. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4502. if (order === void 0) { order = "YZX"; }
  4503. var qz = this.z;
  4504. var qx = this.x;
  4505. var qy = this.y;
  4506. var qw = this.w;
  4507. var sqw = qw * qw;
  4508. var sqz = qz * qz;
  4509. var sqx = qx * qx;
  4510. var sqy = qy * qy;
  4511. var zAxisY = qy * qz - qx * qw;
  4512. var limit = .4999999;
  4513. if (zAxisY < -limit) {
  4514. result.y = 2 * Math.atan2(qy, qw);
  4515. result.x = Math.PI / 2;
  4516. result.z = 0;
  4517. }
  4518. else if (zAxisY > limit) {
  4519. result.y = 2 * Math.atan2(qy, qw);
  4520. result.x = -Math.PI / 2;
  4521. result.z = 0;
  4522. }
  4523. else {
  4524. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4525. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4526. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4527. }
  4528. return this;
  4529. };
  4530. /**
  4531. * Updates the given rotation matrix with the current quaternion values
  4532. * @param result defines the target matrix
  4533. * @returns the current unchanged quaternion
  4534. */
  4535. Quaternion.prototype.toRotationMatrix = function (result) {
  4536. var xx = this.x * this.x;
  4537. var yy = this.y * this.y;
  4538. var zz = this.z * this.z;
  4539. var xy = this.x * this.y;
  4540. var zw = this.z * this.w;
  4541. var zx = this.z * this.x;
  4542. var yw = this.y * this.w;
  4543. var yz = this.y * this.z;
  4544. var xw = this.x * this.w;
  4545. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4546. result.m[1] = 2.0 * (xy + zw);
  4547. result.m[2] = 2.0 * (zx - yw);
  4548. result.m[3] = 0;
  4549. result.m[4] = 2.0 * (xy - zw);
  4550. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4551. result.m[6] = 2.0 * (yz + xw);
  4552. result.m[7] = 0;
  4553. result.m[8] = 2.0 * (zx + yw);
  4554. result.m[9] = 2.0 * (yz - xw);
  4555. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4556. result.m[11] = 0;
  4557. result.m[12] = 0;
  4558. result.m[13] = 0;
  4559. result.m[14] = 0;
  4560. result.m[15] = 1.0;
  4561. result._markAsUpdated();
  4562. return this;
  4563. };
  4564. /**
  4565. * Updates the current quaternion from the given rotation matrix values
  4566. * @param matrix defines the source matrix
  4567. * @returns the current updated quaternion
  4568. */
  4569. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4570. Quaternion.FromRotationMatrixToRef(matrix, this);
  4571. return this;
  4572. };
  4573. // Statics
  4574. /**
  4575. * Creates a new quaternion from a rotation matrix
  4576. * @param matrix defines the source matrix
  4577. * @returns a new quaternion created from the given rotation matrix values
  4578. */
  4579. Quaternion.FromRotationMatrix = function (matrix) {
  4580. var result = new Quaternion();
  4581. Quaternion.FromRotationMatrixToRef(matrix, result);
  4582. return result;
  4583. };
  4584. /**
  4585. * Updates the given quaternion with the given rotation matrix values
  4586. * @param matrix defines the source matrix
  4587. * @param result defines the target quaternion
  4588. */
  4589. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4590. var data = matrix.m;
  4591. var m11 = data[0], m12 = data[4], m13 = data[8];
  4592. var m21 = data[1], m22 = data[5], m23 = data[9];
  4593. var m31 = data[2], m32 = data[6], m33 = data[10];
  4594. var trace = m11 + m22 + m33;
  4595. var s;
  4596. if (trace > 0) {
  4597. s = 0.5 / Math.sqrt(trace + 1.0);
  4598. result.w = 0.25 / s;
  4599. result.x = (m32 - m23) * s;
  4600. result.y = (m13 - m31) * s;
  4601. result.z = (m21 - m12) * s;
  4602. }
  4603. else if (m11 > m22 && m11 > m33) {
  4604. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4605. result.w = (m32 - m23) / s;
  4606. result.x = 0.25 * s;
  4607. result.y = (m12 + m21) / s;
  4608. result.z = (m13 + m31) / s;
  4609. }
  4610. else if (m22 > m33) {
  4611. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4612. result.w = (m13 - m31) / s;
  4613. result.x = (m12 + m21) / s;
  4614. result.y = 0.25 * s;
  4615. result.z = (m23 + m32) / s;
  4616. }
  4617. else {
  4618. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4619. result.w = (m21 - m12) / s;
  4620. result.x = (m13 + m31) / s;
  4621. result.y = (m23 + m32) / s;
  4622. result.z = 0.25 * s;
  4623. }
  4624. };
  4625. /**
  4626. * Creates an empty quaternion
  4627. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4628. */
  4629. Quaternion.Zero = function () {
  4630. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4631. };
  4632. /**
  4633. * Inverse a given quaternion
  4634. * @param q defines the source quaternion
  4635. * @returns a new quaternion as the inverted current quaternion
  4636. */
  4637. Quaternion.Inverse = function (q) {
  4638. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4639. };
  4640. /**
  4641. * Creates an identity quaternion
  4642. * @returns the identity quaternion
  4643. */
  4644. Quaternion.Identity = function () {
  4645. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4646. };
  4647. /**
  4648. * Gets a boolean indicating if the given quaternion is identity
  4649. * @param quaternion defines the quaternion to check
  4650. * @returns true if the quaternion is identity
  4651. */
  4652. Quaternion.IsIdentity = function (quaternion) {
  4653. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4654. };
  4655. /**
  4656. * Creates a quaternion from a rotation around an axis
  4657. * @param axis defines the axis to use
  4658. * @param angle defines the angle to use
  4659. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4660. */
  4661. Quaternion.RotationAxis = function (axis, angle) {
  4662. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4663. };
  4664. /**
  4665. * Creates a rotation around an axis and stores it into the given quaternion
  4666. * @param axis defines the axis to use
  4667. * @param angle defines the angle to use
  4668. * @param result defines the target quaternion
  4669. * @returns the target quaternion
  4670. */
  4671. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4672. var sin = Math.sin(angle / 2);
  4673. axis.normalize();
  4674. result.w = Math.cos(angle / 2);
  4675. result.x = axis.x * sin;
  4676. result.y = axis.y * sin;
  4677. result.z = axis.z * sin;
  4678. return result;
  4679. };
  4680. /**
  4681. * Creates a new quaternion from data stored into an array
  4682. * @param array defines the data source
  4683. * @param offset defines the offset in the source array where the data starts
  4684. * @returns a new quaternion
  4685. */
  4686. Quaternion.FromArray = function (array, offset) {
  4687. if (!offset) {
  4688. offset = 0;
  4689. }
  4690. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4691. };
  4692. /**
  4693. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4694. * @param yaw defines the rotation around Y axis
  4695. * @param pitch defines the rotation around X axis
  4696. * @param roll defines the rotation around Z axis
  4697. * @returns the new quaternion
  4698. */
  4699. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4700. var q = new Quaternion();
  4701. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4702. return q;
  4703. };
  4704. /**
  4705. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4706. * @param yaw defines the rotation around Y axis
  4707. * @param pitch defines the rotation around X axis
  4708. * @param roll defines the rotation around Z axis
  4709. * @param result defines the target quaternion
  4710. */
  4711. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4712. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4713. var halfRoll = roll * 0.5;
  4714. var halfPitch = pitch * 0.5;
  4715. var halfYaw = yaw * 0.5;
  4716. var sinRoll = Math.sin(halfRoll);
  4717. var cosRoll = Math.cos(halfRoll);
  4718. var sinPitch = Math.sin(halfPitch);
  4719. var cosPitch = Math.cos(halfPitch);
  4720. var sinYaw = Math.sin(halfYaw);
  4721. var cosYaw = Math.cos(halfYaw);
  4722. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4723. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4724. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4725. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4726. };
  4727. /**
  4728. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4729. * @param alpha defines the rotation around first axis
  4730. * @param beta defines the rotation around second axis
  4731. * @param gamma defines the rotation around third axis
  4732. * @returns the new quaternion
  4733. */
  4734. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4735. var result = new Quaternion();
  4736. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4737. return result;
  4738. };
  4739. /**
  4740. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4741. * @param alpha defines the rotation around first axis
  4742. * @param beta defines the rotation around second axis
  4743. * @param gamma defines the rotation around third axis
  4744. * @param result defines the target quaternion
  4745. */
  4746. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4747. // Produces a quaternion from Euler angles in the z-x-z orientation
  4748. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4749. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4750. var halfBeta = beta * 0.5;
  4751. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4752. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4753. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4754. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4755. };
  4756. /**
  4757. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4758. * @param axis1 defines the first axis
  4759. * @param axis2 defines the second axis
  4760. * @param axis3 defines the third axis
  4761. * @returns the new quaternion
  4762. */
  4763. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4764. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4765. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4766. return quat;
  4767. };
  4768. /**
  4769. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4770. * @param axis1 defines the first axis
  4771. * @param axis2 defines the second axis
  4772. * @param axis3 defines the third axis
  4773. * @param ref defines the target quaternion
  4774. */
  4775. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4776. var rotMat = MathTmp.Matrix[0];
  4777. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4778. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4779. };
  4780. /**
  4781. * Interpolates between two quaternions
  4782. * @param left defines first quaternion
  4783. * @param right defines second quaternion
  4784. * @param amount defines the gradient to use
  4785. * @returns the new interpolated quaternion
  4786. */
  4787. Quaternion.Slerp = function (left, right, amount) {
  4788. var result = Quaternion.Identity();
  4789. Quaternion.SlerpToRef(left, right, amount, result);
  4790. return result;
  4791. };
  4792. /**
  4793. * Interpolates between two quaternions and stores it into a target quaternion
  4794. * @param left defines first quaternion
  4795. * @param right defines second quaternion
  4796. * @param amount defines the gradient to use
  4797. * @param result defines the target quaternion
  4798. */
  4799. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4800. var num2;
  4801. var num3;
  4802. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4803. var flag = false;
  4804. if (num4 < 0) {
  4805. flag = true;
  4806. num4 = -num4;
  4807. }
  4808. if (num4 > 0.999999) {
  4809. num3 = 1 - amount;
  4810. num2 = flag ? -amount : amount;
  4811. }
  4812. else {
  4813. var num5 = Math.acos(num4);
  4814. var num6 = (1.0 / Math.sin(num5));
  4815. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4816. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4817. }
  4818. result.x = (num3 * left.x) + (num2 * right.x);
  4819. result.y = (num3 * left.y) + (num2 * right.y);
  4820. result.z = (num3 * left.z) + (num2 * right.z);
  4821. result.w = (num3 * left.w) + (num2 * right.w);
  4822. };
  4823. /**
  4824. * Interpolate between two quaternions using Hermite interpolation
  4825. * @param value1 defines first quaternion
  4826. * @param tangent1 defines the incoming tangent
  4827. * @param value2 defines second quaternion
  4828. * @param tangent2 defines the outgoing tangent
  4829. * @param amount defines the target quaternion
  4830. * @returns the new interpolated quaternion
  4831. */
  4832. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4833. var squared = amount * amount;
  4834. var cubed = amount * squared;
  4835. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4836. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4837. var part3 = (cubed - (2.0 * squared)) + amount;
  4838. var part4 = cubed - squared;
  4839. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4840. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4841. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4842. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4843. return new Quaternion(x, y, z, w);
  4844. };
  4845. return Quaternion;
  4846. }());
  4847. BABYLON.Quaternion = Quaternion;
  4848. /**
  4849. * Class used to store matrix data (4x4)
  4850. */
  4851. var Matrix = /** @class */ (function () {
  4852. /**
  4853. * Creates an empty matrix (filled with zeros)
  4854. */
  4855. function Matrix() {
  4856. this._isIdentity = false;
  4857. this._isIdentityDirty = true;
  4858. /**
  4859. * Gets or sets the internal data of the matrix
  4860. */
  4861. this.m = new Float32Array(16);
  4862. this._markAsUpdated();
  4863. }
  4864. /** @ignore */
  4865. Matrix.prototype._markAsUpdated = function () {
  4866. this.updateFlag = Matrix._updateFlagSeed++;
  4867. this._isIdentityDirty = true;
  4868. };
  4869. // Properties
  4870. /**
  4871. * Check if the current matrix is indentity
  4872. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  4873. * @returns true is the matrix is the identity matrix
  4874. */
  4875. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4876. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4877. if (this._isIdentityDirty) {
  4878. this._isIdentityDirty = false;
  4879. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4880. this._isIdentity = false;
  4881. }
  4882. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4883. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4884. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4885. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4886. this._isIdentity = false;
  4887. }
  4888. else {
  4889. this._isIdentity = true;
  4890. }
  4891. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4892. this._isIdentity = false;
  4893. }
  4894. }
  4895. return this._isIdentity;
  4896. };
  4897. /**
  4898. * Gets the determinant of the matrix
  4899. * @returns the matrix determinant
  4900. */
  4901. Matrix.prototype.determinant = function () {
  4902. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4903. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4904. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4905. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4906. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4907. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4908. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4909. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4910. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4911. };
  4912. // Methods
  4913. /**
  4914. * Returns the matrix as a Float32Array
  4915. * @returns the matrix underlying array
  4916. */
  4917. Matrix.prototype.toArray = function () {
  4918. return this.m;
  4919. };
  4920. /**
  4921. * Returns the matrix as a Float32Array
  4922. * @returns the matrix underlying array.
  4923. */
  4924. Matrix.prototype.asArray = function () {
  4925. return this.toArray();
  4926. };
  4927. /**
  4928. * Inverts the current matrix in place
  4929. * @returns the current inverted matrix
  4930. */
  4931. Matrix.prototype.invert = function () {
  4932. this.invertToRef(this);
  4933. return this;
  4934. };
  4935. /**
  4936. * Sets all the matrix elements to zero
  4937. * @returns the current matrix
  4938. */
  4939. Matrix.prototype.reset = function () {
  4940. for (var index = 0; index < 16; index++) {
  4941. this.m[index] = 0.0;
  4942. }
  4943. this._markAsUpdated();
  4944. return this;
  4945. };
  4946. /**
  4947. * Adds the current matrix with a second one
  4948. * @param other defines the matrix to add
  4949. * @returns a new matrix as the addition of the current matrix and the given one
  4950. */
  4951. Matrix.prototype.add = function (other) {
  4952. var result = new Matrix();
  4953. this.addToRef(other, result);
  4954. return result;
  4955. };
  4956. /**
  4957. * Sets the given matrix "result" to the addition of the current matrix and the given one
  4958. * @param other defines the matrix to add
  4959. * @param result defines the target matrix
  4960. * @returns the current matrix
  4961. */
  4962. Matrix.prototype.addToRef = function (other, result) {
  4963. for (var index = 0; index < 16; index++) {
  4964. result.m[index] = this.m[index] + other.m[index];
  4965. }
  4966. result._markAsUpdated();
  4967. return this;
  4968. };
  4969. /**
  4970. * Adds in place the given matrix to the current matrix
  4971. * @param other defines the second operand
  4972. * @returns the current updated matrix
  4973. */
  4974. Matrix.prototype.addToSelf = function (other) {
  4975. for (var index = 0; index < 16; index++) {
  4976. this.m[index] += other.m[index];
  4977. }
  4978. this._markAsUpdated();
  4979. return this;
  4980. };
  4981. /**
  4982. * Sets the given matrix to the current inverted Matrix
  4983. * @param other defines the target matrix
  4984. * @returns the unmodified current matrix
  4985. */
  4986. Matrix.prototype.invertToRef = function (other) {
  4987. var l1 = this.m[0];
  4988. var l2 = this.m[1];
  4989. var l3 = this.m[2];
  4990. var l4 = this.m[3];
  4991. var l5 = this.m[4];
  4992. var l6 = this.m[5];
  4993. var l7 = this.m[6];
  4994. var l8 = this.m[7];
  4995. var l9 = this.m[8];
  4996. var l10 = this.m[9];
  4997. var l11 = this.m[10];
  4998. var l12 = this.m[11];
  4999. var l13 = this.m[12];
  5000. var l14 = this.m[13];
  5001. var l15 = this.m[14];
  5002. var l16 = this.m[15];
  5003. var l17 = (l11 * l16) - (l12 * l15);
  5004. var l18 = (l10 * l16) - (l12 * l14);
  5005. var l19 = (l10 * l15) - (l11 * l14);
  5006. var l20 = (l9 * l16) - (l12 * l13);
  5007. var l21 = (l9 * l15) - (l11 * l13);
  5008. var l22 = (l9 * l14) - (l10 * l13);
  5009. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5010. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5011. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5012. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5013. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5014. var l28 = (l7 * l16) - (l8 * l15);
  5015. var l29 = (l6 * l16) - (l8 * l14);
  5016. var l30 = (l6 * l15) - (l7 * l14);
  5017. var l31 = (l5 * l16) - (l8 * l13);
  5018. var l32 = (l5 * l15) - (l7 * l13);
  5019. var l33 = (l5 * l14) - (l6 * l13);
  5020. var l34 = (l7 * l12) - (l8 * l11);
  5021. var l35 = (l6 * l12) - (l8 * l10);
  5022. var l36 = (l6 * l11) - (l7 * l10);
  5023. var l37 = (l5 * l12) - (l8 * l9);
  5024. var l38 = (l5 * l11) - (l7 * l9);
  5025. var l39 = (l5 * l10) - (l6 * l9);
  5026. other.m[0] = l23 * l27;
  5027. other.m[4] = l24 * l27;
  5028. other.m[8] = l25 * l27;
  5029. other.m[12] = l26 * l27;
  5030. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5031. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5032. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5033. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5034. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5035. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5036. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5037. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5038. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5039. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5040. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5041. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5042. other._markAsUpdated();
  5043. return this;
  5044. };
  5045. /**
  5046. * Inserts the translation vector (using 3 floats) in the current matrix
  5047. * @param x defines the 1st component of the translation
  5048. * @param y defines the 2nd component of the translation
  5049. * @param z defines the 3rd component of the translation
  5050. * @returns the current updated matrix
  5051. */
  5052. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5053. this.m[12] = x;
  5054. this.m[13] = y;
  5055. this.m[14] = z;
  5056. this._markAsUpdated();
  5057. return this;
  5058. };
  5059. /**
  5060. * Inserts the translation vector in the current matrix
  5061. * @param vector3 defines the translation to insert
  5062. * @returns the current updated matrix
  5063. */
  5064. Matrix.prototype.setTranslation = function (vector3) {
  5065. this.m[12] = vector3.x;
  5066. this.m[13] = vector3.y;
  5067. this.m[14] = vector3.z;
  5068. this._markAsUpdated();
  5069. return this;
  5070. };
  5071. /**
  5072. * Gets the translation value of the current matrix
  5073. * @returns a new Vector3 as the extracted translation from the matrix
  5074. */
  5075. Matrix.prototype.getTranslation = function () {
  5076. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5077. };
  5078. /**
  5079. * Fill a Vector3 with the extracted translation from the matrix
  5080. * @param result defines the Vector3 where to store the translation
  5081. * @returns the current matrix
  5082. */
  5083. Matrix.prototype.getTranslationToRef = function (result) {
  5084. result.x = this.m[12];
  5085. result.y = this.m[13];
  5086. result.z = this.m[14];
  5087. return this;
  5088. };
  5089. /**
  5090. * Remove rotation and scaling part from the matrix
  5091. * @returns the updated matrix
  5092. */
  5093. Matrix.prototype.removeRotationAndScaling = function () {
  5094. this.setRowFromFloats(0, 1, 0, 0, 0);
  5095. this.setRowFromFloats(1, 0, 1, 0, 0);
  5096. this.setRowFromFloats(2, 0, 0, 1, 0);
  5097. return this;
  5098. };
  5099. /**
  5100. * Multiply two matrices
  5101. * @param other defines the second operand
  5102. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5103. */
  5104. Matrix.prototype.multiply = function (other) {
  5105. var result = new Matrix();
  5106. this.multiplyToRef(other, result);
  5107. return result;
  5108. };
  5109. /**
  5110. * Copy the current matrix from the given one
  5111. * @param other defines the source matrix
  5112. * @returns the current updated matrix
  5113. */
  5114. Matrix.prototype.copyFrom = function (other) {
  5115. for (var index = 0; index < 16; index++) {
  5116. this.m[index] = other.m[index];
  5117. }
  5118. this._markAsUpdated();
  5119. return this;
  5120. };
  5121. /**
  5122. * Populates the given array from the starting index with the current matrix values
  5123. * @param array defines the target array
  5124. * @param offset defines the offset in the target array where to start storing values
  5125. * @returns the current matrix
  5126. */
  5127. Matrix.prototype.copyToArray = function (array, offset) {
  5128. if (offset === void 0) { offset = 0; }
  5129. for (var index = 0; index < 16; index++) {
  5130. array[offset + index] = this.m[index];
  5131. }
  5132. return this;
  5133. };
  5134. /**
  5135. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5136. * @param other defines the second operand
  5137. * @param result defines the matrix where to store the multiplication
  5138. * @returns the current matrix
  5139. */
  5140. Matrix.prototype.multiplyToRef = function (other, result) {
  5141. this.multiplyToArray(other, result.m, 0);
  5142. result._markAsUpdated();
  5143. return this;
  5144. };
  5145. /**
  5146. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5147. * @param other defines the second operand
  5148. * @param result defines the array where to store the multiplication
  5149. * @param offset defines the offset in the target array where to start storing values
  5150. * @returns the current matrix
  5151. */
  5152. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5153. var tm0 = this.m[0];
  5154. var tm1 = this.m[1];
  5155. var tm2 = this.m[2];
  5156. var tm3 = this.m[3];
  5157. var tm4 = this.m[4];
  5158. var tm5 = this.m[5];
  5159. var tm6 = this.m[6];
  5160. var tm7 = this.m[7];
  5161. var tm8 = this.m[8];
  5162. var tm9 = this.m[9];
  5163. var tm10 = this.m[10];
  5164. var tm11 = this.m[11];
  5165. var tm12 = this.m[12];
  5166. var tm13 = this.m[13];
  5167. var tm14 = this.m[14];
  5168. var tm15 = this.m[15];
  5169. var om0 = other.m[0];
  5170. var om1 = other.m[1];
  5171. var om2 = other.m[2];
  5172. var om3 = other.m[3];
  5173. var om4 = other.m[4];
  5174. var om5 = other.m[5];
  5175. var om6 = other.m[6];
  5176. var om7 = other.m[7];
  5177. var om8 = other.m[8];
  5178. var om9 = other.m[9];
  5179. var om10 = other.m[10];
  5180. var om11 = other.m[11];
  5181. var om12 = other.m[12];
  5182. var om13 = other.m[13];
  5183. var om14 = other.m[14];
  5184. var om15 = other.m[15];
  5185. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5186. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5187. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5188. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5189. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5190. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5191. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5192. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5193. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5194. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5195. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5196. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5197. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5198. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5199. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5200. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5201. return this;
  5202. };
  5203. /**
  5204. * Check equality between this matrix and a second one
  5205. * @param value defines the second matrix to compare
  5206. * @returns true is the current matrix and the given one values are strictly equal
  5207. */
  5208. Matrix.prototype.equals = function (value) {
  5209. return value &&
  5210. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5211. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5212. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5213. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5214. };
  5215. /**
  5216. * Clone the current matrix
  5217. * @returns a new matrix from the current matrix
  5218. */
  5219. Matrix.prototype.clone = function () {
  5220. 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]);
  5221. };
  5222. /**
  5223. * Returns the name of the current matrix class
  5224. * @returns the string "Matrix"
  5225. */
  5226. Matrix.prototype.getClassName = function () {
  5227. return "Matrix";
  5228. };
  5229. /**
  5230. * Gets the hash code of the current matrix
  5231. * @returns the hash code
  5232. */
  5233. Matrix.prototype.getHashCode = function () {
  5234. var hash = this.m[0] || 0;
  5235. for (var i = 1; i < 16; i++) {
  5236. hash = (hash * 397) ^ (this.m[i] || 0);
  5237. }
  5238. return hash;
  5239. };
  5240. /**
  5241. * Decomposes the current Matrix into a translation, rotation and scaling components
  5242. * @param scale defines the scale vector3 given as a reference to update
  5243. * @param rotation defines the rotation quaternion given as a reference to update
  5244. * @param translation defines the translation vector3 given as a reference to update
  5245. * @returns true if operation was successful
  5246. */
  5247. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5248. if (translation) {
  5249. translation.x = this.m[12];
  5250. translation.y = this.m[13];
  5251. translation.z = this.m[14];
  5252. }
  5253. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5254. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5255. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5256. if (this.determinant() <= 0) {
  5257. scale.y *= -1;
  5258. }
  5259. if (rotation) {
  5260. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5261. rotation.x = 0;
  5262. rotation.y = 0;
  5263. rotation.z = 0;
  5264. rotation.w = 1;
  5265. return false;
  5266. }
  5267. 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]);
  5268. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5269. }
  5270. return true;
  5271. };
  5272. /**
  5273. * Gets specific row of the matrix
  5274. * @param index defines the number of the row to get
  5275. * @returns the index-th row of the current matrix as a new Vector4
  5276. */
  5277. Matrix.prototype.getRow = function (index) {
  5278. if (index < 0 || index > 3) {
  5279. return null;
  5280. }
  5281. var i = index * 4;
  5282. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5283. };
  5284. /**
  5285. * Sets the index-th row of the current matrix to the vector4 values
  5286. * @param index defines the number of the row to set
  5287. * @param row defines the target vector4
  5288. * @returns the updated current matrix
  5289. */
  5290. Matrix.prototype.setRow = function (index, row) {
  5291. if (index < 0 || index > 3) {
  5292. return this;
  5293. }
  5294. var i = index * 4;
  5295. this.m[i + 0] = row.x;
  5296. this.m[i + 1] = row.y;
  5297. this.m[i + 2] = row.z;
  5298. this.m[i + 3] = row.w;
  5299. this._markAsUpdated();
  5300. return this;
  5301. };
  5302. /**
  5303. * Compute the transpose of the matrix
  5304. * @returns the new transposed matrix
  5305. */
  5306. Matrix.prototype.transpose = function () {
  5307. return Matrix.Transpose(this);
  5308. };
  5309. /**
  5310. * Compute the transpose of the matrix and store it in a given matrix
  5311. * @param result defines the target matrix
  5312. * @returns the current matrix
  5313. */
  5314. Matrix.prototype.transposeToRef = function (result) {
  5315. Matrix.TransposeToRef(this, result);
  5316. return this;
  5317. };
  5318. /**
  5319. * Sets the index-th row of the current matrix with the given 4 x float values
  5320. * @param index defines the row index
  5321. * @param x defines the x component to set
  5322. * @param y defines the y component to set
  5323. * @param z defines the z component to set
  5324. * @param w defines the w component to set
  5325. * @returns the updated current matrix
  5326. */
  5327. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5328. if (index < 0 || index > 3) {
  5329. return this;
  5330. }
  5331. var i = index * 4;
  5332. this.m[i + 0] = x;
  5333. this.m[i + 1] = y;
  5334. this.m[i + 2] = z;
  5335. this.m[i + 3] = w;
  5336. this._markAsUpdated();
  5337. return this;
  5338. };
  5339. /**
  5340. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5341. * @param scale defines the scale factor
  5342. * @returns a new matrix
  5343. */
  5344. Matrix.prototype.scale = function (scale) {
  5345. var result = new Matrix();
  5346. this.scaleToRef(scale, result);
  5347. return result;
  5348. };
  5349. /**
  5350. * Scale the current matrix values by a factor to a given result matrix
  5351. * @param scale defines the scale factor
  5352. * @param result defines the matrix to store the result
  5353. * @returns the current matrix
  5354. */
  5355. Matrix.prototype.scaleToRef = function (scale, result) {
  5356. for (var index = 0; index < 16; index++) {
  5357. result.m[index] = this.m[index] * scale;
  5358. }
  5359. result._markAsUpdated();
  5360. return this;
  5361. };
  5362. /**
  5363. * Scale the current matrix values by a factor and add the result to a given matrix
  5364. * @param scale defines the scale factor
  5365. * @param result defines the Matrix to store the result
  5366. * @returns the current matrix
  5367. */
  5368. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5369. for (var index = 0; index < 16; index++) {
  5370. result.m[index] += this.m[index] * scale;
  5371. }
  5372. result._markAsUpdated();
  5373. return this;
  5374. };
  5375. /**
  5376. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5377. * @param ref matrix to store the result
  5378. */
  5379. Matrix.prototype.toNormalMatrix = function (ref) {
  5380. this.invertToRef(ref);
  5381. ref.transpose();
  5382. var m = ref.m;
  5383. 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);
  5384. };
  5385. /**
  5386. * Gets only rotation part of the current matrix
  5387. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5388. */
  5389. Matrix.prototype.getRotationMatrix = function () {
  5390. var result = Matrix.Identity();
  5391. this.getRotationMatrixToRef(result);
  5392. return result;
  5393. };
  5394. /**
  5395. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5396. * @param result defines the target matrix to store data to
  5397. * @returns the current matrix
  5398. */
  5399. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5400. var m = this.m;
  5401. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5402. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5403. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5404. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5405. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5406. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5407. 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);
  5408. return this;
  5409. };
  5410. // Statics
  5411. /**
  5412. * Creates a matrix from an array
  5413. * @param array defines the source array
  5414. * @param offset defines an offset in the source array
  5415. * @returns a new Matrix set from the starting index of the given array
  5416. */
  5417. Matrix.FromArray = function (array, offset) {
  5418. var result = new Matrix();
  5419. if (!offset) {
  5420. offset = 0;
  5421. }
  5422. Matrix.FromArrayToRef(array, offset, result);
  5423. return result;
  5424. };
  5425. /**
  5426. * Copy the content of an array into a given matrix
  5427. * @param array defines the source array
  5428. * @param offset defines an offset in the source array
  5429. * @param result defines the target matrix
  5430. */
  5431. Matrix.FromArrayToRef = function (array, offset, result) {
  5432. for (var index = 0; index < 16; index++) {
  5433. result.m[index] = array[index + offset];
  5434. }
  5435. result._markAsUpdated();
  5436. };
  5437. /**
  5438. * Stores an array into a matrix after having multiplied each component by a given factor
  5439. * @param array defines the source array
  5440. * @param offset defines the offset in the source array
  5441. * @param scale defines the scaling factor
  5442. * @param result defines the target matrix
  5443. */
  5444. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5445. for (var index = 0; index < 16; index++) {
  5446. result.m[index] = array[index + offset] * scale;
  5447. }
  5448. result._markAsUpdated();
  5449. };
  5450. /**
  5451. * Stores a list of values (16) inside a given matrix
  5452. * @param initialM11 defines 1st value of 1st row
  5453. * @param initialM12 defines 2nd value of 1st row
  5454. * @param initialM13 defines 3rd value of 1st row
  5455. * @param initialM14 defines 4th value of 1st row
  5456. * @param initialM21 defines 1st value of 2nd row
  5457. * @param initialM22 defines 2nd value of 2nd row
  5458. * @param initialM23 defines 3rd value of 2nd row
  5459. * @param initialM24 defines 4th value of 2nd row
  5460. * @param initialM31 defines 1st value of 3rd row
  5461. * @param initialM32 defines 2nd value of 3rd row
  5462. * @param initialM33 defines 3rd value of 3rd row
  5463. * @param initialM34 defines 4th value of 3rd row
  5464. * @param initialM41 defines 1st value of 4th row
  5465. * @param initialM42 defines 2nd value of 4th row
  5466. * @param initialM43 defines 3rd value of 4th row
  5467. * @param initialM44 defines 4th value of 4th row
  5468. * @param result defines the target matrix
  5469. */
  5470. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5471. result.m[0] = initialM11;
  5472. result.m[1] = initialM12;
  5473. result.m[2] = initialM13;
  5474. result.m[3] = initialM14;
  5475. result.m[4] = initialM21;
  5476. result.m[5] = initialM22;
  5477. result.m[6] = initialM23;
  5478. result.m[7] = initialM24;
  5479. result.m[8] = initialM31;
  5480. result.m[9] = initialM32;
  5481. result.m[10] = initialM33;
  5482. result.m[11] = initialM34;
  5483. result.m[12] = initialM41;
  5484. result.m[13] = initialM42;
  5485. result.m[14] = initialM43;
  5486. result.m[15] = initialM44;
  5487. result._markAsUpdated();
  5488. };
  5489. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5490. /**
  5491. * Gets an identity matrix that must not be updated
  5492. */
  5493. get: function () {
  5494. return Matrix._identityReadOnly;
  5495. },
  5496. enumerable: true,
  5497. configurable: true
  5498. });
  5499. /**
  5500. * Creates new matrix from a list of values (16)
  5501. * @param initialM11 defines 1st value of 1st row
  5502. * @param initialM12 defines 2nd value of 1st row
  5503. * @param initialM13 defines 3rd value of 1st row
  5504. * @param initialM14 defines 4th value of 1st row
  5505. * @param initialM21 defines 1st value of 2nd row
  5506. * @param initialM22 defines 2nd value of 2nd row
  5507. * @param initialM23 defines 3rd value of 2nd row
  5508. * @param initialM24 defines 4th value of 2nd row
  5509. * @param initialM31 defines 1st value of 3rd row
  5510. * @param initialM32 defines 2nd value of 3rd row
  5511. * @param initialM33 defines 3rd value of 3rd row
  5512. * @param initialM34 defines 4th value of 3rd row
  5513. * @param initialM41 defines 1st value of 4th row
  5514. * @param initialM42 defines 2nd value of 4th row
  5515. * @param initialM43 defines 3rd value of 4th row
  5516. * @param initialM44 defines 4th value of 4th row
  5517. * @returns the new matrix
  5518. */
  5519. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5520. var result = new Matrix();
  5521. result.m[0] = initialM11;
  5522. result.m[1] = initialM12;
  5523. result.m[2] = initialM13;
  5524. result.m[3] = initialM14;
  5525. result.m[4] = initialM21;
  5526. result.m[5] = initialM22;
  5527. result.m[6] = initialM23;
  5528. result.m[7] = initialM24;
  5529. result.m[8] = initialM31;
  5530. result.m[9] = initialM32;
  5531. result.m[10] = initialM33;
  5532. result.m[11] = initialM34;
  5533. result.m[12] = initialM41;
  5534. result.m[13] = initialM42;
  5535. result.m[14] = initialM43;
  5536. result.m[15] = initialM44;
  5537. return result;
  5538. };
  5539. /**
  5540. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5541. * @param scale defines the scale vector3
  5542. * @param rotation defines the rotation quaternion
  5543. * @param translation defines the translation vector3
  5544. * @returns a new matrix
  5545. */
  5546. Matrix.Compose = function (scale, rotation, translation) {
  5547. var result = Matrix.Identity();
  5548. Matrix.ComposeToRef(scale, rotation, translation, result);
  5549. return result;
  5550. };
  5551. /**
  5552. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5553. * @param scale defines the scale vector3
  5554. * @param rotation defines the rotation quaternion
  5555. * @param translation defines the translation vector3
  5556. * @param result defines the target matrix
  5557. */
  5558. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5559. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5560. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5561. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5562. result.setTranslation(translation);
  5563. };
  5564. /**
  5565. * Creates a new identity matrix
  5566. * @returns a new identity matrix
  5567. */
  5568. Matrix.Identity = function () {
  5569. 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);
  5570. };
  5571. /**
  5572. * Creates a new identity matrix and stores the result in a given matrix
  5573. * @param result defines the target matrix
  5574. */
  5575. Matrix.IdentityToRef = function (result) {
  5576. 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);
  5577. };
  5578. /**
  5579. * Creates a new zero matrix
  5580. * @returns a new zero matrix
  5581. */
  5582. Matrix.Zero = function () {
  5583. 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);
  5584. };
  5585. /**
  5586. * Creates a new rotation matrix for "angle" radians around the X axis
  5587. * @param angle defines the angle (in radians) to use
  5588. * @return the new matrix
  5589. */
  5590. Matrix.RotationX = function (angle) {
  5591. var result = new Matrix();
  5592. Matrix.RotationXToRef(angle, result);
  5593. return result;
  5594. };
  5595. /**
  5596. * Creates a new matrix as the invert of a given matrix
  5597. * @param source defines the source matrix
  5598. * @returns the new matrix
  5599. */
  5600. Matrix.Invert = function (source) {
  5601. var result = new Matrix();
  5602. source.invertToRef(result);
  5603. return result;
  5604. };
  5605. /**
  5606. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5607. * @param angle defines the angle (in radians) to use
  5608. * @param result defines the target matrix
  5609. */
  5610. Matrix.RotationXToRef = function (angle, result) {
  5611. var s = Math.sin(angle);
  5612. var c = Math.cos(angle);
  5613. result.m[0] = 1.0;
  5614. result.m[15] = 1.0;
  5615. result.m[5] = c;
  5616. result.m[10] = c;
  5617. result.m[9] = -s;
  5618. result.m[6] = s;
  5619. result.m[1] = 0.0;
  5620. result.m[2] = 0.0;
  5621. result.m[3] = 0.0;
  5622. result.m[4] = 0.0;
  5623. result.m[7] = 0.0;
  5624. result.m[8] = 0.0;
  5625. result.m[11] = 0.0;
  5626. result.m[12] = 0.0;
  5627. result.m[13] = 0.0;
  5628. result.m[14] = 0.0;
  5629. result._markAsUpdated();
  5630. };
  5631. /**
  5632. * Creates a new rotation matrix for "angle" radians around the Y axis
  5633. * @param angle defines the angle (in radians) to use
  5634. * @return the new matrix
  5635. */
  5636. Matrix.RotationY = function (angle) {
  5637. var result = new Matrix();
  5638. Matrix.RotationYToRef(angle, result);
  5639. return result;
  5640. };
  5641. /**
  5642. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5643. * @param angle defines the angle (in radians) to use
  5644. * @param result defines the target matrix
  5645. */
  5646. Matrix.RotationYToRef = function (angle, result) {
  5647. var s = Math.sin(angle);
  5648. var c = Math.cos(angle);
  5649. result.m[5] = 1.0;
  5650. result.m[15] = 1.0;
  5651. result.m[0] = c;
  5652. result.m[2] = -s;
  5653. result.m[8] = s;
  5654. result.m[10] = c;
  5655. result.m[1] = 0.0;
  5656. result.m[3] = 0.0;
  5657. result.m[4] = 0.0;
  5658. result.m[6] = 0.0;
  5659. result.m[7] = 0.0;
  5660. result.m[9] = 0.0;
  5661. result.m[11] = 0.0;
  5662. result.m[12] = 0.0;
  5663. result.m[13] = 0.0;
  5664. result.m[14] = 0.0;
  5665. result._markAsUpdated();
  5666. };
  5667. /**
  5668. * Creates a new rotation matrix for "angle" radians around the Z axis
  5669. * @param angle defines the angle (in radians) to use
  5670. * @return the new matrix
  5671. */
  5672. Matrix.RotationZ = function (angle) {
  5673. var result = new Matrix();
  5674. Matrix.RotationZToRef(angle, result);
  5675. return result;
  5676. };
  5677. /**
  5678. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5679. * @param angle defines the angle (in radians) to use
  5680. * @param result defines the target matrix
  5681. */
  5682. Matrix.RotationZToRef = function (angle, result) {
  5683. var s = Math.sin(angle);
  5684. var c = Math.cos(angle);
  5685. result.m[10] = 1.0;
  5686. result.m[15] = 1.0;
  5687. result.m[0] = c;
  5688. result.m[1] = s;
  5689. result.m[4] = -s;
  5690. result.m[5] = c;
  5691. result.m[2] = 0.0;
  5692. result.m[3] = 0.0;
  5693. result.m[6] = 0.0;
  5694. result.m[7] = 0.0;
  5695. result.m[8] = 0.0;
  5696. result.m[9] = 0.0;
  5697. result.m[11] = 0.0;
  5698. result.m[12] = 0.0;
  5699. result.m[13] = 0.0;
  5700. result.m[14] = 0.0;
  5701. result._markAsUpdated();
  5702. };
  5703. /**
  5704. * Creates a new rotation matrix for "angle" radians around the given axis
  5705. * @param axis defines the axis to use
  5706. * @param angle defines the angle (in radians) to use
  5707. * @return the new matrix
  5708. */
  5709. Matrix.RotationAxis = function (axis, angle) {
  5710. var result = Matrix.Zero();
  5711. Matrix.RotationAxisToRef(axis, angle, result);
  5712. return result;
  5713. };
  5714. /**
  5715. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5716. * @param axis defines the axis to use
  5717. * @param angle defines the angle (in radians) to use
  5718. * @param result defines the target matrix
  5719. */
  5720. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5721. var s = Math.sin(-angle);
  5722. var c = Math.cos(-angle);
  5723. var c1 = 1 - c;
  5724. axis.normalize();
  5725. result.m[0] = (axis.x * axis.x) * c1 + c;
  5726. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5727. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5728. result.m[3] = 0.0;
  5729. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5730. result.m[5] = (axis.y * axis.y) * c1 + c;
  5731. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5732. result.m[7] = 0.0;
  5733. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5734. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5735. result.m[10] = (axis.z * axis.z) * c1 + c;
  5736. result.m[11] = 0.0;
  5737. result.m[15] = 1.0;
  5738. result._markAsUpdated();
  5739. };
  5740. /**
  5741. * Creates a rotation matrix
  5742. * @param yaw defines the yaw angle in radians (Y axis)
  5743. * @param pitch defines the pitch angle in radians (X axis)
  5744. * @param roll defines the roll angle in radians (X axis)
  5745. * @returns the new rotation matrix
  5746. */
  5747. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5748. var result = new Matrix();
  5749. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5750. return result;
  5751. };
  5752. /**
  5753. * Creates a rotation matrix and stores it in a given matrix
  5754. * @param yaw defines the yaw angle in radians (Y axis)
  5755. * @param pitch defines the pitch angle in radians (X axis)
  5756. * @param roll defines the roll angle in radians (X axis)
  5757. * @param result defines the target matrix
  5758. */
  5759. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5760. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5761. this._tempQuaternion.toRotationMatrix(result);
  5762. };
  5763. /**
  5764. * Creates a scaling matrix
  5765. * @param x defines the scale factor on X axis
  5766. * @param y defines the scale factor on Y axis
  5767. * @param z defines the scale factor on Z axis
  5768. * @returns the new matrix
  5769. */
  5770. Matrix.Scaling = function (x, y, z) {
  5771. var result = Matrix.Zero();
  5772. Matrix.ScalingToRef(x, y, z, result);
  5773. return result;
  5774. };
  5775. /**
  5776. * Creates a scaling matrix and stores it in a given matrix
  5777. * @param x defines the scale factor on X axis
  5778. * @param y defines the scale factor on Y axis
  5779. * @param z defines the scale factor on Z axis
  5780. * @param result defines the target matrix
  5781. */
  5782. Matrix.ScalingToRef = function (x, y, z, result) {
  5783. result.m[0] = x;
  5784. result.m[1] = 0.0;
  5785. result.m[2] = 0.0;
  5786. result.m[3] = 0.0;
  5787. result.m[4] = 0.0;
  5788. result.m[5] = y;
  5789. result.m[6] = 0.0;
  5790. result.m[7] = 0.0;
  5791. result.m[8] = 0.0;
  5792. result.m[9] = 0.0;
  5793. result.m[10] = z;
  5794. result.m[11] = 0.0;
  5795. result.m[12] = 0.0;
  5796. result.m[13] = 0.0;
  5797. result.m[14] = 0.0;
  5798. result.m[15] = 1.0;
  5799. result._markAsUpdated();
  5800. };
  5801. /**
  5802. * Creates a translation matrix
  5803. * @param x defines the translation on X axis
  5804. * @param y defines the translation on Y axis
  5805. * @param z defines the translationon Z axis
  5806. * @returns the new matrix
  5807. */
  5808. Matrix.Translation = function (x, y, z) {
  5809. var result = Matrix.Identity();
  5810. Matrix.TranslationToRef(x, y, z, result);
  5811. return result;
  5812. };
  5813. /**
  5814. * Creates a translation matrix and stores it in a given matrix
  5815. * @param x defines the translation on X axis
  5816. * @param y defines the translation on Y axis
  5817. * @param z defines the translationon Z axis
  5818. * @param result defines the target matrix
  5819. */
  5820. Matrix.TranslationToRef = function (x, y, z, result) {
  5821. 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);
  5822. };
  5823. /**
  5824. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5825. * @param startValue defines the start value
  5826. * @param endValue defines the end value
  5827. * @param gradient defines the gradient factor
  5828. * @returns the new matrix
  5829. */
  5830. Matrix.Lerp = function (startValue, endValue, gradient) {
  5831. var result = Matrix.Zero();
  5832. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5833. return result;
  5834. };
  5835. /**
  5836. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5837. * @param startValue defines the start value
  5838. * @param endValue defines the end value
  5839. * @param gradient defines the gradient factor
  5840. * @param result defines the Matrix object where to store data
  5841. */
  5842. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5843. for (var index = 0; index < 16; index++) {
  5844. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5845. }
  5846. result._markAsUpdated();
  5847. };
  5848. /**
  5849. * Builds a new matrix whose values are computed by:
  5850. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5851. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5852. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5853. * @param startValue defines the first matrix
  5854. * @param endValue defines the second matrix
  5855. * @param gradient defines the gradient between the two matrices
  5856. * @returns the new matrix
  5857. */
  5858. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5859. var result = Matrix.Zero();
  5860. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  5861. return result;
  5862. };
  5863. /**
  5864. * Update a matrix to values which are computed by:
  5865. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5866. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5867. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5868. * @param startValue defines the first matrix
  5869. * @param endValue defines the second matrix
  5870. * @param gradient defines the gradient between the two matrices
  5871. * @param result defines the target matrix
  5872. */
  5873. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  5874. var startScale = MathTmp.Vector3[0];
  5875. var startRotation = MathTmp.Quaternion[0];
  5876. var startTranslation = MathTmp.Vector3[1];
  5877. startValue.decompose(startScale, startRotation, startTranslation);
  5878. var endScale = MathTmp.Vector3[2];
  5879. var endRotation = MathTmp.Quaternion[1];
  5880. var endTranslation = MathTmp.Vector3[3];
  5881. endValue.decompose(endScale, endRotation, endTranslation);
  5882. var resultScale = MathTmp.Vector3[4];
  5883. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  5884. var resultRotation = MathTmp.Quaternion[2];
  5885. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  5886. var resultTranslation = MathTmp.Vector3[5];
  5887. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  5888. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  5889. };
  5890. /**
  5891. * 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"
  5892. * This function works in left handed mode
  5893. * @param eye defines the final position of the entity
  5894. * @param target defines where the entity should look at
  5895. * @param up defines the up vector for the entity
  5896. * @returns the new matrix
  5897. */
  5898. Matrix.LookAtLH = function (eye, target, up) {
  5899. var result = Matrix.Zero();
  5900. Matrix.LookAtLHToRef(eye, target, up, result);
  5901. return result;
  5902. };
  5903. /**
  5904. * 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".
  5905. * This function works in left handed mode
  5906. * @param eye defines the final position of the entity
  5907. * @param target defines where the entity should look at
  5908. * @param up defines the up vector for the entity
  5909. * @param result defines the target matrix
  5910. */
  5911. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5912. // Z axis
  5913. target.subtractToRef(eye, this._zAxis);
  5914. this._zAxis.normalize();
  5915. // X axis
  5916. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5917. if (this._xAxis.lengthSquared() === 0) {
  5918. this._xAxis.x = 1.0;
  5919. }
  5920. else {
  5921. this._xAxis.normalize();
  5922. }
  5923. // Y axis
  5924. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5925. this._yAxis.normalize();
  5926. // Eye angles
  5927. var ex = -Vector3.Dot(this._xAxis, eye);
  5928. var ey = -Vector3.Dot(this._yAxis, eye);
  5929. var ez = -Vector3.Dot(this._zAxis, eye);
  5930. 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);
  5931. };
  5932. /**
  5933. * 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"
  5934. * This function works in right handed mode
  5935. * @param eye defines the final position of the entity
  5936. * @param target defines where the entity should look at
  5937. * @param up defines the up vector for the entity
  5938. * @returns the new matrix
  5939. */
  5940. Matrix.LookAtRH = function (eye, target, up) {
  5941. var result = Matrix.Zero();
  5942. Matrix.LookAtRHToRef(eye, target, up, result);
  5943. return result;
  5944. };
  5945. /**
  5946. * 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".
  5947. * This function works in right handed mode
  5948. * @param eye defines the final position of the entity
  5949. * @param target defines where the entity should look at
  5950. * @param up defines the up vector for the entity
  5951. * @param result defines the target matrix
  5952. */
  5953. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5954. // Z axis
  5955. eye.subtractToRef(target, this._zAxis);
  5956. this._zAxis.normalize();
  5957. // X axis
  5958. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5959. if (this._xAxis.lengthSquared() === 0) {
  5960. this._xAxis.x = 1.0;
  5961. }
  5962. else {
  5963. this._xAxis.normalize();
  5964. }
  5965. // Y axis
  5966. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5967. this._yAxis.normalize();
  5968. // Eye angles
  5969. var ex = -Vector3.Dot(this._xAxis, eye);
  5970. var ey = -Vector3.Dot(this._yAxis, eye);
  5971. var ez = -Vector3.Dot(this._zAxis, eye);
  5972. 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);
  5973. };
  5974. /**
  5975. * Create a left-handed orthographic projection matrix
  5976. * @param width defines the viewport width
  5977. * @param height defines the viewport height
  5978. * @param znear defines the near clip plane
  5979. * @param zfar defines the far clip plane
  5980. * @returns a new matrix as a left-handed orthographic projection matrix
  5981. */
  5982. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5983. var matrix = Matrix.Zero();
  5984. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5985. return matrix;
  5986. };
  5987. /**
  5988. * Store a left-handed orthographic projection to a given matrix
  5989. * @param width defines the viewport width
  5990. * @param height defines the viewport height
  5991. * @param znear defines the near clip plane
  5992. * @param zfar defines the far clip plane
  5993. * @param result defines the target matrix
  5994. */
  5995. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5996. var n = znear;
  5997. var f = zfar;
  5998. var a = 2.0 / width;
  5999. var b = 2.0 / height;
  6000. var c = 2.0 / (f - n);
  6001. var d = -(f + n) / (f - n);
  6002. 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);
  6003. };
  6004. /**
  6005. * Create a left-handed orthographic projection matrix
  6006. * @param left defines the viewport left coordinate
  6007. * @param right defines the viewport right coordinate
  6008. * @param bottom defines the viewport bottom coordinate
  6009. * @param top defines the viewport top coordinate
  6010. * @param znear defines the near clip plane
  6011. * @param zfar defines the far clip plane
  6012. * @returns a new matrix as a left-handed orthographic projection matrix
  6013. */
  6014. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6015. var matrix = Matrix.Zero();
  6016. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6017. return matrix;
  6018. };
  6019. /**
  6020. * Stores a left-handed orthographic projection into a given matrix
  6021. * @param left defines the viewport left coordinate
  6022. * @param right defines the viewport right coordinate
  6023. * @param bottom defines the viewport bottom coordinate
  6024. * @param top defines the viewport top coordinate
  6025. * @param znear defines the near clip plane
  6026. * @param zfar defines the far clip plane
  6027. * @param result defines the target matrix
  6028. */
  6029. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6030. var n = znear;
  6031. var f = zfar;
  6032. var a = 2.0 / (right - left);
  6033. var b = 2.0 / (top - bottom);
  6034. var c = 2.0 / (f - n);
  6035. var d = -(f + n) / (f - n);
  6036. var i0 = (left + right) / (left - right);
  6037. var i1 = (top + bottom) / (bottom - top);
  6038. 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);
  6039. };
  6040. /**
  6041. * Creates a right-handed orthographic projection matrix
  6042. * @param left defines the viewport left coordinate
  6043. * @param right defines the viewport right coordinate
  6044. * @param bottom defines the viewport bottom coordinate
  6045. * @param top defines the viewport top coordinate
  6046. * @param znear defines the near clip plane
  6047. * @param zfar defines the far clip plane
  6048. * @returns a new matrix as a right-handed orthographic projection matrix
  6049. */
  6050. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6051. var matrix = Matrix.Zero();
  6052. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6053. return matrix;
  6054. };
  6055. /**
  6056. * Stores a right-handed orthographic projection into a given matrix
  6057. * @param left defines the viewport left coordinate
  6058. * @param right defines the viewport right coordinate
  6059. * @param bottom defines the viewport bottom coordinate
  6060. * @param top defines the viewport top coordinate
  6061. * @param znear defines the near clip plane
  6062. * @param zfar defines the far clip plane
  6063. * @param result defines the target matrix
  6064. */
  6065. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6066. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6067. result.m[10] *= -1.0;
  6068. };
  6069. /**
  6070. * Creates a left-handed perspective projection matrix
  6071. * @param width defines the viewport width
  6072. * @param height defines the viewport height
  6073. * @param znear defines the near clip plane
  6074. * @param zfar defines the far clip plane
  6075. * @returns a new matrix as a left-handed perspective projection matrix
  6076. */
  6077. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6078. var matrix = Matrix.Zero();
  6079. var n = znear;
  6080. var f = zfar;
  6081. var a = 2.0 * n / width;
  6082. var b = 2.0 * n / height;
  6083. var c = (f + n) / (f - n);
  6084. var d = -2.0 * f * n / (f - n);
  6085. 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);
  6086. return matrix;
  6087. };
  6088. /**
  6089. * Creates a left-handed perspective projection matrix
  6090. * @param fov defines the horizontal field of view
  6091. * @param aspect defines the aspect ratio
  6092. * @param znear defines the near clip plane
  6093. * @param zfar defines the far clip plane
  6094. * @returns a new matrix as a left-handed perspective projection matrix
  6095. */
  6096. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6097. var matrix = Matrix.Zero();
  6098. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6099. return matrix;
  6100. };
  6101. /**
  6102. * Stores a left-handed perspective projection into a given matrix
  6103. * @param fov defines the horizontal field of view
  6104. * @param aspect defines the aspect ratio
  6105. * @param znear defines the near clip plane
  6106. * @param zfar defines the far clip plane
  6107. * @param result defines the target matrix
  6108. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6109. */
  6110. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6111. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6112. var n = znear;
  6113. var f = zfar;
  6114. var t = 1.0 / (Math.tan(fov * 0.5));
  6115. var a = isVerticalFovFixed ? (t / aspect) : t;
  6116. var b = isVerticalFovFixed ? t : (t * aspect);
  6117. var c = (f + n) / (f - n);
  6118. var d = -2.0 * f * n / (f - n);
  6119. 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);
  6120. };
  6121. /**
  6122. * Creates a right-handed perspective projection matrix
  6123. * @param fov defines the horizontal field of view
  6124. * @param aspect defines the aspect ratio
  6125. * @param znear defines the near clip plane
  6126. * @param zfar defines the far clip plane
  6127. * @returns a new matrix as a right-handed perspective projection matrix
  6128. */
  6129. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6130. var matrix = Matrix.Zero();
  6131. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6132. return matrix;
  6133. };
  6134. /**
  6135. * Stores a right-handed perspective projection into a given matrix
  6136. * @param fov defines the horizontal field of view
  6137. * @param aspect defines the aspect ratio
  6138. * @param znear defines the near clip plane
  6139. * @param zfar defines the far clip plane
  6140. * @param result defines the target matrix
  6141. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6142. */
  6143. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6144. //alternatively this could be expressed as:
  6145. // m = PerspectiveFovLHToRef
  6146. // m[10] *= -1.0;
  6147. // m[11] *= -1.0;
  6148. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6149. var n = znear;
  6150. var f = zfar;
  6151. var t = 1.0 / (Math.tan(fov * 0.5));
  6152. var a = isVerticalFovFixed ? (t / aspect) : t;
  6153. var b = isVerticalFovFixed ? t : (t * aspect);
  6154. var c = -(f + n) / (f - n);
  6155. var d = -2 * f * n / (f - n);
  6156. 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);
  6157. };
  6158. /**
  6159. * Stores a perspective projection for WebVR info a given matrix
  6160. * @param fov defines the field of view
  6161. * @param znear defines the near clip plane
  6162. * @param zfar defines the far clip plane
  6163. * @param result defines the target matrix
  6164. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6165. */
  6166. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6167. if (rightHanded === void 0) { rightHanded = false; }
  6168. var rightHandedFactor = rightHanded ? -1 : 1;
  6169. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6170. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6171. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6172. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6173. var xScale = 2.0 / (leftTan + rightTan);
  6174. var yScale = 2.0 / (upTan + downTan);
  6175. result.m[0] = xScale;
  6176. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6177. result.m[5] = yScale;
  6178. result.m[6] = result.m[7] = 0.0;
  6179. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6180. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6181. result.m[10] = -zfar / (znear - zfar);
  6182. result.m[11] = 1.0 * rightHandedFactor;
  6183. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6184. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6185. result._markAsUpdated();
  6186. };
  6187. /**
  6188. * Computes a complete transformation matrix
  6189. * @param viewport defines the viewport to use
  6190. * @param world defines the world matrix
  6191. * @param view defines the view matrix
  6192. * @param projection defines the projection matrix
  6193. * @param zmin defines the near clip plane
  6194. * @param zmax defines the far clip plane
  6195. * @returns the transformation matrix
  6196. */
  6197. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6198. var cw = viewport.width;
  6199. var ch = viewport.height;
  6200. var cx = viewport.x;
  6201. var cy = viewport.y;
  6202. 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);
  6203. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6204. };
  6205. /**
  6206. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6207. * @param matrix defines the matrix to use
  6208. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6209. */
  6210. Matrix.GetAsMatrix2x2 = function (matrix) {
  6211. return new Float32Array([
  6212. matrix.m[0], matrix.m[1],
  6213. matrix.m[4], matrix.m[5]
  6214. ]);
  6215. };
  6216. /**
  6217. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6218. * @param matrix defines the matrix to use
  6219. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6220. */
  6221. Matrix.GetAsMatrix3x3 = function (matrix) {
  6222. return new Float32Array([
  6223. matrix.m[0], matrix.m[1], matrix.m[2],
  6224. matrix.m[4], matrix.m[5], matrix.m[6],
  6225. matrix.m[8], matrix.m[9], matrix.m[10]
  6226. ]);
  6227. };
  6228. /**
  6229. * Compute the transpose of a given matrix
  6230. * @param matrix defines the matrix to transpose
  6231. * @returns the new matrix
  6232. */
  6233. Matrix.Transpose = function (matrix) {
  6234. var result = new Matrix();
  6235. Matrix.TransposeToRef(matrix, result);
  6236. return result;
  6237. };
  6238. /**
  6239. * Compute the transpose of a matrix and store it in a target matrix
  6240. * @param matrix defines the matrix to transpose
  6241. * @param result defines the target matrix
  6242. */
  6243. Matrix.TransposeToRef = function (matrix, result) {
  6244. result.m[0] = matrix.m[0];
  6245. result.m[1] = matrix.m[4];
  6246. result.m[2] = matrix.m[8];
  6247. result.m[3] = matrix.m[12];
  6248. result.m[4] = matrix.m[1];
  6249. result.m[5] = matrix.m[5];
  6250. result.m[6] = matrix.m[9];
  6251. result.m[7] = matrix.m[13];
  6252. result.m[8] = matrix.m[2];
  6253. result.m[9] = matrix.m[6];
  6254. result.m[10] = matrix.m[10];
  6255. result.m[11] = matrix.m[14];
  6256. result.m[12] = matrix.m[3];
  6257. result.m[13] = matrix.m[7];
  6258. result.m[14] = matrix.m[11];
  6259. result.m[15] = matrix.m[15];
  6260. };
  6261. /**
  6262. * Computes a reflection matrix from a plane
  6263. * @param plane defines the reflection plane
  6264. * @returns a new matrix
  6265. */
  6266. Matrix.Reflection = function (plane) {
  6267. var matrix = new Matrix();
  6268. Matrix.ReflectionToRef(plane, matrix);
  6269. return matrix;
  6270. };
  6271. /**
  6272. * Computes a reflection matrix from a plane
  6273. * @param plane defines the reflection plane
  6274. * @param result defines the target matrix
  6275. */
  6276. Matrix.ReflectionToRef = function (plane, result) {
  6277. plane.normalize();
  6278. var x = plane.normal.x;
  6279. var y = plane.normal.y;
  6280. var z = plane.normal.z;
  6281. var temp = -2 * x;
  6282. var temp2 = -2 * y;
  6283. var temp3 = -2 * z;
  6284. result.m[0] = (temp * x) + 1;
  6285. result.m[1] = temp2 * x;
  6286. result.m[2] = temp3 * x;
  6287. result.m[3] = 0.0;
  6288. result.m[4] = temp * y;
  6289. result.m[5] = (temp2 * y) + 1;
  6290. result.m[6] = temp3 * y;
  6291. result.m[7] = 0.0;
  6292. result.m[8] = temp * z;
  6293. result.m[9] = temp2 * z;
  6294. result.m[10] = (temp3 * z) + 1;
  6295. result.m[11] = 0.0;
  6296. result.m[12] = temp * plane.d;
  6297. result.m[13] = temp2 * plane.d;
  6298. result.m[14] = temp3 * plane.d;
  6299. result.m[15] = 1.0;
  6300. result._markAsUpdated();
  6301. };
  6302. /**
  6303. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6304. * @param xaxis defines the value of the 1st axis
  6305. * @param yaxis defines the value of the 2nd axis
  6306. * @param zaxis defines the value of the 3rd axis
  6307. * @param result defines the target matrix
  6308. */
  6309. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6310. result.m[0] = xaxis.x;
  6311. result.m[1] = xaxis.y;
  6312. result.m[2] = xaxis.z;
  6313. result.m[3] = 0.0;
  6314. result.m[4] = yaxis.x;
  6315. result.m[5] = yaxis.y;
  6316. result.m[6] = yaxis.z;
  6317. result.m[7] = 0.0;
  6318. result.m[8] = zaxis.x;
  6319. result.m[9] = zaxis.y;
  6320. result.m[10] = zaxis.z;
  6321. result.m[11] = 0.0;
  6322. result.m[12] = 0.0;
  6323. result.m[13] = 0.0;
  6324. result.m[14] = 0.0;
  6325. result.m[15] = 1.0;
  6326. result._markAsUpdated();
  6327. };
  6328. /**
  6329. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6330. * @param quat defines the quaternion to use
  6331. * @param result defines the target matrix
  6332. */
  6333. Matrix.FromQuaternionToRef = function (quat, result) {
  6334. var xx = quat.x * quat.x;
  6335. var yy = quat.y * quat.y;
  6336. var zz = quat.z * quat.z;
  6337. var xy = quat.x * quat.y;
  6338. var zw = quat.z * quat.w;
  6339. var zx = quat.z * quat.x;
  6340. var yw = quat.y * quat.w;
  6341. var yz = quat.y * quat.z;
  6342. var xw = quat.x * quat.w;
  6343. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6344. result.m[1] = 2.0 * (xy + zw);
  6345. result.m[2] = 2.0 * (zx - yw);
  6346. result.m[3] = 0.0;
  6347. result.m[4] = 2.0 * (xy - zw);
  6348. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6349. result.m[6] = 2.0 * (yz + xw);
  6350. result.m[7] = 0.0;
  6351. result.m[8] = 2.0 * (zx + yw);
  6352. result.m[9] = 2.0 * (yz - xw);
  6353. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6354. result.m[11] = 0.0;
  6355. result.m[12] = 0.0;
  6356. result.m[13] = 0.0;
  6357. result.m[14] = 0.0;
  6358. result.m[15] = 1.0;
  6359. result._markAsUpdated();
  6360. };
  6361. Matrix._tempQuaternion = new Quaternion();
  6362. Matrix._xAxis = Vector3.Zero();
  6363. Matrix._yAxis = Vector3.Zero();
  6364. Matrix._zAxis = Vector3.Zero();
  6365. Matrix._updateFlagSeed = 0;
  6366. Matrix._identityReadOnly = Matrix.Identity();
  6367. return Matrix;
  6368. }());
  6369. BABYLON.Matrix = Matrix;
  6370. var Plane = /** @class */ (function () {
  6371. /**
  6372. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6373. */
  6374. function Plane(a, b, c, d) {
  6375. this.normal = new Vector3(a, b, c);
  6376. this.d = d;
  6377. }
  6378. /**
  6379. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6380. */
  6381. Plane.prototype.asArray = function () {
  6382. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6383. };
  6384. // Methods
  6385. /**
  6386. * Returns a new plane copied from the current Plane.
  6387. */
  6388. Plane.prototype.clone = function () {
  6389. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6390. };
  6391. /**
  6392. * Returns the string "Plane".
  6393. */
  6394. Plane.prototype.getClassName = function () {
  6395. return "Plane";
  6396. };
  6397. /**
  6398. * Returns the Plane hash code.
  6399. */
  6400. Plane.prototype.getHashCode = function () {
  6401. var hash = this.normal.getHashCode();
  6402. hash = (hash * 397) ^ (this.d || 0);
  6403. return hash;
  6404. };
  6405. /**
  6406. * Normalize the current Plane in place.
  6407. * Returns the updated Plane.
  6408. */
  6409. Plane.prototype.normalize = function () {
  6410. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6411. var magnitude = 0.0;
  6412. if (norm !== 0) {
  6413. magnitude = 1.0 / norm;
  6414. }
  6415. this.normal.x *= magnitude;
  6416. this.normal.y *= magnitude;
  6417. this.normal.z *= magnitude;
  6418. this.d *= magnitude;
  6419. return this;
  6420. };
  6421. /**
  6422. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6423. */
  6424. Plane.prototype.transform = function (transformation) {
  6425. var transposedMatrix = Matrix.Transpose(transformation);
  6426. var x = this.normal.x;
  6427. var y = this.normal.y;
  6428. var z = this.normal.z;
  6429. var d = this.d;
  6430. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6431. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6432. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6433. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6434. return new Plane(normalX, normalY, normalZ, finalD);
  6435. };
  6436. /**
  6437. * Returns the dot product (float) of the point coordinates and the plane normal.
  6438. */
  6439. Plane.prototype.dotCoordinate = function (point) {
  6440. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6441. };
  6442. /**
  6443. * Updates the current Plane from the plane defined by the three given points.
  6444. * Returns the updated Plane.
  6445. */
  6446. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6447. var x1 = point2.x - point1.x;
  6448. var y1 = point2.y - point1.y;
  6449. var z1 = point2.z - point1.z;
  6450. var x2 = point3.x - point1.x;
  6451. var y2 = point3.y - point1.y;
  6452. var z2 = point3.z - point1.z;
  6453. var yz = (y1 * z2) - (z1 * y2);
  6454. var xz = (z1 * x2) - (x1 * z2);
  6455. var xy = (x1 * y2) - (y1 * x2);
  6456. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6457. var invPyth;
  6458. if (pyth !== 0) {
  6459. invPyth = 1.0 / pyth;
  6460. }
  6461. else {
  6462. invPyth = 0.0;
  6463. }
  6464. this.normal.x = yz * invPyth;
  6465. this.normal.y = xz * invPyth;
  6466. this.normal.z = xy * invPyth;
  6467. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6468. return this;
  6469. };
  6470. /**
  6471. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6472. */
  6473. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6474. var dot = Vector3.Dot(this.normal, direction);
  6475. return (dot <= epsilon);
  6476. };
  6477. /**
  6478. * Returns the signed distance (float) from the given point to the Plane.
  6479. */
  6480. Plane.prototype.signedDistanceTo = function (point) {
  6481. return Vector3.Dot(point, this.normal) + this.d;
  6482. };
  6483. // Statics
  6484. /**
  6485. * Returns a new Plane from the given array.
  6486. */
  6487. Plane.FromArray = function (array) {
  6488. return new Plane(array[0], array[1], array[2], array[3]);
  6489. };
  6490. /**
  6491. * Returns a new Plane defined by the three given points.
  6492. */
  6493. Plane.FromPoints = function (point1, point2, point3) {
  6494. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6495. result.copyFromPoints(point1, point2, point3);
  6496. return result;
  6497. };
  6498. /**
  6499. * Returns a new Plane the normal vector to this plane at the given origin point.
  6500. * Note : the vector "normal" is updated because normalized.
  6501. */
  6502. Plane.FromPositionAndNormal = function (origin, normal) {
  6503. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6504. normal.normalize();
  6505. result.normal = normal;
  6506. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6507. return result;
  6508. };
  6509. /**
  6510. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6511. */
  6512. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6513. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6514. return Vector3.Dot(point, normal) + d;
  6515. };
  6516. return Plane;
  6517. }());
  6518. BABYLON.Plane = Plane;
  6519. var Viewport = /** @class */ (function () {
  6520. /**
  6521. * Creates a Viewport object located at (x, y) and sized (width, height).
  6522. */
  6523. function Viewport(x, y, width, height) {
  6524. this.x = x;
  6525. this.y = y;
  6526. this.width = width;
  6527. this.height = height;
  6528. }
  6529. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6530. if (renderWidthOrEngine.getRenderWidth) {
  6531. var engine = renderWidthOrEngine;
  6532. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6533. }
  6534. var renderWidth = renderWidthOrEngine;
  6535. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6536. };
  6537. /**
  6538. * Returns a new Viewport copied from the current one.
  6539. */
  6540. Viewport.prototype.clone = function () {
  6541. return new Viewport(this.x, this.y, this.width, this.height);
  6542. };
  6543. return Viewport;
  6544. }());
  6545. BABYLON.Viewport = Viewport;
  6546. var Frustum = /** @class */ (function () {
  6547. function Frustum() {
  6548. }
  6549. /**
  6550. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6551. */
  6552. Frustum.GetPlanes = function (transform) {
  6553. var frustumPlanes = [];
  6554. for (var index = 0; index < 6; index++) {
  6555. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6556. }
  6557. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6558. return frustumPlanes;
  6559. };
  6560. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6561. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6562. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6563. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6564. frustumPlane.d = transform.m[15] + transform.m[14];
  6565. frustumPlane.normalize();
  6566. };
  6567. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6568. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6569. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6570. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6571. frustumPlane.d = transform.m[15] - transform.m[14];
  6572. frustumPlane.normalize();
  6573. };
  6574. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6575. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6576. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6577. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6578. frustumPlane.d = transform.m[15] + transform.m[12];
  6579. frustumPlane.normalize();
  6580. };
  6581. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6582. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6583. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6584. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6585. frustumPlane.d = transform.m[15] - transform.m[12];
  6586. frustumPlane.normalize();
  6587. };
  6588. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6589. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6590. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6591. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6592. frustumPlane.d = transform.m[15] - transform.m[13];
  6593. frustumPlane.normalize();
  6594. };
  6595. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6596. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6597. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6598. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6599. frustumPlane.d = transform.m[15] + transform.m[13];
  6600. frustumPlane.normalize();
  6601. };
  6602. /**
  6603. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6604. */
  6605. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6606. // Near
  6607. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6608. // Far
  6609. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6610. // Left
  6611. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6612. // Right
  6613. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6614. // Top
  6615. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6616. // Bottom
  6617. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6618. };
  6619. return Frustum;
  6620. }());
  6621. BABYLON.Frustum = Frustum;
  6622. var Space;
  6623. (function (Space) {
  6624. Space[Space["LOCAL"] = 0] = "LOCAL";
  6625. Space[Space["WORLD"] = 1] = "WORLD";
  6626. Space[Space["BONE"] = 2] = "BONE";
  6627. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6628. var Axis = /** @class */ (function () {
  6629. function Axis() {
  6630. }
  6631. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6632. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6633. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6634. return Axis;
  6635. }());
  6636. BABYLON.Axis = Axis;
  6637. ;
  6638. var BezierCurve = /** @class */ (function () {
  6639. function BezierCurve() {
  6640. }
  6641. /**
  6642. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6643. */
  6644. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6645. // Extract X (which is equal to time here)
  6646. var f0 = 1 - 3 * x2 + 3 * x1;
  6647. var f1 = 3 * x2 - 6 * x1;
  6648. var f2 = 3 * x1;
  6649. var refinedT = t;
  6650. for (var i = 0; i < 5; i++) {
  6651. var refinedT2 = refinedT * refinedT;
  6652. var refinedT3 = refinedT2 * refinedT;
  6653. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6654. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6655. refinedT -= (x - t) * slope;
  6656. refinedT = Math.min(1, Math.max(0, refinedT));
  6657. }
  6658. // Resolve cubic bezier for the given x
  6659. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6660. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6661. Math.pow(refinedT, 3);
  6662. };
  6663. return BezierCurve;
  6664. }());
  6665. BABYLON.BezierCurve = BezierCurve;
  6666. var Orientation;
  6667. (function (Orientation) {
  6668. Orientation[Orientation["CW"] = 0] = "CW";
  6669. Orientation[Orientation["CCW"] = 1] = "CCW";
  6670. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6671. var Angle = /** @class */ (function () {
  6672. /**
  6673. * Creates an Angle object of "radians" radians (float).
  6674. */
  6675. function Angle(radians) {
  6676. var _this = this;
  6677. /**
  6678. * Returns the Angle value in degrees (float).
  6679. */
  6680. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6681. /**
  6682. * Returns the Angle value in radians (float).
  6683. */
  6684. this.radians = function () { return _this._radians; };
  6685. this._radians = radians;
  6686. if (this._radians < 0.0)
  6687. this._radians += (2.0 * Math.PI);
  6688. }
  6689. /**
  6690. * Returns a new Angle object valued with the angle value in radians between the two given vectors.
  6691. */
  6692. Angle.BetweenTwoPoints = function (a, b) {
  6693. var delta = b.subtract(a);
  6694. var theta = Math.atan2(delta.y, delta.x);
  6695. return new Angle(theta);
  6696. };
  6697. /**
  6698. * Returns a new Angle object from the given float in radians.
  6699. */
  6700. Angle.FromRadians = function (radians) {
  6701. return new Angle(radians);
  6702. };
  6703. /**
  6704. * Returns a new Angle object from the given float in degrees.
  6705. */
  6706. Angle.FromDegrees = function (degrees) {
  6707. return new Angle(degrees * Math.PI / 180.0);
  6708. };
  6709. return Angle;
  6710. }());
  6711. BABYLON.Angle = Angle;
  6712. var Arc2 = /** @class */ (function () {
  6713. /**
  6714. * Creates an Arc object from the three given points : start, middle and end.
  6715. */
  6716. function Arc2(startPoint, midPoint, endPoint) {
  6717. this.startPoint = startPoint;
  6718. this.midPoint = midPoint;
  6719. this.endPoint = endPoint;
  6720. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6721. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6722. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6723. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6724. 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);
  6725. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6726. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6727. var a1 = this.startAngle.degrees();
  6728. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6729. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6730. // angles correction
  6731. if (a2 - a1 > +180.0)
  6732. a2 -= 360.0;
  6733. if (a2 - a1 < -180.0)
  6734. a2 += 360.0;
  6735. if (a3 - a2 > +180.0)
  6736. a3 -= 360.0;
  6737. if (a3 - a2 < -180.0)
  6738. a3 += 360.0;
  6739. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6740. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6741. }
  6742. return Arc2;
  6743. }());
  6744. BABYLON.Arc2 = Arc2;
  6745. var Path2 = /** @class */ (function () {
  6746. /**
  6747. * Creates a Path2 object from the starting 2D coordinates x and y.
  6748. */
  6749. function Path2(x, y) {
  6750. this._points = new Array();
  6751. this._length = 0.0;
  6752. this.closed = false;
  6753. this._points.push(new Vector2(x, y));
  6754. }
  6755. /**
  6756. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6757. * Returns the updated Path2.
  6758. */
  6759. Path2.prototype.addLineTo = function (x, y) {
  6760. if (this.closed) {
  6761. return this;
  6762. }
  6763. var newPoint = new Vector2(x, y);
  6764. var previousPoint = this._points[this._points.length - 1];
  6765. this._points.push(newPoint);
  6766. this._length += newPoint.subtract(previousPoint).length();
  6767. return this;
  6768. };
  6769. /**
  6770. * 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.
  6771. * Returns the updated Path2.
  6772. */
  6773. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6774. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6775. if (this.closed) {
  6776. return this;
  6777. }
  6778. var startPoint = this._points[this._points.length - 1];
  6779. var midPoint = new Vector2(midX, midY);
  6780. var endPoint = new Vector2(endX, endY);
  6781. var arc = new Arc2(startPoint, midPoint, endPoint);
  6782. var increment = arc.angle.radians() / numberOfSegments;
  6783. if (arc.orientation === Orientation.CW)
  6784. increment *= -1;
  6785. var currentAngle = arc.startAngle.radians() + increment;
  6786. for (var i = 0; i < numberOfSegments; i++) {
  6787. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6788. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6789. this.addLineTo(x, y);
  6790. currentAngle += increment;
  6791. }
  6792. return this;
  6793. };
  6794. /**
  6795. * Closes the Path2.
  6796. * Returns the Path2.
  6797. */
  6798. Path2.prototype.close = function () {
  6799. this.closed = true;
  6800. return this;
  6801. };
  6802. /**
  6803. * Returns the Path2 total length (float).
  6804. */
  6805. Path2.prototype.length = function () {
  6806. var result = this._length;
  6807. if (!this.closed) {
  6808. var lastPoint = this._points[this._points.length - 1];
  6809. var firstPoint = this._points[0];
  6810. result += (firstPoint.subtract(lastPoint).length());
  6811. }
  6812. return result;
  6813. };
  6814. /**
  6815. * Returns the Path2 internal array of points.
  6816. */
  6817. Path2.prototype.getPoints = function () {
  6818. return this._points;
  6819. };
  6820. /**
  6821. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6822. */
  6823. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6824. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6825. return Vector2.Zero();
  6826. }
  6827. var lengthPosition = normalizedLengthPosition * this.length();
  6828. var previousOffset = 0;
  6829. for (var i = 0; i < this._points.length; i++) {
  6830. var j = (i + 1) % this._points.length;
  6831. var a = this._points[i];
  6832. var b = this._points[j];
  6833. var bToA = b.subtract(a);
  6834. var nextOffset = (bToA.length() + previousOffset);
  6835. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6836. var dir = bToA.normalize();
  6837. var localOffset = lengthPosition - previousOffset;
  6838. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6839. }
  6840. previousOffset = nextOffset;
  6841. }
  6842. return Vector2.Zero();
  6843. };
  6844. /**
  6845. * Returns a new Path2 starting at the coordinates (x, y).
  6846. */
  6847. Path2.StartingAt = function (x, y) {
  6848. return new Path2(x, y);
  6849. };
  6850. return Path2;
  6851. }());
  6852. BABYLON.Path2 = Path2;
  6853. var Path3D = /** @class */ (function () {
  6854. /**
  6855. * new Path3D(path, normal, raw)
  6856. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6857. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6858. * path : an array of Vector3, the curve axis of the Path3D
  6859. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6860. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6861. */
  6862. function Path3D(path, firstNormal, raw) {
  6863. if (firstNormal === void 0) { firstNormal = null; }
  6864. this.path = path;
  6865. this._curve = new Array();
  6866. this._distances = new Array();
  6867. this._tangents = new Array();
  6868. this._normals = new Array();
  6869. this._binormals = new Array();
  6870. for (var p = 0; p < path.length; p++) {
  6871. this._curve[p] = path[p].clone(); // hard copy
  6872. }
  6873. this._raw = raw || false;
  6874. this._compute(firstNormal);
  6875. }
  6876. /**
  6877. * Returns the Path3D array of successive Vector3 designing its curve.
  6878. */
  6879. Path3D.prototype.getCurve = function () {
  6880. return this._curve;
  6881. };
  6882. /**
  6883. * Returns an array populated with tangent vectors on each Path3D curve point.
  6884. */
  6885. Path3D.prototype.getTangents = function () {
  6886. return this._tangents;
  6887. };
  6888. /**
  6889. * Returns an array populated with normal vectors on each Path3D curve point.
  6890. */
  6891. Path3D.prototype.getNormals = function () {
  6892. return this._normals;
  6893. };
  6894. /**
  6895. * Returns an array populated with binormal vectors on each Path3D curve point.
  6896. */
  6897. Path3D.prototype.getBinormals = function () {
  6898. return this._binormals;
  6899. };
  6900. /**
  6901. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6902. */
  6903. Path3D.prototype.getDistances = function () {
  6904. return this._distances;
  6905. };
  6906. /**
  6907. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6908. * Returns the same object updated.
  6909. */
  6910. Path3D.prototype.update = function (path, firstNormal) {
  6911. if (firstNormal === void 0) { firstNormal = null; }
  6912. for (var p = 0; p < path.length; p++) {
  6913. this._curve[p].x = path[p].x;
  6914. this._curve[p].y = path[p].y;
  6915. this._curve[p].z = path[p].z;
  6916. }
  6917. this._compute(firstNormal);
  6918. return this;
  6919. };
  6920. // private function compute() : computes tangents, normals and binormals
  6921. Path3D.prototype._compute = function (firstNormal) {
  6922. var l = this._curve.length;
  6923. // first and last tangents
  6924. this._tangents[0] = this._getFirstNonNullVector(0);
  6925. if (!this._raw) {
  6926. this._tangents[0].normalize();
  6927. }
  6928. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6929. if (!this._raw) {
  6930. this._tangents[l - 1].normalize();
  6931. }
  6932. // normals and binormals at first point : arbitrary vector with _normalVector()
  6933. var tg0 = this._tangents[0];
  6934. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6935. this._normals[0] = pp0;
  6936. if (!this._raw) {
  6937. this._normals[0].normalize();
  6938. }
  6939. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6940. if (!this._raw) {
  6941. this._binormals[0].normalize();
  6942. }
  6943. this._distances[0] = 0.0;
  6944. // normals and binormals : next points
  6945. var prev; // previous vector (segment)
  6946. var cur; // current vector (segment)
  6947. var curTang; // current tangent
  6948. // previous normal
  6949. var prevBinor; // previous binormal
  6950. for (var i = 1; i < l; i++) {
  6951. // tangents
  6952. prev = this._getLastNonNullVector(i);
  6953. if (i < l - 1) {
  6954. cur = this._getFirstNonNullVector(i);
  6955. this._tangents[i] = prev.add(cur);
  6956. this._tangents[i].normalize();
  6957. }
  6958. this._distances[i] = this._distances[i - 1] + prev.length();
  6959. // normals and binormals
  6960. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6961. curTang = this._tangents[i];
  6962. prevBinor = this._binormals[i - 1];
  6963. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6964. if (!this._raw) {
  6965. this._normals[i].normalize();
  6966. }
  6967. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6968. if (!this._raw) {
  6969. this._binormals[i].normalize();
  6970. }
  6971. }
  6972. };
  6973. // private function getFirstNonNullVector(index)
  6974. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6975. Path3D.prototype._getFirstNonNullVector = function (index) {
  6976. var i = 1;
  6977. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6978. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6979. i++;
  6980. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6981. }
  6982. return nNVector;
  6983. };
  6984. // private function getLastNonNullVector(index)
  6985. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6986. Path3D.prototype._getLastNonNullVector = function (index) {
  6987. var i = 1;
  6988. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6989. while (nLVector.length() === 0 && index > i + 1) {
  6990. i++;
  6991. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6992. }
  6993. return nLVector;
  6994. };
  6995. // private function normalVector(v0, vt, va) :
  6996. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6997. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6998. Path3D.prototype._normalVector = function (v0, vt, va) {
  6999. var normal0;
  7000. var tgl = vt.length();
  7001. if (tgl === 0.0) {
  7002. tgl = 1.0;
  7003. }
  7004. if (va === undefined || va === null) {
  7005. var point;
  7006. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  7007. point = new Vector3(0.0, -1.0, 0.0);
  7008. }
  7009. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7010. point = new Vector3(1.0, 0.0, 0.0);
  7011. }
  7012. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7013. point = new Vector3(0.0, 0.0, 1.0);
  7014. }
  7015. else {
  7016. point = Vector3.Zero();
  7017. }
  7018. normal0 = Vector3.Cross(vt, point);
  7019. }
  7020. else {
  7021. normal0 = Vector3.Cross(vt, va);
  7022. Vector3.CrossToRef(normal0, vt, normal0);
  7023. }
  7024. normal0.normalize();
  7025. return normal0;
  7026. };
  7027. return Path3D;
  7028. }());
  7029. BABYLON.Path3D = Path3D;
  7030. var Curve3 = /** @class */ (function () {
  7031. /**
  7032. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7033. * A Curve3 is designed from a series of successive Vector3.
  7034. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7035. */
  7036. function Curve3(points) {
  7037. this._length = 0.0;
  7038. this._points = points;
  7039. this._length = this._computeLength(points);
  7040. }
  7041. /**
  7042. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7043. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7044. * @param v1 (Vector3) the control point
  7045. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7046. * @param nbPoints (integer) the wanted number of points in the curve
  7047. */
  7048. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7049. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7050. var bez = new Array();
  7051. var equation = function (t, val0, val1, val2) {
  7052. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7053. return res;
  7054. };
  7055. for (var i = 0; i <= nbPoints; i++) {
  7056. 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)));
  7057. }
  7058. return new Curve3(bez);
  7059. };
  7060. /**
  7061. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7062. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7063. * @param v1 (Vector3) the first control point
  7064. * @param v2 (Vector3) the second control point
  7065. * @param v3 (Vector3) the end point of the Cubic Bezier
  7066. * @param nbPoints (integer) the wanted number of points in the curve
  7067. */
  7068. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7069. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7070. var bez = new Array();
  7071. var equation = function (t, val0, val1, val2, val3) {
  7072. 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;
  7073. return res;
  7074. };
  7075. for (var i = 0; i <= nbPoints; i++) {
  7076. 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)));
  7077. }
  7078. return new Curve3(bez);
  7079. };
  7080. /**
  7081. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7082. * @param p1 (Vector3) the origin point of the Hermite Spline
  7083. * @param t1 (Vector3) the tangent vector at the origin point
  7084. * @param p2 (Vector3) the end point of the Hermite Spline
  7085. * @param t2 (Vector3) the tangent vector at the end point
  7086. * @param nbPoints (integer) the wanted number of points in the curve
  7087. */
  7088. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7089. var hermite = new Array();
  7090. var step = 1.0 / nbPoints;
  7091. for (var i = 0; i <= nbPoints; i++) {
  7092. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7093. }
  7094. return new Curve3(hermite);
  7095. };
  7096. /**
  7097. * Returns a Curve3 object along a CatmullRom Spline curve :
  7098. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7099. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7100. */
  7101. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7102. var totalPoints = new Array();
  7103. totalPoints.push(points[0].clone());
  7104. Array.prototype.push.apply(totalPoints, points);
  7105. totalPoints.push(points[points.length - 1].clone());
  7106. var catmullRom = new Array();
  7107. var step = 1.0 / nbPoints;
  7108. var amount = 0.0;
  7109. for (var i = 0; i < totalPoints.length - 3; i++) {
  7110. amount = 0;
  7111. for (var c = 0; c < nbPoints; c++) {
  7112. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7113. amount += step;
  7114. }
  7115. }
  7116. i--;
  7117. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7118. return new Curve3(catmullRom);
  7119. };
  7120. /**
  7121. * Returns the Curve3 stored array of successive Vector3
  7122. */
  7123. Curve3.prototype.getPoints = function () {
  7124. return this._points;
  7125. };
  7126. /**
  7127. * Returns the computed length (float) of the curve.
  7128. */
  7129. Curve3.prototype.length = function () {
  7130. return this._length;
  7131. };
  7132. /**
  7133. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7134. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7135. * curveA and curveB keep unchanged.
  7136. */
  7137. Curve3.prototype.continue = function (curve) {
  7138. var lastPoint = this._points[this._points.length - 1];
  7139. var continuedPoints = this._points.slice();
  7140. var curvePoints = curve.getPoints();
  7141. for (var i = 1; i < curvePoints.length; i++) {
  7142. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7143. }
  7144. var continuedCurve = new Curve3(continuedPoints);
  7145. return continuedCurve;
  7146. };
  7147. Curve3.prototype._computeLength = function (path) {
  7148. var l = 0;
  7149. for (var i = 1; i < path.length; i++) {
  7150. l += (path[i].subtract(path[i - 1])).length();
  7151. }
  7152. return l;
  7153. };
  7154. return Curve3;
  7155. }());
  7156. BABYLON.Curve3 = Curve3;
  7157. // Vertex formats
  7158. var PositionNormalVertex = /** @class */ (function () {
  7159. function PositionNormalVertex(position, normal) {
  7160. if (position === void 0) { position = Vector3.Zero(); }
  7161. if (normal === void 0) { normal = Vector3.Up(); }
  7162. this.position = position;
  7163. this.normal = normal;
  7164. }
  7165. PositionNormalVertex.prototype.clone = function () {
  7166. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7167. };
  7168. return PositionNormalVertex;
  7169. }());
  7170. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7171. var PositionNormalTextureVertex = /** @class */ (function () {
  7172. function PositionNormalTextureVertex(position, normal, uv) {
  7173. if (position === void 0) { position = Vector3.Zero(); }
  7174. if (normal === void 0) { normal = Vector3.Up(); }
  7175. if (uv === void 0) { uv = Vector2.Zero(); }
  7176. this.position = position;
  7177. this.normal = normal;
  7178. this.uv = uv;
  7179. }
  7180. PositionNormalTextureVertex.prototype.clone = function () {
  7181. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7182. };
  7183. return PositionNormalTextureVertex;
  7184. }());
  7185. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7186. // Temporary pre-allocated objects for engine internal use
  7187. // usage in any internal function :
  7188. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7189. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7190. var Tmp = /** @class */ (function () {
  7191. function Tmp() {
  7192. }
  7193. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7194. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7195. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7196. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7197. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7198. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7199. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7200. Matrix.Zero(), Matrix.Zero(),
  7201. Matrix.Zero(), Matrix.Zero(),
  7202. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7203. return Tmp;
  7204. }());
  7205. BABYLON.Tmp = Tmp;
  7206. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7207. var MathTmp = /** @class */ (function () {
  7208. function MathTmp() {
  7209. }
  7210. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7211. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7212. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7213. return MathTmp;
  7214. }());
  7215. })(BABYLON || (BABYLON = {}));
  7216. //# sourceMappingURL=babylon.math.js.map
  7217. "use strict";
  7218. var BABYLON;
  7219. (function (BABYLON) {
  7220. var Scalar = /** @class */ (function () {
  7221. function Scalar() {
  7222. }
  7223. /**
  7224. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7225. */
  7226. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7227. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7228. var num = a - b;
  7229. return -epsilon <= num && num <= epsilon;
  7230. };
  7231. /**
  7232. * Returns a string : the upper case translation of the number i to hexadecimal.
  7233. */
  7234. Scalar.ToHex = function (i) {
  7235. var str = i.toString(16);
  7236. if (i <= 15) {
  7237. return ("0" + str).toUpperCase();
  7238. }
  7239. return str.toUpperCase();
  7240. };
  7241. /**
  7242. * Returns -1 if value is negative and +1 is value is positive.
  7243. * Returns the value itself if it's equal to zero.
  7244. */
  7245. Scalar.Sign = function (value) {
  7246. value = +value; // convert to a number
  7247. if (value === 0 || isNaN(value))
  7248. return value;
  7249. return value > 0 ? 1 : -1;
  7250. };
  7251. /**
  7252. * Returns the value itself if it's between min and max.
  7253. * Returns min if the value is lower than min.
  7254. * Returns max if the value is greater than max.
  7255. */
  7256. Scalar.Clamp = function (value, min, max) {
  7257. if (min === void 0) { min = 0; }
  7258. if (max === void 0) { max = 1; }
  7259. return Math.min(max, Math.max(min, value));
  7260. };
  7261. /**
  7262. * Returns the log2 of value.
  7263. */
  7264. Scalar.Log2 = function (value) {
  7265. return Math.log(value) * Math.LOG2E;
  7266. };
  7267. /**
  7268. * Loops the value, so that it is never larger than length and never smaller than 0.
  7269. *
  7270. * This is similar to the modulo operator but it works with floating point numbers.
  7271. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7272. * With t = 5 and length = 2.5, the result would be 0.0.
  7273. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7274. */
  7275. Scalar.Repeat = function (value, length) {
  7276. return value - Math.floor(value / length) * length;
  7277. };
  7278. /**
  7279. * Normalize the value between 0.0 and 1.0 using min and max values
  7280. */
  7281. Scalar.Normalize = function (value, min, max) {
  7282. return (value - min) / (max - min);
  7283. };
  7284. /**
  7285. * Denormalize the value from 0.0 and 1.0 using min and max values
  7286. */
  7287. Scalar.Denormalize = function (normalized, min, max) {
  7288. return (normalized * (max - min) + min);
  7289. };
  7290. /**
  7291. * Calculates the shortest difference between two given angles given in degrees.
  7292. */
  7293. Scalar.DeltaAngle = function (current, target) {
  7294. var num = Scalar.Repeat(target - current, 360.0);
  7295. if (num > 180.0) {
  7296. num -= 360.0;
  7297. }
  7298. return num;
  7299. };
  7300. /**
  7301. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7302. *
  7303. * The returned value will move back and forth between 0 and length
  7304. */
  7305. Scalar.PingPong = function (tx, length) {
  7306. var t = Scalar.Repeat(tx, length * 2.0);
  7307. return length - Math.abs(t - length);
  7308. };
  7309. /**
  7310. * Interpolates between min and max with smoothing at the limits.
  7311. *
  7312. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7313. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7314. */
  7315. Scalar.SmoothStep = function (from, to, tx) {
  7316. var t = Scalar.Clamp(tx);
  7317. t = -2.0 * t * t * t + 3.0 * t * t;
  7318. return to * t + from * (1.0 - t);
  7319. };
  7320. /**
  7321. * Moves a value current towards target.
  7322. *
  7323. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7324. * Negative values of maxDelta pushes the value away from target.
  7325. */
  7326. Scalar.MoveTowards = function (current, target, maxDelta) {
  7327. var result = 0;
  7328. if (Math.abs(target - current) <= maxDelta) {
  7329. result = target;
  7330. }
  7331. else {
  7332. result = current + Scalar.Sign(target - current) * maxDelta;
  7333. }
  7334. return result;
  7335. };
  7336. /**
  7337. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7338. *
  7339. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7340. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7341. */
  7342. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7343. var num = Scalar.DeltaAngle(current, target);
  7344. var result = 0;
  7345. if (-maxDelta < num && num < maxDelta) {
  7346. result = target;
  7347. }
  7348. else {
  7349. target = current + num;
  7350. result = Scalar.MoveTowards(current, target, maxDelta);
  7351. }
  7352. return result;
  7353. };
  7354. /**
  7355. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7356. */
  7357. Scalar.Lerp = function (start, end, amount) {
  7358. return start + ((end - start) * amount);
  7359. };
  7360. /**
  7361. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7362. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7363. */
  7364. Scalar.LerpAngle = function (start, end, amount) {
  7365. var num = Scalar.Repeat(end - start, 360.0);
  7366. if (num > 180.0) {
  7367. num -= 360.0;
  7368. }
  7369. return start + num * Scalar.Clamp(amount);
  7370. };
  7371. /**
  7372. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7373. */
  7374. Scalar.InverseLerp = function (a, b, value) {
  7375. var result = 0;
  7376. if (a != b) {
  7377. result = Scalar.Clamp((value - a) / (b - a));
  7378. }
  7379. else {
  7380. result = 0.0;
  7381. }
  7382. return result;
  7383. };
  7384. /**
  7385. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7386. */
  7387. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7388. var squared = amount * amount;
  7389. var cubed = amount * squared;
  7390. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7391. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7392. var part3 = (cubed - (2.0 * squared)) + amount;
  7393. var part4 = cubed - squared;
  7394. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7395. };
  7396. /**
  7397. * Returns a random float number between and min and max values
  7398. */
  7399. Scalar.RandomRange = function (min, max) {
  7400. if (min === max)
  7401. return min;
  7402. return ((Math.random() * (max - min)) + min);
  7403. };
  7404. /**
  7405. * This function returns percentage of a number in a given range.
  7406. *
  7407. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7408. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7409. */
  7410. Scalar.RangeToPercent = function (number, min, max) {
  7411. return ((number - min) / (max - min));
  7412. };
  7413. /**
  7414. * This function returns number that corresponds to the percentage in a given range.
  7415. *
  7416. * PercentToRange(0.34,0,100) will return 34.
  7417. */
  7418. Scalar.PercentToRange = function (percent, min, max) {
  7419. return ((max - min) * percent + min);
  7420. };
  7421. /**
  7422. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7423. * @param angle The angle to normalize in radian.
  7424. * @return The converted angle.
  7425. */
  7426. Scalar.NormalizeRadians = function (angle) {
  7427. // More precise but slower version kept for reference.
  7428. // angle = angle % Tools.TwoPi;
  7429. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7430. //if (angle > Math.PI) {
  7431. // angle -= Tools.TwoPi;
  7432. //}
  7433. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7434. return angle;
  7435. };
  7436. /**
  7437. * Two pi constants convenient for computation.
  7438. */
  7439. Scalar.TwoPi = Math.PI * 2;
  7440. return Scalar;
  7441. }());
  7442. BABYLON.Scalar = Scalar;
  7443. })(BABYLON || (BABYLON = {}));
  7444. //# sourceMappingURL=babylon.math.scalar.js.map
  7445. "use strict";
  7446. //# sourceMappingURL=babylon.mixins.js.map
  7447. "use strict";
  7448. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7449. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7450. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7451. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7452. //# sourceMappingURL=babylon.webgl2.js.map
  7453. "use strict";
  7454. var BABYLON;
  7455. (function (BABYLON) {
  7456. var __decoratorInitialStore = {};
  7457. var __mergedStore = {};
  7458. var _copySource = function (creationFunction, source, instanciate) {
  7459. var destination = creationFunction();
  7460. // Tags
  7461. if (BABYLON.Tags) {
  7462. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7463. }
  7464. var classStore = getMergedStore(destination);
  7465. // Properties
  7466. for (var property in classStore) {
  7467. var propertyDescriptor = classStore[property];
  7468. var sourceProperty = source[property];
  7469. var propertyType = propertyDescriptor.type;
  7470. if (sourceProperty !== undefined && sourceProperty !== null) {
  7471. switch (propertyType) {
  7472. case 0: // Value
  7473. case 6: // Mesh reference
  7474. case 11:// Camera reference
  7475. destination[property] = sourceProperty;
  7476. break;
  7477. case 1:// Texture
  7478. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7479. break;
  7480. case 2: // Color3
  7481. case 3: // FresnelParameters
  7482. case 4: // Vector2
  7483. case 5: // Vector3
  7484. case 7: // Color Curves
  7485. case 10:// Quaternion
  7486. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7487. break;
  7488. }
  7489. }
  7490. }
  7491. return destination;
  7492. };
  7493. function getDirectStore(target) {
  7494. var classKey = target.getClassName();
  7495. if (!__decoratorInitialStore[classKey]) {
  7496. __decoratorInitialStore[classKey] = {};
  7497. }
  7498. return __decoratorInitialStore[classKey];
  7499. }
  7500. /**
  7501. * Return the list of properties flagged as serializable
  7502. * @param target: host object
  7503. */
  7504. function getMergedStore(target) {
  7505. var classKey = target.getClassName();
  7506. if (__mergedStore[classKey]) {
  7507. return __mergedStore[classKey];
  7508. }
  7509. __mergedStore[classKey] = {};
  7510. var store = __mergedStore[classKey];
  7511. var currentTarget = target;
  7512. var currentKey = classKey;
  7513. while (currentKey) {
  7514. var initialStore = __decoratorInitialStore[currentKey];
  7515. for (var property in initialStore) {
  7516. store[property] = initialStore[property];
  7517. }
  7518. var parent_1 = void 0;
  7519. var done = false;
  7520. do {
  7521. parent_1 = Object.getPrototypeOf(currentTarget);
  7522. if (!parent_1.getClassName) {
  7523. done = true;
  7524. break;
  7525. }
  7526. if (parent_1.getClassName() !== currentKey) {
  7527. break;
  7528. }
  7529. currentTarget = parent_1;
  7530. } while (parent_1);
  7531. if (done) {
  7532. break;
  7533. }
  7534. currentKey = parent_1.getClassName();
  7535. currentTarget = parent_1;
  7536. }
  7537. return store;
  7538. }
  7539. function generateSerializableMember(type, sourceName) {
  7540. return function (target, propertyKey) {
  7541. var classStore = getDirectStore(target);
  7542. if (!classStore[propertyKey]) {
  7543. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7544. }
  7545. };
  7546. }
  7547. function generateExpandMember(setCallback, targetKey) {
  7548. if (targetKey === void 0) { targetKey = null; }
  7549. return function (target, propertyKey) {
  7550. var key = targetKey || ("_" + propertyKey);
  7551. Object.defineProperty(target, propertyKey, {
  7552. get: function () {
  7553. return this[key];
  7554. },
  7555. set: function (value) {
  7556. if (this[key] === value) {
  7557. return;
  7558. }
  7559. this[key] = value;
  7560. target[setCallback].apply(this);
  7561. },
  7562. enumerable: true,
  7563. configurable: true
  7564. });
  7565. };
  7566. }
  7567. function expandToProperty(callback, targetKey) {
  7568. if (targetKey === void 0) { targetKey = null; }
  7569. return generateExpandMember(callback, targetKey);
  7570. }
  7571. BABYLON.expandToProperty = expandToProperty;
  7572. function serialize(sourceName) {
  7573. return generateSerializableMember(0, sourceName); // value member
  7574. }
  7575. BABYLON.serialize = serialize;
  7576. function serializeAsTexture(sourceName) {
  7577. return generateSerializableMember(1, sourceName); // texture member
  7578. }
  7579. BABYLON.serializeAsTexture = serializeAsTexture;
  7580. function serializeAsColor3(sourceName) {
  7581. return generateSerializableMember(2, sourceName); // color3 member
  7582. }
  7583. BABYLON.serializeAsColor3 = serializeAsColor3;
  7584. function serializeAsFresnelParameters(sourceName) {
  7585. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7586. }
  7587. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7588. function serializeAsVector2(sourceName) {
  7589. return generateSerializableMember(4, sourceName); // vector2 member
  7590. }
  7591. BABYLON.serializeAsVector2 = serializeAsVector2;
  7592. function serializeAsVector3(sourceName) {
  7593. return generateSerializableMember(5, sourceName); // vector3 member
  7594. }
  7595. BABYLON.serializeAsVector3 = serializeAsVector3;
  7596. function serializeAsMeshReference(sourceName) {
  7597. return generateSerializableMember(6, sourceName); // mesh reference member
  7598. }
  7599. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7600. function serializeAsColorCurves(sourceName) {
  7601. return generateSerializableMember(7, sourceName); // color curves
  7602. }
  7603. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7604. function serializeAsColor4(sourceName) {
  7605. return generateSerializableMember(8, sourceName); // color 4
  7606. }
  7607. BABYLON.serializeAsColor4 = serializeAsColor4;
  7608. function serializeAsImageProcessingConfiguration(sourceName) {
  7609. return generateSerializableMember(9, sourceName); // image processing
  7610. }
  7611. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7612. function serializeAsQuaternion(sourceName) {
  7613. return generateSerializableMember(10, sourceName); // quaternion member
  7614. }
  7615. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7616. /**
  7617. * Decorator used to define property that can be serialized as reference to a camera
  7618. * @param sourceName defines the name of the property to decorate
  7619. */
  7620. function serializeAsCameraReference(sourceName) {
  7621. return generateSerializableMember(11, sourceName); // camera reference member
  7622. }
  7623. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7624. var SerializationHelper = /** @class */ (function () {
  7625. function SerializationHelper() {
  7626. }
  7627. SerializationHelper.Serialize = function (entity, serializationObject) {
  7628. if (!serializationObject) {
  7629. serializationObject = {};
  7630. }
  7631. // Tags
  7632. if (BABYLON.Tags) {
  7633. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7634. }
  7635. var serializedProperties = getMergedStore(entity);
  7636. // Properties
  7637. for (var property in serializedProperties) {
  7638. var propertyDescriptor = serializedProperties[property];
  7639. var targetPropertyName = propertyDescriptor.sourceName || property;
  7640. var propertyType = propertyDescriptor.type;
  7641. var sourceProperty = entity[property];
  7642. if (sourceProperty !== undefined && sourceProperty !== null) {
  7643. switch (propertyType) {
  7644. case 0:// Value
  7645. serializationObject[targetPropertyName] = sourceProperty;
  7646. break;
  7647. case 1:// Texture
  7648. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7649. break;
  7650. case 2:// Color3
  7651. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7652. break;
  7653. case 3:// FresnelParameters
  7654. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7655. break;
  7656. case 4:// Vector2
  7657. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7658. break;
  7659. case 5:// Vector3
  7660. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7661. break;
  7662. case 6:// Mesh reference
  7663. serializationObject[targetPropertyName] = sourceProperty.id;
  7664. break;
  7665. case 7:// Color Curves
  7666. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7667. break;
  7668. case 8:// Color 4
  7669. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7670. break;
  7671. case 9:// Image Processing
  7672. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7673. break;
  7674. case 10:// Quaternion
  7675. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7676. break;
  7677. case 11:// Camera reference
  7678. serializationObject[targetPropertyName] = sourceProperty.id;
  7679. break;
  7680. }
  7681. }
  7682. }
  7683. return serializationObject;
  7684. };
  7685. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7686. if (rootUrl === void 0) { rootUrl = null; }
  7687. var destination = creationFunction();
  7688. if (!rootUrl) {
  7689. rootUrl = "";
  7690. }
  7691. // Tags
  7692. if (BABYLON.Tags) {
  7693. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7694. }
  7695. var classStore = getMergedStore(destination);
  7696. // Properties
  7697. for (var property in classStore) {
  7698. var propertyDescriptor = classStore[property];
  7699. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7700. var propertyType = propertyDescriptor.type;
  7701. if (sourceProperty !== undefined && sourceProperty !== null) {
  7702. var dest = destination;
  7703. switch (propertyType) {
  7704. case 0:// Value
  7705. dest[property] = sourceProperty;
  7706. break;
  7707. case 1:// Texture
  7708. if (scene) {
  7709. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7710. }
  7711. break;
  7712. case 2:// Color3
  7713. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7714. break;
  7715. case 3:// FresnelParameters
  7716. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7717. break;
  7718. case 4:// Vector2
  7719. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7720. break;
  7721. case 5:// Vector3
  7722. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7723. break;
  7724. case 6:// Mesh reference
  7725. if (scene) {
  7726. dest[property] = scene.getLastMeshByID(sourceProperty);
  7727. }
  7728. break;
  7729. case 7:// Color Curves
  7730. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7731. break;
  7732. case 8:// Color 4
  7733. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7734. break;
  7735. case 9:// Image Processing
  7736. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7737. break;
  7738. case 10:// Quaternion
  7739. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7740. break;
  7741. case 11:// Camera reference
  7742. if (scene) {
  7743. dest[property] = scene.getCameraByID(sourceProperty);
  7744. }
  7745. break;
  7746. }
  7747. }
  7748. }
  7749. return destination;
  7750. };
  7751. SerializationHelper.Clone = function (creationFunction, source) {
  7752. return _copySource(creationFunction, source, false);
  7753. };
  7754. SerializationHelper.Instanciate = function (creationFunction, source) {
  7755. return _copySource(creationFunction, source, true);
  7756. };
  7757. return SerializationHelper;
  7758. }());
  7759. BABYLON.SerializationHelper = SerializationHelper;
  7760. })(BABYLON || (BABYLON = {}));
  7761. //# sourceMappingURL=babylon.decorators.js.map
  7762. "use strict";
  7763. var BABYLON;
  7764. (function (BABYLON) {
  7765. /**
  7766. * Wrapper class for promise with external resolve and reject.
  7767. */
  7768. var Deferred = /** @class */ (function () {
  7769. /**
  7770. * Constructor for this deferred object.
  7771. */
  7772. function Deferred() {
  7773. var _this = this;
  7774. this.promise = new Promise(function (resolve, reject) {
  7775. _this._resolve = resolve;
  7776. _this._reject = reject;
  7777. });
  7778. }
  7779. Object.defineProperty(Deferred.prototype, "resolve", {
  7780. /**
  7781. * The resolve method of the promise associated with this deferred object.
  7782. */
  7783. get: function () {
  7784. return this._resolve;
  7785. },
  7786. enumerable: true,
  7787. configurable: true
  7788. });
  7789. Object.defineProperty(Deferred.prototype, "reject", {
  7790. /**
  7791. * The reject method of the promise associated with this deferred object.
  7792. */
  7793. get: function () {
  7794. return this._reject;
  7795. },
  7796. enumerable: true,
  7797. configurable: true
  7798. });
  7799. return Deferred;
  7800. }());
  7801. BABYLON.Deferred = Deferred;
  7802. })(BABYLON || (BABYLON = {}));
  7803. //# sourceMappingURL=babylon.deferred.js.map
  7804. "use strict";
  7805. var BABYLON;
  7806. (function (BABYLON) {
  7807. /**
  7808. * A class serves as a medium between the observable and its observers
  7809. */
  7810. var EventState = /** @class */ (function () {
  7811. /**
  7812. * Create a new EventState
  7813. * @param mask defines the mask associated with this state
  7814. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7815. * @param target defines the original target of the state
  7816. * @param currentTarget defines the current target of the state
  7817. */
  7818. function EventState(mask, skipNextObservers, target, currentTarget) {
  7819. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7820. this.initalize(mask, skipNextObservers, target, currentTarget);
  7821. }
  7822. /**
  7823. * Initialize the current event state
  7824. * @param mask defines the mask associated with this state
  7825. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7826. * @param target defines the original target of the state
  7827. * @param currentTarget defines the current target of the state
  7828. * @returns the current event state
  7829. */
  7830. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7831. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7832. this.mask = mask;
  7833. this.skipNextObservers = skipNextObservers;
  7834. this.target = target;
  7835. this.currentTarget = currentTarget;
  7836. return this;
  7837. };
  7838. return EventState;
  7839. }());
  7840. BABYLON.EventState = EventState;
  7841. /**
  7842. * Represent an Observer registered to a given Observable object.
  7843. */
  7844. var Observer = /** @class */ (function () {
  7845. /**
  7846. * Creates a new observer
  7847. * @param callback defines the callback to call when the observer is notified
  7848. * @param mask defines the mask of the observer (used to filter notifications)
  7849. * @param scope defines the current scope used to restore the JS context
  7850. */
  7851. function Observer(
  7852. /**
  7853. * Defines the callback to call when the observer is notified
  7854. */
  7855. callback,
  7856. /**
  7857. * Defines the mask of the observer (used to filter notifications)
  7858. */
  7859. mask,
  7860. /**
  7861. * Defines the current scope used to restore the JS context
  7862. */
  7863. scope) {
  7864. if (scope === void 0) { scope = null; }
  7865. this.callback = callback;
  7866. this.mask = mask;
  7867. this.scope = scope;
  7868. /** @ignore */
  7869. this._willBeUnregistered = false;
  7870. /**
  7871. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7872. */
  7873. this.unregisterOnNextCall = false;
  7874. }
  7875. return Observer;
  7876. }());
  7877. BABYLON.Observer = Observer;
  7878. /**
  7879. * Represent a list of observers registered to multiple Observables object.
  7880. */
  7881. var MultiObserver = /** @class */ (function () {
  7882. function MultiObserver() {
  7883. }
  7884. /**
  7885. * Release associated resources
  7886. */
  7887. MultiObserver.prototype.dispose = function () {
  7888. if (this._observers && this._observables) {
  7889. for (var index = 0; index < this._observers.length; index++) {
  7890. this._observables[index].remove(this._observers[index]);
  7891. }
  7892. }
  7893. this._observers = null;
  7894. this._observables = null;
  7895. };
  7896. /**
  7897. * Raise a callback when one of the observable will notify
  7898. * @param observables defines a list of observables to watch
  7899. * @param callback defines the callback to call on notification
  7900. * @param mask defines the mask used to filter notifications
  7901. * @param scope defines the current scope used to restore the JS context
  7902. * @returns the new MultiObserver
  7903. */
  7904. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7905. if (mask === void 0) { mask = -1; }
  7906. if (scope === void 0) { scope = null; }
  7907. var result = new MultiObserver();
  7908. result._observers = new Array();
  7909. result._observables = observables;
  7910. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7911. var observable = observables_1[_i];
  7912. var observer = observable.add(callback, mask, false, scope);
  7913. if (observer) {
  7914. result._observers.push(observer);
  7915. }
  7916. }
  7917. return result;
  7918. };
  7919. return MultiObserver;
  7920. }());
  7921. BABYLON.MultiObserver = MultiObserver;
  7922. /**
  7923. * The Observable class is a simple implementation of the Observable pattern.
  7924. *
  7925. * 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.
  7926. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7927. * 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).
  7928. * 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.
  7929. */
  7930. var Observable = /** @class */ (function () {
  7931. /**
  7932. * Creates a new observable
  7933. * @param onObserverAdded defines a callback to call when a new observer is added
  7934. */
  7935. function Observable(onObserverAdded) {
  7936. this._observers = new Array();
  7937. this._eventState = new EventState(0);
  7938. if (onObserverAdded) {
  7939. this._onObserverAdded = onObserverAdded;
  7940. }
  7941. }
  7942. /**
  7943. * Create a new Observer with the specified callback
  7944. * @param callback the callback that will be executed for that Observer
  7945. * @param mask the mask used to filter observers
  7946. * @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.
  7947. * @param scope optional scope for the callback to be called from
  7948. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7949. * @returns the new observer created for the callback
  7950. */
  7951. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7952. if (mask === void 0) { mask = -1; }
  7953. if (insertFirst === void 0) { insertFirst = false; }
  7954. if (scope === void 0) { scope = null; }
  7955. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7956. if (!callback) {
  7957. return null;
  7958. }
  7959. var observer = new Observer(callback, mask, scope);
  7960. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7961. if (insertFirst) {
  7962. this._observers.unshift(observer);
  7963. }
  7964. else {
  7965. this._observers.push(observer);
  7966. }
  7967. if (this._onObserverAdded) {
  7968. this._onObserverAdded(observer);
  7969. }
  7970. return observer;
  7971. };
  7972. /**
  7973. * Remove an Observer from the Observable object
  7974. * @param observer the instance of the Observer to remove
  7975. * @returns false if it doesn't belong to this Observable
  7976. */
  7977. Observable.prototype.remove = function (observer) {
  7978. if (!observer) {
  7979. return false;
  7980. }
  7981. var index = this._observers.indexOf(observer);
  7982. if (index !== -1) {
  7983. this._observers.splice(index, 1);
  7984. return true;
  7985. }
  7986. return false;
  7987. };
  7988. /**
  7989. * Remove a callback from the Observable object
  7990. * @param callback the callback to remove
  7991. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7992. * @returns false if it doesn't belong to this Observable
  7993. */
  7994. Observable.prototype.removeCallback = function (callback, scope) {
  7995. for (var index = 0; index < this._observers.length; index++) {
  7996. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7997. this._observers.splice(index, 1);
  7998. return true;
  7999. }
  8000. }
  8001. return false;
  8002. };
  8003. Observable.prototype._deferUnregister = function (observer) {
  8004. var _this = this;
  8005. observer.unregisterOnNextCall = false;
  8006. observer._willBeUnregistered = true;
  8007. BABYLON.Tools.SetImmediate(function () {
  8008. _this.remove(observer);
  8009. });
  8010. };
  8011. /**
  8012. * Notify all Observers by calling their respective callback with the given data
  8013. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8014. * @param eventData defines the data to send to all observers
  8015. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8016. * @param target defines the original target of the state
  8017. * @param currentTarget defines the current target of the state
  8018. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8019. */
  8020. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8021. if (mask === void 0) { mask = -1; }
  8022. if (!this._observers.length) {
  8023. return true;
  8024. }
  8025. var state = this._eventState;
  8026. state.mask = mask;
  8027. state.target = target;
  8028. state.currentTarget = currentTarget;
  8029. state.skipNextObservers = false;
  8030. state.lastReturnValue = eventData;
  8031. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8032. var obs = _a[_i];
  8033. if (obs._willBeUnregistered) {
  8034. continue;
  8035. }
  8036. if (obs.mask & mask) {
  8037. if (obs.scope) {
  8038. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8039. }
  8040. else {
  8041. state.lastReturnValue = obs.callback(eventData, state);
  8042. }
  8043. if (obs.unregisterOnNextCall) {
  8044. this._deferUnregister(obs);
  8045. }
  8046. }
  8047. if (state.skipNextObservers) {
  8048. return false;
  8049. }
  8050. }
  8051. return true;
  8052. };
  8053. /**
  8054. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8055. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8056. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8057. * and it is crucial that all callbacks will be executed.
  8058. * The order of the callbacks is kept, callbacks are not executed parallel.
  8059. *
  8060. * @param eventData The data to be sent to each callback
  8061. * @param mask is used to filter observers defaults to -1
  8062. * @param target defines the callback target (see EventState)
  8063. * @param currentTarget defines he current object in the bubbling phase
  8064. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8065. */
  8066. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8067. var _this = this;
  8068. if (mask === void 0) { mask = -1; }
  8069. // create an empty promise
  8070. var p = Promise.resolve(eventData);
  8071. // no observers? return this promise.
  8072. if (!this._observers.length) {
  8073. return p;
  8074. }
  8075. var state = this._eventState;
  8076. state.mask = mask;
  8077. state.target = target;
  8078. state.currentTarget = currentTarget;
  8079. state.skipNextObservers = false;
  8080. // execute one callback after another (not using Promise.all, the order is important)
  8081. this._observers.forEach(function (obs) {
  8082. if (state.skipNextObservers) {
  8083. return;
  8084. }
  8085. if (obs._willBeUnregistered) {
  8086. return;
  8087. }
  8088. if (obs.mask & mask) {
  8089. if (obs.scope) {
  8090. p = p.then(function (lastReturnedValue) {
  8091. state.lastReturnValue = lastReturnedValue;
  8092. return obs.callback.apply(obs.scope, [eventData, state]);
  8093. });
  8094. }
  8095. else {
  8096. p = p.then(function (lastReturnedValue) {
  8097. state.lastReturnValue = lastReturnedValue;
  8098. return obs.callback(eventData, state);
  8099. });
  8100. }
  8101. if (obs.unregisterOnNextCall) {
  8102. _this._deferUnregister(obs);
  8103. }
  8104. }
  8105. });
  8106. // return the eventData
  8107. return p.then(function () { return eventData; });
  8108. };
  8109. /**
  8110. * Notify a specific observer
  8111. * @param observer defines the observer to notify
  8112. * @param eventData defines the data to be sent to each callback
  8113. * @param mask is used to filter observers defaults to -1
  8114. */
  8115. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8116. if (mask === void 0) { mask = -1; }
  8117. var state = this._eventState;
  8118. state.mask = mask;
  8119. state.skipNextObservers = false;
  8120. observer.callback(eventData, state);
  8121. };
  8122. /**
  8123. * Gets a boolean indicating if the observable has at least one observer
  8124. * @returns true is the Observable has at least one Observer registered
  8125. */
  8126. Observable.prototype.hasObservers = function () {
  8127. return this._observers.length > 0;
  8128. };
  8129. /**
  8130. * Clear the list of observers
  8131. */
  8132. Observable.prototype.clear = function () {
  8133. this._observers = new Array();
  8134. this._onObserverAdded = null;
  8135. };
  8136. /**
  8137. * Clone the current observable
  8138. * @returns a new observable
  8139. */
  8140. Observable.prototype.clone = function () {
  8141. var result = new Observable();
  8142. result._observers = this._observers.slice(0);
  8143. return result;
  8144. };
  8145. /**
  8146. * Does this observable handles observer registered with a given mask
  8147. * @param mask defines the mask to be tested
  8148. * @return whether or not one observer registered with the given mask is handeled
  8149. **/
  8150. Observable.prototype.hasSpecificMask = function (mask) {
  8151. if (mask === void 0) { mask = -1; }
  8152. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8153. var obs = _a[_i];
  8154. if (obs.mask & mask || obs.mask === mask) {
  8155. return true;
  8156. }
  8157. }
  8158. return false;
  8159. };
  8160. return Observable;
  8161. }());
  8162. BABYLON.Observable = Observable;
  8163. })(BABYLON || (BABYLON = {}));
  8164. //# sourceMappingURL=babylon.observable.js.map
  8165. "use strict";
  8166. var BABYLON;
  8167. (function (BABYLON) {
  8168. var SmartArray = /** @class */ (function () {
  8169. function SmartArray(capacity) {
  8170. this.length = 0;
  8171. this.data = new Array(capacity);
  8172. this._id = SmartArray._GlobalId++;
  8173. }
  8174. SmartArray.prototype.push = function (value) {
  8175. this.data[this.length++] = value;
  8176. if (this.length > this.data.length) {
  8177. this.data.length *= 2;
  8178. }
  8179. };
  8180. SmartArray.prototype.forEach = function (func) {
  8181. for (var index = 0; index < this.length; index++) {
  8182. func(this.data[index]);
  8183. }
  8184. };
  8185. SmartArray.prototype.sort = function (compareFn) {
  8186. this.data.sort(compareFn);
  8187. };
  8188. SmartArray.prototype.reset = function () {
  8189. this.length = 0;
  8190. };
  8191. SmartArray.prototype.dispose = function () {
  8192. this.reset();
  8193. if (this.data) {
  8194. this.data.length = 0;
  8195. this.data = [];
  8196. }
  8197. };
  8198. SmartArray.prototype.concat = function (array) {
  8199. if (array.length === 0) {
  8200. return;
  8201. }
  8202. if (this.length + array.length > this.data.length) {
  8203. this.data.length = (this.length + array.length) * 2;
  8204. }
  8205. for (var index = 0; index < array.length; index++) {
  8206. this.data[this.length++] = (array.data || array)[index];
  8207. }
  8208. };
  8209. SmartArray.prototype.indexOf = function (value) {
  8210. var position = this.data.indexOf(value);
  8211. if (position >= this.length) {
  8212. return -1;
  8213. }
  8214. return position;
  8215. };
  8216. SmartArray.prototype.contains = function (value) {
  8217. return this.data.indexOf(value) !== -1;
  8218. };
  8219. // Statics
  8220. SmartArray._GlobalId = 0;
  8221. return SmartArray;
  8222. }());
  8223. BABYLON.SmartArray = SmartArray;
  8224. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8225. __extends(SmartArrayNoDuplicate, _super);
  8226. function SmartArrayNoDuplicate() {
  8227. var _this = _super !== null && _super.apply(this, arguments) || this;
  8228. _this._duplicateId = 0;
  8229. return _this;
  8230. }
  8231. SmartArrayNoDuplicate.prototype.push = function (value) {
  8232. _super.prototype.push.call(this, value);
  8233. if (!value.__smartArrayFlags) {
  8234. value.__smartArrayFlags = {};
  8235. }
  8236. value.__smartArrayFlags[this._id] = this._duplicateId;
  8237. };
  8238. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8239. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8240. return false;
  8241. }
  8242. this.push(value);
  8243. return true;
  8244. };
  8245. SmartArrayNoDuplicate.prototype.reset = function () {
  8246. _super.prototype.reset.call(this);
  8247. this._duplicateId++;
  8248. };
  8249. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8250. if (array.length === 0) {
  8251. return;
  8252. }
  8253. if (this.length + array.length > this.data.length) {
  8254. this.data.length = (this.length + array.length) * 2;
  8255. }
  8256. for (var index = 0; index < array.length; index++) {
  8257. var item = (array.data || array)[index];
  8258. this.pushNoDuplicate(item);
  8259. }
  8260. };
  8261. return SmartArrayNoDuplicate;
  8262. }(SmartArray));
  8263. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8264. })(BABYLON || (BABYLON = {}));
  8265. //# sourceMappingURL=babylon.smartArray.js.map
  8266. "use strict";
  8267. var BABYLON;
  8268. (function (BABYLON) {
  8269. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8270. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8271. var LoadFileError = /** @class */ (function (_super) {
  8272. __extends(LoadFileError, _super);
  8273. function LoadFileError(message, request) {
  8274. var _this = _super.call(this, message) || this;
  8275. _this.request = request;
  8276. _this.name = "LoadFileError";
  8277. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8278. return _this;
  8279. }
  8280. // Polyfill for Object.setPrototypeOf if necessary.
  8281. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8282. return LoadFileError;
  8283. }(Error));
  8284. BABYLON.LoadFileError = LoadFileError;
  8285. var RetryStrategy = /** @class */ (function () {
  8286. function RetryStrategy() {
  8287. }
  8288. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8289. if (maxRetries === void 0) { maxRetries = 3; }
  8290. if (baseInterval === void 0) { baseInterval = 500; }
  8291. return function (url, request, retryIndex) {
  8292. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8293. return -1;
  8294. }
  8295. return Math.pow(2, retryIndex) * baseInterval;
  8296. };
  8297. };
  8298. return RetryStrategy;
  8299. }());
  8300. BABYLON.RetryStrategy = RetryStrategy;
  8301. // Screenshots
  8302. var screenshotCanvas;
  8303. var cloneValue = function (source, destinationObject) {
  8304. if (!source)
  8305. return null;
  8306. if (source instanceof BABYLON.Mesh) {
  8307. return null;
  8308. }
  8309. if (source instanceof BABYLON.SubMesh) {
  8310. return source.clone(destinationObject);
  8311. }
  8312. else if (source.clone) {
  8313. return source.clone();
  8314. }
  8315. return null;
  8316. };
  8317. var Tools = /** @class */ (function () {
  8318. function Tools() {
  8319. }
  8320. /**
  8321. * Interpolates between a and b via alpha
  8322. * @param a The lower value (returned when alpha = 0)
  8323. * @param b The upper value (returned when alpha = 1)
  8324. * @param alpha The interpolation-factor
  8325. * @return The mixed value
  8326. */
  8327. Tools.Mix = function (a, b, alpha) {
  8328. return a * (1 - alpha) + b * alpha;
  8329. };
  8330. Tools.Instantiate = function (className) {
  8331. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8332. return Tools.RegisteredExternalClasses[className];
  8333. }
  8334. var arr = className.split(".");
  8335. var fn = (window || this);
  8336. for (var i = 0, len = arr.length; i < len; i++) {
  8337. fn = fn[arr[i]];
  8338. }
  8339. if (typeof fn !== "function") {
  8340. return null;
  8341. }
  8342. return fn;
  8343. };
  8344. /**
  8345. * Provides a slice function that will work even on IE
  8346. * @param data defines the array to slice
  8347. * @param start defines the start of the data (optional)
  8348. * @param end defines the end of the data (optional)
  8349. * @returns the new sliced array
  8350. */
  8351. Tools.Slice = function (data, start, end) {
  8352. if (data.slice) {
  8353. return data.slice(start, end);
  8354. }
  8355. return Array.prototype.slice.call(data, start, end);
  8356. };
  8357. Tools.SetImmediate = function (action) {
  8358. if (window.setImmediate) {
  8359. window.setImmediate(action);
  8360. }
  8361. else {
  8362. setTimeout(action, 1);
  8363. }
  8364. };
  8365. Tools.IsExponentOfTwo = function (value) {
  8366. var count = 1;
  8367. do {
  8368. count *= 2;
  8369. } while (count < value);
  8370. return count === value;
  8371. };
  8372. /**
  8373. * Find the next highest power of two.
  8374. * @param x Number to start search from.
  8375. * @return Next highest power of two.
  8376. */
  8377. Tools.CeilingPOT = function (x) {
  8378. x--;
  8379. x |= x >> 1;
  8380. x |= x >> 2;
  8381. x |= x >> 4;
  8382. x |= x >> 8;
  8383. x |= x >> 16;
  8384. x++;
  8385. return x;
  8386. };
  8387. /**
  8388. * Find the next lowest power of two.
  8389. * @param x Number to start search from.
  8390. * @return Next lowest power of two.
  8391. */
  8392. Tools.FloorPOT = function (x) {
  8393. x = x | (x >> 1);
  8394. x = x | (x >> 2);
  8395. x = x | (x >> 4);
  8396. x = x | (x >> 8);
  8397. x = x | (x >> 16);
  8398. return x - (x >> 1);
  8399. };
  8400. /**
  8401. * Find the nearest power of two.
  8402. * @param x Number to start search from.
  8403. * @return Next nearest power of two.
  8404. */
  8405. Tools.NearestPOT = function (x) {
  8406. var c = Tools.CeilingPOT(x);
  8407. var f = Tools.FloorPOT(x);
  8408. return (c - x) > (x - f) ? f : c;
  8409. };
  8410. Tools.GetExponentOfTwo = function (value, max, mode) {
  8411. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8412. var pot;
  8413. switch (mode) {
  8414. case BABYLON.Engine.SCALEMODE_FLOOR:
  8415. pot = Tools.FloorPOT(value);
  8416. break;
  8417. case BABYLON.Engine.SCALEMODE_NEAREST:
  8418. pot = Tools.NearestPOT(value);
  8419. break;
  8420. case BABYLON.Engine.SCALEMODE_CEILING:
  8421. default:
  8422. pot = Tools.CeilingPOT(value);
  8423. break;
  8424. }
  8425. return Math.min(pot, max);
  8426. };
  8427. Tools.GetFilename = function (path) {
  8428. var index = path.lastIndexOf("/");
  8429. if (index < 0)
  8430. return path;
  8431. return path.substring(index + 1);
  8432. };
  8433. /**
  8434. * Extracts the "folder" part of a path (everything before the filename).
  8435. * @param uri The URI to extract the info from
  8436. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8437. * @returns The "folder" part of the path
  8438. */
  8439. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8440. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8441. var index = uri.lastIndexOf("/");
  8442. if (index < 0) {
  8443. if (returnUnchangedIfNoSlash) {
  8444. return uri;
  8445. }
  8446. return "";
  8447. }
  8448. return uri.substring(0, index + 1);
  8449. };
  8450. Tools.GetDOMTextContent = function (element) {
  8451. var result = "";
  8452. var child = element.firstChild;
  8453. while (child) {
  8454. if (child.nodeType === 3) {
  8455. result += child.textContent;
  8456. }
  8457. child = child.nextSibling;
  8458. }
  8459. return result;
  8460. };
  8461. Tools.ToDegrees = function (angle) {
  8462. return angle * 180 / Math.PI;
  8463. };
  8464. Tools.ToRadians = function (angle) {
  8465. return angle * Math.PI / 180;
  8466. };
  8467. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8468. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8469. var output = "";
  8470. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8471. var i = 0;
  8472. var bytes = new Uint8Array(buffer);
  8473. while (i < bytes.length) {
  8474. chr1 = bytes[i++];
  8475. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8476. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8477. enc1 = chr1 >> 2;
  8478. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8479. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8480. enc4 = chr3 & 63;
  8481. if (isNaN(chr2)) {
  8482. enc3 = enc4 = 64;
  8483. }
  8484. else if (isNaN(chr3)) {
  8485. enc4 = 64;
  8486. }
  8487. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8488. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8489. }
  8490. return "data:image/png;base64," + output;
  8491. };
  8492. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8493. if (bias === void 0) { bias = null; }
  8494. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8495. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8496. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8497. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8498. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8499. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8500. }
  8501. if (bias) {
  8502. minimum.x -= minimum.x * bias.x + bias.y;
  8503. minimum.y -= minimum.y * bias.x + bias.y;
  8504. minimum.z -= minimum.z * bias.x + bias.y;
  8505. maximum.x += maximum.x * bias.x + bias.y;
  8506. maximum.y += maximum.y * bias.x + bias.y;
  8507. maximum.z += maximum.z * bias.x + bias.y;
  8508. }
  8509. return {
  8510. minimum: minimum,
  8511. maximum: maximum
  8512. };
  8513. };
  8514. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8515. if (bias === void 0) { bias = null; }
  8516. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8517. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8518. if (!stride) {
  8519. stride = 3;
  8520. }
  8521. for (var index = start; index < start + count; index++) {
  8522. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8523. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8524. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8525. }
  8526. if (bias) {
  8527. minimum.x -= minimum.x * bias.x + bias.y;
  8528. minimum.y -= minimum.y * bias.x + bias.y;
  8529. minimum.z -= minimum.z * bias.x + bias.y;
  8530. maximum.x += maximum.x * bias.x + bias.y;
  8531. maximum.y += maximum.y * bias.x + bias.y;
  8532. maximum.z += maximum.z * bias.x + bias.y;
  8533. }
  8534. return {
  8535. minimum: minimum,
  8536. maximum: maximum
  8537. };
  8538. };
  8539. Tools.Vector2ArrayFeeder = function (array) {
  8540. return function (index) {
  8541. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8542. var length = isFloatArray ? array.length / 2 : array.length;
  8543. if (index >= length) {
  8544. return null;
  8545. }
  8546. if (isFloatArray) {
  8547. var fa = array;
  8548. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8549. }
  8550. var a = array;
  8551. return a[index];
  8552. };
  8553. };
  8554. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8555. if (bias === void 0) { bias = null; }
  8556. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8557. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8558. var i = 0;
  8559. var cur = feeder(i++);
  8560. while (cur) {
  8561. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8562. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8563. cur = feeder(i++);
  8564. }
  8565. if (bias) {
  8566. minimum.x -= minimum.x * bias.x + bias.y;
  8567. minimum.y -= minimum.y * bias.x + bias.y;
  8568. maximum.x += maximum.x * bias.x + bias.y;
  8569. maximum.y += maximum.y * bias.x + bias.y;
  8570. }
  8571. return {
  8572. minimum: minimum,
  8573. maximum: maximum
  8574. };
  8575. };
  8576. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8577. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8578. return null;
  8579. return Array.isArray(obj) ? obj : [obj];
  8580. };
  8581. // Misc.
  8582. Tools.GetPointerPrefix = function () {
  8583. var eventPrefix = "pointer";
  8584. // Check if pointer events are supported
  8585. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8586. eventPrefix = "mouse";
  8587. }
  8588. return eventPrefix;
  8589. };
  8590. /**
  8591. * @param func - the function to be called
  8592. * @param requester - the object that will request the next frame. Falls back to window.
  8593. */
  8594. Tools.QueueNewFrame = function (func, requester) {
  8595. if (!Tools.IsWindowObjectExist()) {
  8596. return setTimeout(func, 16);
  8597. }
  8598. if (!requester) {
  8599. requester = window;
  8600. }
  8601. if (requester.requestAnimationFrame) {
  8602. return requester.requestAnimationFrame(func);
  8603. }
  8604. else if (requester.msRequestAnimationFrame) {
  8605. return requester.msRequestAnimationFrame(func);
  8606. }
  8607. else if (requester.webkitRequestAnimationFrame) {
  8608. return requester.webkitRequestAnimationFrame(func);
  8609. }
  8610. else if (requester.mozRequestAnimationFrame) {
  8611. return requester.mozRequestAnimationFrame(func);
  8612. }
  8613. else if (requester.oRequestAnimationFrame) {
  8614. return requester.oRequestAnimationFrame(func);
  8615. }
  8616. else {
  8617. return window.setTimeout(func, 16);
  8618. }
  8619. };
  8620. Tools.RequestFullscreen = function (element) {
  8621. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8622. if (!requestFunction)
  8623. return;
  8624. requestFunction.call(element);
  8625. };
  8626. Tools.ExitFullscreen = function () {
  8627. if (document.exitFullscreen) {
  8628. document.exitFullscreen();
  8629. }
  8630. else if (document.mozCancelFullScreen) {
  8631. document.mozCancelFullScreen();
  8632. }
  8633. else if (document.webkitCancelFullScreen) {
  8634. document.webkitCancelFullScreen();
  8635. }
  8636. else if (document.msCancelFullScreen) {
  8637. document.msCancelFullScreen();
  8638. }
  8639. };
  8640. Tools.SetCorsBehavior = function (url, element) {
  8641. if (url && url.indexOf("data:") === 0) {
  8642. return;
  8643. }
  8644. if (Tools.CorsBehavior) {
  8645. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8646. element.crossOrigin = Tools.CorsBehavior;
  8647. }
  8648. else {
  8649. var result = Tools.CorsBehavior(url);
  8650. if (result) {
  8651. element.crossOrigin = result;
  8652. }
  8653. }
  8654. }
  8655. };
  8656. // External files
  8657. Tools.CleanUrl = function (url) {
  8658. url = url.replace(/#/mg, "%23");
  8659. return url;
  8660. };
  8661. Tools.LoadImage = function (url, onLoad, onError, database) {
  8662. if (url instanceof ArrayBuffer) {
  8663. url = Tools.EncodeArrayBufferTobase64(url);
  8664. }
  8665. url = Tools.CleanUrl(url);
  8666. url = Tools.PreprocessUrl(url);
  8667. var img = new Image();
  8668. Tools.SetCorsBehavior(url, img);
  8669. var loadHandler = function () {
  8670. img.removeEventListener("load", loadHandler);
  8671. img.removeEventListener("error", errorHandler);
  8672. onLoad(img);
  8673. };
  8674. var errorHandler = function (err) {
  8675. img.removeEventListener("load", loadHandler);
  8676. img.removeEventListener("error", errorHandler);
  8677. Tools.Error("Error while trying to load image: " + url);
  8678. if (onError) {
  8679. onError("Error while trying to load image: " + url, err);
  8680. }
  8681. };
  8682. img.addEventListener("load", loadHandler);
  8683. img.addEventListener("error", errorHandler);
  8684. var noIndexedDB = function () {
  8685. img.src = url;
  8686. };
  8687. var loadFromIndexedDB = function () {
  8688. if (database) {
  8689. database.loadImageFromDB(url, img);
  8690. }
  8691. };
  8692. //ANY database to do!
  8693. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8694. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8695. }
  8696. else {
  8697. if (url.indexOf("file:") !== -1) {
  8698. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8699. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8700. try {
  8701. var blobURL;
  8702. try {
  8703. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8704. }
  8705. catch (ex) {
  8706. // Chrome doesn't support oneTimeOnly parameter
  8707. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8708. }
  8709. img.src = blobURL;
  8710. }
  8711. catch (e) {
  8712. img.src = "";
  8713. }
  8714. return img;
  8715. }
  8716. }
  8717. noIndexedDB();
  8718. }
  8719. return img;
  8720. };
  8721. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8722. url = Tools.CleanUrl(url);
  8723. url = Tools.PreprocessUrl(url);
  8724. // If file and file input are set
  8725. if (url.indexOf("file:") !== -1) {
  8726. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8727. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8728. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8729. }
  8730. }
  8731. var loadUrl = Tools.BaseUrl + url;
  8732. var aborted = false;
  8733. var fileRequest = {
  8734. onCompleteObservable: new BABYLON.Observable(),
  8735. abort: function () { return aborted = true; },
  8736. };
  8737. var requestFile = function () {
  8738. var request = new XMLHttpRequest();
  8739. var retryHandle = null;
  8740. fileRequest.abort = function () {
  8741. aborted = true;
  8742. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8743. request.abort();
  8744. }
  8745. if (retryHandle !== null) {
  8746. clearTimeout(retryHandle);
  8747. retryHandle = null;
  8748. }
  8749. };
  8750. var retryLoop = function (retryIndex) {
  8751. request.open('GET', loadUrl, true);
  8752. if (useArrayBuffer) {
  8753. request.responseType = "arraybuffer";
  8754. }
  8755. if (onProgress) {
  8756. request.addEventListener("progress", onProgress);
  8757. }
  8758. var onLoadEnd = function () {
  8759. request.removeEventListener("loadend", onLoadEnd);
  8760. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8761. fileRequest.onCompleteObservable.clear();
  8762. };
  8763. request.addEventListener("loadend", onLoadEnd);
  8764. var onReadyStateChange = function () {
  8765. if (aborted) {
  8766. return;
  8767. }
  8768. // In case of undefined state in some browsers.
  8769. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8770. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8771. request.removeEventListener("readystatechange", onReadyStateChange);
  8772. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8773. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8774. return;
  8775. }
  8776. var retryStrategy = Tools.DefaultRetryStrategy;
  8777. if (retryStrategy) {
  8778. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8779. if (waitTime !== -1) {
  8780. // Prevent the request from completing for retry.
  8781. request.removeEventListener("loadend", onLoadEnd);
  8782. request = new XMLHttpRequest();
  8783. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8784. return;
  8785. }
  8786. }
  8787. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8788. if (onError) {
  8789. onError(request, e);
  8790. }
  8791. else {
  8792. throw e;
  8793. }
  8794. }
  8795. };
  8796. request.addEventListener("readystatechange", onReadyStateChange);
  8797. request.send();
  8798. };
  8799. retryLoop(0);
  8800. };
  8801. // Caching all files
  8802. if (database && database.enableSceneOffline) {
  8803. var noIndexedDB_1 = function () {
  8804. if (!aborted) {
  8805. requestFile();
  8806. }
  8807. };
  8808. var loadFromIndexedDB = function () {
  8809. // TODO: database needs to support aborting and should return a IFileRequest
  8810. if (aborted) {
  8811. return;
  8812. }
  8813. if (database) {
  8814. database.loadFileFromDB(url, function (data) {
  8815. if (!aborted) {
  8816. onSuccess(data);
  8817. }
  8818. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8819. }, onProgress ? function (event) {
  8820. if (!aborted) {
  8821. onProgress(event);
  8822. }
  8823. } : undefined, noIndexedDB_1, useArrayBuffer);
  8824. }
  8825. };
  8826. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8827. }
  8828. else {
  8829. requestFile();
  8830. }
  8831. return fileRequest;
  8832. };
  8833. /**
  8834. * Load a script (identified by an url). When the url returns, the
  8835. * content of this file is added into a new script element, attached to the DOM (body element)
  8836. */
  8837. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8838. var head = document.getElementsByTagName('head')[0];
  8839. var script = document.createElement('script');
  8840. script.type = 'text/javascript';
  8841. script.src = scriptUrl;
  8842. script.onload = function () {
  8843. if (onSuccess) {
  8844. onSuccess();
  8845. }
  8846. };
  8847. script.onerror = function (e) {
  8848. if (onError) {
  8849. onError("Unable to load script '" + scriptUrl + "'", e);
  8850. }
  8851. };
  8852. head.appendChild(script);
  8853. };
  8854. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8855. var reader = new FileReader();
  8856. var request = {
  8857. onCompleteObservable: new BABYLON.Observable(),
  8858. abort: function () { return reader.abort(); },
  8859. };
  8860. reader.onloadend = function (e) {
  8861. request.onCompleteObservable.notifyObservers(request);
  8862. };
  8863. reader.onload = function (e) {
  8864. //target doesn't have result from ts 1.3
  8865. callback(e.target['result']);
  8866. };
  8867. reader.onprogress = progressCallback;
  8868. reader.readAsDataURL(fileToLoad);
  8869. return request;
  8870. };
  8871. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8872. var reader = new FileReader();
  8873. var request = {
  8874. onCompleteObservable: new BABYLON.Observable(),
  8875. abort: function () { return reader.abort(); },
  8876. };
  8877. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8878. reader.onerror = function (e) {
  8879. Tools.Log("Error while reading file: " + fileToLoad.name);
  8880. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8881. };
  8882. reader.onload = function (e) {
  8883. //target doesn't have result from ts 1.3
  8884. callback(e.target['result']);
  8885. };
  8886. if (progressCallBack) {
  8887. reader.onprogress = progressCallBack;
  8888. }
  8889. if (!useArrayBuffer) {
  8890. // Asynchronous read
  8891. reader.readAsText(fileToLoad);
  8892. }
  8893. else {
  8894. reader.readAsArrayBuffer(fileToLoad);
  8895. }
  8896. return request;
  8897. };
  8898. //returns a downloadable url to a file content.
  8899. Tools.FileAsURL = function (content) {
  8900. var fileBlob = new Blob([content]);
  8901. var url = window.URL || window.webkitURL;
  8902. var link = url.createObjectURL(fileBlob);
  8903. return link;
  8904. };
  8905. // Misc.
  8906. Tools.Format = function (value, decimals) {
  8907. if (decimals === void 0) { decimals = 2; }
  8908. return value.toFixed(decimals);
  8909. };
  8910. Tools.CheckExtends = function (v, min, max) {
  8911. if (v.x < min.x)
  8912. min.x = v.x;
  8913. if (v.y < min.y)
  8914. min.y = v.y;
  8915. if (v.z < min.z)
  8916. min.z = v.z;
  8917. if (v.x > max.x)
  8918. max.x = v.x;
  8919. if (v.y > max.y)
  8920. max.y = v.y;
  8921. if (v.z > max.z)
  8922. max.z = v.z;
  8923. };
  8924. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8925. for (var prop in source) {
  8926. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8927. continue;
  8928. }
  8929. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8930. continue;
  8931. }
  8932. var sourceValue = source[prop];
  8933. var typeOfSourceValue = typeof sourceValue;
  8934. if (typeOfSourceValue === "function") {
  8935. continue;
  8936. }
  8937. try {
  8938. if (typeOfSourceValue === "object") {
  8939. if (sourceValue instanceof Array) {
  8940. destination[prop] = [];
  8941. if (sourceValue.length > 0) {
  8942. if (typeof sourceValue[0] == "object") {
  8943. for (var index = 0; index < sourceValue.length; index++) {
  8944. var clonedValue = cloneValue(sourceValue[index], destination);
  8945. if (destination[prop].indexOf(clonedValue) === -1) {
  8946. destination[prop].push(clonedValue);
  8947. }
  8948. }
  8949. }
  8950. else {
  8951. destination[prop] = sourceValue.slice(0);
  8952. }
  8953. }
  8954. }
  8955. else {
  8956. destination[prop] = cloneValue(sourceValue, destination);
  8957. }
  8958. }
  8959. else {
  8960. destination[prop] = sourceValue;
  8961. }
  8962. }
  8963. catch (e) {
  8964. // Just ignore error (it could be because of a read-only property)
  8965. }
  8966. }
  8967. };
  8968. Tools.IsEmpty = function (obj) {
  8969. for (var i in obj) {
  8970. if (obj.hasOwnProperty(i)) {
  8971. return false;
  8972. }
  8973. }
  8974. return true;
  8975. };
  8976. Tools.RegisterTopRootEvents = function (events) {
  8977. for (var index = 0; index < events.length; index++) {
  8978. var event = events[index];
  8979. window.addEventListener(event.name, event.handler, false);
  8980. try {
  8981. if (window.parent) {
  8982. window.parent.addEventListener(event.name, event.handler, false);
  8983. }
  8984. }
  8985. catch (e) {
  8986. // Silently fails...
  8987. }
  8988. }
  8989. };
  8990. Tools.UnregisterTopRootEvents = function (events) {
  8991. for (var index = 0; index < events.length; index++) {
  8992. var event = events[index];
  8993. window.removeEventListener(event.name, event.handler);
  8994. try {
  8995. if (window.parent) {
  8996. window.parent.removeEventListener(event.name, event.handler);
  8997. }
  8998. }
  8999. catch (e) {
  9000. // Silently fails...
  9001. }
  9002. }
  9003. };
  9004. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9005. if (mimeType === void 0) { mimeType = "image/png"; }
  9006. // Read the contents of the framebuffer
  9007. var numberOfChannelsByLine = width * 4;
  9008. var halfHeight = height / 2;
  9009. //Reading datas from WebGL
  9010. var data = engine.readPixels(0, 0, width, height);
  9011. //To flip image on Y axis.
  9012. for (var i = 0; i < halfHeight; i++) {
  9013. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9014. var currentCell = j + i * numberOfChannelsByLine;
  9015. var targetLine = height - i - 1;
  9016. var targetCell = j + targetLine * numberOfChannelsByLine;
  9017. var temp = data[currentCell];
  9018. data[currentCell] = data[targetCell];
  9019. data[targetCell] = temp;
  9020. }
  9021. }
  9022. // Create a 2D canvas to store the result
  9023. if (!screenshotCanvas) {
  9024. screenshotCanvas = document.createElement('canvas');
  9025. }
  9026. screenshotCanvas.width = width;
  9027. screenshotCanvas.height = height;
  9028. var context = screenshotCanvas.getContext('2d');
  9029. if (context) {
  9030. // Copy the pixels to a 2D canvas
  9031. var imageData = context.createImageData(width, height);
  9032. var castData = (imageData.data);
  9033. castData.set(data);
  9034. context.putImageData(imageData, 0, 0);
  9035. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9036. }
  9037. };
  9038. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9039. if (mimeType === void 0) { mimeType = "image/png"; }
  9040. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9041. if (successCallback) {
  9042. successCallback(base64Image);
  9043. }
  9044. else {
  9045. // We need HTMLCanvasElement.toBlob for HD screenshots
  9046. if (!screenshotCanvas.toBlob) {
  9047. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9048. screenshotCanvas.toBlob = function (callback, type, quality) {
  9049. var _this = this;
  9050. setTimeout(function () {
  9051. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9052. for (var i = 0; i < len; i++) {
  9053. arr[i] = binStr.charCodeAt(i);
  9054. }
  9055. callback(new Blob([arr], { type: type || 'image/png' }));
  9056. });
  9057. };
  9058. }
  9059. screenshotCanvas.toBlob(function (blob) {
  9060. var url = URL.createObjectURL(blob);
  9061. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9062. if (("download" in document.createElement("a"))) {
  9063. var a = window.document.createElement("a");
  9064. a.href = url;
  9065. if (fileName) {
  9066. a.setAttribute("download", fileName);
  9067. }
  9068. else {
  9069. var date = new Date();
  9070. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9071. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9072. }
  9073. window.document.body.appendChild(a);
  9074. a.addEventListener("click", function () {
  9075. if (a.parentElement) {
  9076. a.parentElement.removeChild(a);
  9077. }
  9078. });
  9079. a.click();
  9080. }
  9081. else {
  9082. var newWindow = window.open("");
  9083. if (!newWindow)
  9084. return;
  9085. var img = newWindow.document.createElement("img");
  9086. img.onload = function () {
  9087. // no longer need to read the blob so it's revoked
  9088. URL.revokeObjectURL(url);
  9089. };
  9090. img.src = url;
  9091. newWindow.document.body.appendChild(img);
  9092. }
  9093. });
  9094. }
  9095. };
  9096. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9097. if (mimeType === void 0) { mimeType = "image/png"; }
  9098. var width;
  9099. var height;
  9100. // If a precision value is specified
  9101. if (size.precision) {
  9102. width = Math.round(engine.getRenderWidth() * size.precision);
  9103. height = Math.round(width / engine.getAspectRatio(camera));
  9104. }
  9105. else if (size.width && size.height) {
  9106. width = size.width;
  9107. height = size.height;
  9108. }
  9109. else if (size.width && !size.height) {
  9110. width = size.width;
  9111. height = Math.round(width / engine.getAspectRatio(camera));
  9112. }
  9113. else if (size.height && !size.width) {
  9114. height = size.height;
  9115. width = Math.round(height * engine.getAspectRatio(camera));
  9116. }
  9117. else if (!isNaN(size)) {
  9118. height = size;
  9119. width = size;
  9120. }
  9121. else {
  9122. Tools.Error("Invalid 'size' parameter !");
  9123. return;
  9124. }
  9125. if (!screenshotCanvas) {
  9126. screenshotCanvas = document.createElement('canvas');
  9127. }
  9128. screenshotCanvas.width = width;
  9129. screenshotCanvas.height = height;
  9130. var renderContext = screenshotCanvas.getContext("2d");
  9131. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9132. var newWidth = width;
  9133. var newHeight = newWidth / ratio;
  9134. if (newHeight > height) {
  9135. newHeight = height;
  9136. newWidth = newHeight * ratio;
  9137. }
  9138. var offsetX = Math.max(0, width - newWidth) / 2;
  9139. var offsetY = Math.max(0, height - newHeight) / 2;
  9140. var renderingCanvas = engine.getRenderingCanvas();
  9141. if (renderContext && renderingCanvas) {
  9142. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9143. }
  9144. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9145. };
  9146. /**
  9147. * Generates an image screenshot from the specified camera.
  9148. *
  9149. * @param engine The engine to use for rendering
  9150. * @param camera The camera to use for rendering
  9151. * @param size This parameter can be set to a single number or to an object with the
  9152. * following (optional) properties: precision, width, height. If a single number is passed,
  9153. * it will be used for both width and height. If an object is passed, the screenshot size
  9154. * will be derived from the parameters. The precision property is a multiplier allowing
  9155. * rendering at a higher or lower resolution.
  9156. * @param successCallback The callback receives a single parameter which contains the
  9157. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9158. * src parameter of an <img> to display it.
  9159. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9160. * Check your browser for supported MIME types.
  9161. * @param samples Texture samples (default: 1)
  9162. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9163. * @param fileName A name for for the downloaded file.
  9164. * @constructor
  9165. */
  9166. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9167. if (mimeType === void 0) { mimeType = "image/png"; }
  9168. if (samples === void 0) { samples = 1; }
  9169. if (antialiasing === void 0) { antialiasing = false; }
  9170. var width;
  9171. var height;
  9172. //If a precision value is specified
  9173. if (size.precision) {
  9174. width = Math.round(engine.getRenderWidth() * size.precision);
  9175. height = Math.round(width / engine.getAspectRatio(camera));
  9176. size = { width: width, height: height };
  9177. }
  9178. else if (size.width && size.height) {
  9179. width = size.width;
  9180. height = size.height;
  9181. }
  9182. else if (size.width && !size.height) {
  9183. width = size.width;
  9184. height = Math.round(width / engine.getAspectRatio(camera));
  9185. size = { width: width, height: height };
  9186. }
  9187. else if (size.height && !size.width) {
  9188. height = size.height;
  9189. width = Math.round(height * engine.getAspectRatio(camera));
  9190. size = { width: width, height: height };
  9191. }
  9192. else if (!isNaN(size)) {
  9193. height = size;
  9194. width = size;
  9195. }
  9196. else {
  9197. Tools.Error("Invalid 'size' parameter !");
  9198. return;
  9199. }
  9200. var scene = camera.getScene();
  9201. var previousCamera = null;
  9202. if (scene.activeCamera !== camera) {
  9203. previousCamera = scene.activeCamera;
  9204. scene.activeCamera = camera;
  9205. }
  9206. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9207. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9208. texture.renderList = null;
  9209. texture.samples = samples;
  9210. if (antialiasing) {
  9211. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9212. }
  9213. texture.onAfterRenderObservable.add(function () {
  9214. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9215. });
  9216. scene.incrementRenderId();
  9217. scene.resetCachedMaterial();
  9218. texture.render(true);
  9219. texture.dispose();
  9220. if (previousCamera) {
  9221. scene.activeCamera = previousCamera;
  9222. }
  9223. camera.getProjectionMatrix(true); // Force cache refresh;
  9224. };
  9225. // XHR response validator for local file scenario
  9226. Tools.ValidateXHRData = function (xhr, dataType) {
  9227. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9228. if (dataType === void 0) { dataType = 7; }
  9229. try {
  9230. if (dataType & 1) {
  9231. if (xhr.responseText && xhr.responseText.length > 0) {
  9232. return true;
  9233. }
  9234. else if (dataType === 1) {
  9235. return false;
  9236. }
  9237. }
  9238. if (dataType & 2) {
  9239. // Check header width and height since there is no "TGA" magic number
  9240. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9241. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9242. return true;
  9243. }
  9244. else if (dataType === 2) {
  9245. return false;
  9246. }
  9247. }
  9248. if (dataType & 4) {
  9249. // Check for the "DDS" magic number
  9250. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9251. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9252. return true;
  9253. }
  9254. else {
  9255. return false;
  9256. }
  9257. }
  9258. }
  9259. catch (e) {
  9260. // Global protection
  9261. }
  9262. return false;
  9263. };
  9264. /**
  9265. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9266. * Be aware Math.random() could cause collisions, but:
  9267. * "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"
  9268. */
  9269. Tools.RandomId = function () {
  9270. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9271. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9272. return v.toString(16);
  9273. });
  9274. };
  9275. /**
  9276. * Test if the given uri is a base64 string.
  9277. * @param uri The uri to test
  9278. * @return True if the uri is a base64 string or false otherwise.
  9279. */
  9280. Tools.IsBase64 = function (uri) {
  9281. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9282. };
  9283. /**
  9284. * Decode the given base64 uri.
  9285. * @param uri The uri to decode
  9286. * @return The decoded base64 data.
  9287. */
  9288. Tools.DecodeBase64 = function (uri) {
  9289. var decodedString = atob(uri.split(",")[1]);
  9290. var bufferLength = decodedString.length;
  9291. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9292. for (var i = 0; i < bufferLength; i++) {
  9293. bufferView[i] = decodedString.charCodeAt(i);
  9294. }
  9295. return bufferView.buffer;
  9296. };
  9297. Object.defineProperty(Tools, "NoneLogLevel", {
  9298. get: function () {
  9299. return Tools._NoneLogLevel;
  9300. },
  9301. enumerable: true,
  9302. configurable: true
  9303. });
  9304. Object.defineProperty(Tools, "MessageLogLevel", {
  9305. get: function () {
  9306. return Tools._MessageLogLevel;
  9307. },
  9308. enumerable: true,
  9309. configurable: true
  9310. });
  9311. Object.defineProperty(Tools, "WarningLogLevel", {
  9312. get: function () {
  9313. return Tools._WarningLogLevel;
  9314. },
  9315. enumerable: true,
  9316. configurable: true
  9317. });
  9318. Object.defineProperty(Tools, "ErrorLogLevel", {
  9319. get: function () {
  9320. return Tools._ErrorLogLevel;
  9321. },
  9322. enumerable: true,
  9323. configurable: true
  9324. });
  9325. Object.defineProperty(Tools, "AllLogLevel", {
  9326. get: function () {
  9327. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9328. },
  9329. enumerable: true,
  9330. configurable: true
  9331. });
  9332. Tools._AddLogEntry = function (entry) {
  9333. Tools._LogCache = entry + Tools._LogCache;
  9334. if (Tools.OnNewCacheEntry) {
  9335. Tools.OnNewCacheEntry(entry);
  9336. }
  9337. };
  9338. Tools._FormatMessage = function (message) {
  9339. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9340. var date = new Date();
  9341. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9342. };
  9343. Tools._LogDisabled = function (message) {
  9344. // nothing to do
  9345. };
  9346. Tools._LogEnabled = function (message) {
  9347. var formattedMessage = Tools._FormatMessage(message);
  9348. console.log("BJS - " + formattedMessage);
  9349. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9350. Tools._AddLogEntry(entry);
  9351. };
  9352. Tools._WarnDisabled = function (message) {
  9353. // nothing to do
  9354. };
  9355. Tools._WarnEnabled = function (message) {
  9356. var formattedMessage = Tools._FormatMessage(message);
  9357. console.warn("BJS - " + formattedMessage);
  9358. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9359. Tools._AddLogEntry(entry);
  9360. };
  9361. Tools._ErrorDisabled = function (message) {
  9362. // nothing to do
  9363. };
  9364. Tools._ErrorEnabled = function (message) {
  9365. Tools.errorsCount++;
  9366. var formattedMessage = Tools._FormatMessage(message);
  9367. console.error("BJS - " + formattedMessage);
  9368. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9369. Tools._AddLogEntry(entry);
  9370. };
  9371. Object.defineProperty(Tools, "LogCache", {
  9372. get: function () {
  9373. return Tools._LogCache;
  9374. },
  9375. enumerable: true,
  9376. configurable: true
  9377. });
  9378. Tools.ClearLogCache = function () {
  9379. Tools._LogCache = "";
  9380. Tools.errorsCount = 0;
  9381. };
  9382. Object.defineProperty(Tools, "LogLevels", {
  9383. set: function (level) {
  9384. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9385. Tools.Log = Tools._LogEnabled;
  9386. }
  9387. else {
  9388. Tools.Log = Tools._LogDisabled;
  9389. }
  9390. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9391. Tools.Warn = Tools._WarnEnabled;
  9392. }
  9393. else {
  9394. Tools.Warn = Tools._WarnDisabled;
  9395. }
  9396. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9397. Tools.Error = Tools._ErrorEnabled;
  9398. }
  9399. else {
  9400. Tools.Error = Tools._ErrorDisabled;
  9401. }
  9402. },
  9403. enumerable: true,
  9404. configurable: true
  9405. });
  9406. Tools.IsWindowObjectExist = function () {
  9407. return (typeof window) !== "undefined";
  9408. };
  9409. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9410. get: function () {
  9411. return Tools._PerformanceNoneLogLevel;
  9412. },
  9413. enumerable: true,
  9414. configurable: true
  9415. });
  9416. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9417. get: function () {
  9418. return Tools._PerformanceUserMarkLogLevel;
  9419. },
  9420. enumerable: true,
  9421. configurable: true
  9422. });
  9423. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9424. get: function () {
  9425. return Tools._PerformanceConsoleLogLevel;
  9426. },
  9427. enumerable: true,
  9428. configurable: true
  9429. });
  9430. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9431. set: function (level) {
  9432. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9433. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9434. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9435. return;
  9436. }
  9437. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9438. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9439. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9440. return;
  9441. }
  9442. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9443. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9444. },
  9445. enumerable: true,
  9446. configurable: true
  9447. });
  9448. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9449. };
  9450. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9451. };
  9452. Tools._StartUserMark = function (counterName, condition) {
  9453. if (condition === void 0) { condition = true; }
  9454. if (!Tools._performance) {
  9455. if (!Tools.IsWindowObjectExist()) {
  9456. return;
  9457. }
  9458. Tools._performance = window.performance;
  9459. }
  9460. if (!condition || !Tools._performance.mark) {
  9461. return;
  9462. }
  9463. Tools._performance.mark(counterName + "-Begin");
  9464. };
  9465. Tools._EndUserMark = function (counterName, condition) {
  9466. if (condition === void 0) { condition = true; }
  9467. if (!condition || !Tools._performance.mark) {
  9468. return;
  9469. }
  9470. Tools._performance.mark(counterName + "-End");
  9471. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9472. };
  9473. Tools._StartPerformanceConsole = function (counterName, condition) {
  9474. if (condition === void 0) { condition = true; }
  9475. if (!condition) {
  9476. return;
  9477. }
  9478. Tools._StartUserMark(counterName, condition);
  9479. if (console.time) {
  9480. console.time(counterName);
  9481. }
  9482. };
  9483. Tools._EndPerformanceConsole = function (counterName, condition) {
  9484. if (condition === void 0) { condition = true; }
  9485. if (!condition) {
  9486. return;
  9487. }
  9488. Tools._EndUserMark(counterName, condition);
  9489. if (console.time) {
  9490. console.timeEnd(counterName);
  9491. }
  9492. };
  9493. Object.defineProperty(Tools, "Now", {
  9494. get: function () {
  9495. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9496. return window.performance.now();
  9497. }
  9498. return new Date().getTime();
  9499. },
  9500. enumerable: true,
  9501. configurable: true
  9502. });
  9503. /**
  9504. * This method will return the name of the class used to create the instance of the given object.
  9505. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9506. * @param object the object to get the class name from
  9507. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9508. */
  9509. Tools.GetClassName = function (object, isType) {
  9510. if (isType === void 0) { isType = false; }
  9511. var name = null;
  9512. if (!isType && object.getClassName) {
  9513. name = object.getClassName();
  9514. }
  9515. else {
  9516. if (object instanceof Object) {
  9517. var classObj = isType ? object : Object.getPrototypeOf(object);
  9518. name = classObj.constructor["__bjsclassName__"];
  9519. }
  9520. if (!name) {
  9521. name = typeof object;
  9522. }
  9523. }
  9524. return name;
  9525. };
  9526. Tools.First = function (array, predicate) {
  9527. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9528. var el = array_1[_i];
  9529. if (predicate(el)) {
  9530. return el;
  9531. }
  9532. }
  9533. return null;
  9534. };
  9535. /**
  9536. * This method will return the name of the full name of the class, including its owning module (if any).
  9537. * 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).
  9538. * @param object the object to get the class name from
  9539. * @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.
  9540. */
  9541. Tools.getFullClassName = function (object, isType) {
  9542. if (isType === void 0) { isType = false; }
  9543. var className = null;
  9544. var moduleName = null;
  9545. if (!isType && object.getClassName) {
  9546. className = object.getClassName();
  9547. }
  9548. else {
  9549. if (object instanceof Object) {
  9550. var classObj = isType ? object : Object.getPrototypeOf(object);
  9551. className = classObj.constructor["__bjsclassName__"];
  9552. moduleName = classObj.constructor["__bjsmoduleName__"];
  9553. }
  9554. if (!className) {
  9555. className = typeof object;
  9556. }
  9557. }
  9558. if (!className) {
  9559. return null;
  9560. }
  9561. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9562. };
  9563. /**
  9564. * 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.
  9565. * @param array
  9566. */
  9567. Tools.arrayOrStringFeeder = function (array) {
  9568. return function (index) {
  9569. if (index >= array.length) {
  9570. return null;
  9571. }
  9572. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9573. if (val && val.getHashCode) {
  9574. val = val.getHashCode();
  9575. }
  9576. if (typeof val === "string") {
  9577. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9578. }
  9579. return val;
  9580. };
  9581. };
  9582. /**
  9583. * Compute the hashCode of a stream of number
  9584. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9585. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9586. * @return the hash code computed
  9587. */
  9588. Tools.hashCodeFromStream = function (feeder) {
  9589. // Based from here: http://stackoverflow.com/a/7616484/802124
  9590. var hash = 0;
  9591. var index = 0;
  9592. var chr = feeder(index++);
  9593. while (chr != null) {
  9594. hash = ((hash << 5) - hash) + chr;
  9595. hash |= 0; // Convert to 32bit integer
  9596. chr = feeder(index++);
  9597. }
  9598. return hash;
  9599. };
  9600. /**
  9601. * Returns a promise that resolves after the given amount of time.
  9602. * @param delay Number of milliseconds to delay
  9603. * @returns Promise that resolves after the given amount of time
  9604. */
  9605. Tools.DelayAsync = function (delay) {
  9606. return new Promise(function (resolve) {
  9607. setTimeout(function () {
  9608. resolve();
  9609. }, delay);
  9610. });
  9611. };
  9612. Tools.BaseUrl = "";
  9613. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9614. /**
  9615. * Default behaviour for cors in the application.
  9616. * It can be a string if the expected behavior is identical in the entire app.
  9617. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9618. */
  9619. Tools.CorsBehavior = "anonymous";
  9620. Tools.UseFallbackTexture = true;
  9621. /**
  9622. * Use this object to register external classes like custom textures or material
  9623. * to allow the laoders to instantiate them
  9624. */
  9625. Tools.RegisteredExternalClasses = {};
  9626. // Used in case of a texture loading problem
  9627. 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";
  9628. Tools.PreprocessUrl = function (url) {
  9629. return url;
  9630. };
  9631. // Logs
  9632. Tools._NoneLogLevel = 0;
  9633. Tools._MessageLogLevel = 1;
  9634. Tools._WarningLogLevel = 2;
  9635. Tools._ErrorLogLevel = 4;
  9636. Tools._LogCache = "";
  9637. Tools.errorsCount = 0;
  9638. Tools.Log = Tools._LogEnabled;
  9639. Tools.Warn = Tools._WarnEnabled;
  9640. Tools.Error = Tools._ErrorEnabled;
  9641. // Performances
  9642. Tools._PerformanceNoneLogLevel = 0;
  9643. Tools._PerformanceUserMarkLogLevel = 1;
  9644. Tools._PerformanceConsoleLogLevel = 2;
  9645. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9646. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9647. return Tools;
  9648. }());
  9649. BABYLON.Tools = Tools;
  9650. /**
  9651. * This class is used to track a performance counter which is number based.
  9652. * The user has access to many properties which give statistics of different nature
  9653. *
  9654. * The implementer can track two kinds of Performance Counter: time and count
  9655. * 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.
  9656. * 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.
  9657. */
  9658. var PerfCounter = /** @class */ (function () {
  9659. function PerfCounter() {
  9660. this._startMonitoringTime = 0;
  9661. this._min = 0;
  9662. this._max = 0;
  9663. this._average = 0;
  9664. this._lastSecAverage = 0;
  9665. this._current = 0;
  9666. this._totalValueCount = 0;
  9667. this._totalAccumulated = 0;
  9668. this._lastSecAccumulated = 0;
  9669. this._lastSecTime = 0;
  9670. this._lastSecValueCount = 0;
  9671. }
  9672. Object.defineProperty(PerfCounter.prototype, "min", {
  9673. /**
  9674. * Returns the smallest value ever
  9675. */
  9676. get: function () {
  9677. return this._min;
  9678. },
  9679. enumerable: true,
  9680. configurable: true
  9681. });
  9682. Object.defineProperty(PerfCounter.prototype, "max", {
  9683. /**
  9684. * Returns the biggest value ever
  9685. */
  9686. get: function () {
  9687. return this._max;
  9688. },
  9689. enumerable: true,
  9690. configurable: true
  9691. });
  9692. Object.defineProperty(PerfCounter.prototype, "average", {
  9693. /**
  9694. * Returns the average value since the performance counter is running
  9695. */
  9696. get: function () {
  9697. return this._average;
  9698. },
  9699. enumerable: true,
  9700. configurable: true
  9701. });
  9702. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9703. /**
  9704. * Returns the average value of the last second the counter was monitored
  9705. */
  9706. get: function () {
  9707. return this._lastSecAverage;
  9708. },
  9709. enumerable: true,
  9710. configurable: true
  9711. });
  9712. Object.defineProperty(PerfCounter.prototype, "current", {
  9713. /**
  9714. * Returns the current value
  9715. */
  9716. get: function () {
  9717. return this._current;
  9718. },
  9719. enumerable: true,
  9720. configurable: true
  9721. });
  9722. Object.defineProperty(PerfCounter.prototype, "total", {
  9723. get: function () {
  9724. return this._totalAccumulated;
  9725. },
  9726. enumerable: true,
  9727. configurable: true
  9728. });
  9729. Object.defineProperty(PerfCounter.prototype, "count", {
  9730. get: function () {
  9731. return this._totalValueCount;
  9732. },
  9733. enumerable: true,
  9734. configurable: true
  9735. });
  9736. /**
  9737. * Call this method to start monitoring a new frame.
  9738. * 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.
  9739. */
  9740. PerfCounter.prototype.fetchNewFrame = function () {
  9741. this._totalValueCount++;
  9742. this._current = 0;
  9743. this._lastSecValueCount++;
  9744. };
  9745. /**
  9746. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9747. * @param newCount the count value to add to the monitored count
  9748. * @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.
  9749. */
  9750. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9751. if (!PerfCounter.Enabled) {
  9752. return;
  9753. }
  9754. this._current += newCount;
  9755. if (fetchResult) {
  9756. this._fetchResult();
  9757. }
  9758. };
  9759. /**
  9760. * Start monitoring this performance counter
  9761. */
  9762. PerfCounter.prototype.beginMonitoring = function () {
  9763. if (!PerfCounter.Enabled) {
  9764. return;
  9765. }
  9766. this._startMonitoringTime = Tools.Now;
  9767. };
  9768. /**
  9769. * Compute the time lapsed since the previous beginMonitoring() call.
  9770. * @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
  9771. */
  9772. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9773. if (newFrame === void 0) { newFrame = true; }
  9774. if (!PerfCounter.Enabled) {
  9775. return;
  9776. }
  9777. if (newFrame) {
  9778. this.fetchNewFrame();
  9779. }
  9780. var currentTime = Tools.Now;
  9781. this._current = currentTime - this._startMonitoringTime;
  9782. if (newFrame) {
  9783. this._fetchResult();
  9784. }
  9785. };
  9786. PerfCounter.prototype._fetchResult = function () {
  9787. this._totalAccumulated += this._current;
  9788. this._lastSecAccumulated += this._current;
  9789. // Min/Max update
  9790. this._min = Math.min(this._min, this._current);
  9791. this._max = Math.max(this._max, this._current);
  9792. this._average = this._totalAccumulated / this._totalValueCount;
  9793. // Reset last sec?
  9794. var now = Tools.Now;
  9795. if ((now - this._lastSecTime) > 1000) {
  9796. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9797. this._lastSecTime = now;
  9798. this._lastSecAccumulated = 0;
  9799. this._lastSecValueCount = 0;
  9800. }
  9801. };
  9802. PerfCounter.Enabled = true;
  9803. return PerfCounter;
  9804. }());
  9805. BABYLON.PerfCounter = PerfCounter;
  9806. /**
  9807. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9808. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9809. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9810. * @param name The name of the class, case should be preserved
  9811. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9812. */
  9813. function className(name, module) {
  9814. return function (target) {
  9815. target["__bjsclassName__"] = name;
  9816. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9817. };
  9818. }
  9819. BABYLON.className = className;
  9820. /**
  9821. * An implementation of a loop for asynchronous functions.
  9822. */
  9823. var AsyncLoop = /** @class */ (function () {
  9824. /**
  9825. * Constroctor.
  9826. * @param iterations the number of iterations.
  9827. * @param _fn the function to run each iteration
  9828. * @param _successCallback the callback that will be called upon succesful execution
  9829. * @param offset starting offset.
  9830. */
  9831. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9832. if (offset === void 0) { offset = 0; }
  9833. this.iterations = iterations;
  9834. this._fn = _fn;
  9835. this._successCallback = _successCallback;
  9836. this.index = offset - 1;
  9837. this._done = false;
  9838. }
  9839. /**
  9840. * Execute the next iteration. Must be called after the last iteration was finished.
  9841. */
  9842. AsyncLoop.prototype.executeNext = function () {
  9843. if (!this._done) {
  9844. if (this.index + 1 < this.iterations) {
  9845. ++this.index;
  9846. this._fn(this);
  9847. }
  9848. else {
  9849. this.breakLoop();
  9850. }
  9851. }
  9852. };
  9853. /**
  9854. * Break the loop and run the success callback.
  9855. */
  9856. AsyncLoop.prototype.breakLoop = function () {
  9857. this._done = true;
  9858. this._successCallback();
  9859. };
  9860. /**
  9861. * Helper function
  9862. */
  9863. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9864. if (offset === void 0) { offset = 0; }
  9865. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9866. loop.executeNext();
  9867. return loop;
  9868. };
  9869. /**
  9870. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9871. * @param iterations total number of iterations
  9872. * @param syncedIterations number of synchronous iterations in each async iteration.
  9873. * @param fn the function to call each iteration.
  9874. * @param callback a success call back that will be called when iterating stops.
  9875. * @param breakFunction a break condition (optional)
  9876. * @param timeout timeout settings for the setTimeout function. default - 0.
  9877. * @constructor
  9878. */
  9879. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9880. if (timeout === void 0) { timeout = 0; }
  9881. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9882. if (breakFunction && breakFunction())
  9883. loop.breakLoop();
  9884. else {
  9885. setTimeout(function () {
  9886. for (var i = 0; i < syncedIterations; ++i) {
  9887. var iteration = (loop.index * syncedIterations) + i;
  9888. if (iteration >= iterations)
  9889. break;
  9890. fn(iteration);
  9891. if (breakFunction && breakFunction()) {
  9892. loop.breakLoop();
  9893. break;
  9894. }
  9895. }
  9896. loop.executeNext();
  9897. }, timeout);
  9898. }
  9899. }, callback);
  9900. };
  9901. return AsyncLoop;
  9902. }());
  9903. BABYLON.AsyncLoop = AsyncLoop;
  9904. })(BABYLON || (BABYLON = {}));
  9905. //# sourceMappingURL=babylon.tools.js.map
  9906. "use strict";
  9907. var BABYLON;
  9908. (function (BABYLON) {
  9909. var PromiseStates;
  9910. (function (PromiseStates) {
  9911. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9912. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9913. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9914. })(PromiseStates || (PromiseStates = {}));
  9915. var FulFillmentAgregator = /** @class */ (function () {
  9916. function FulFillmentAgregator() {
  9917. this.count = 0;
  9918. this.target = 0;
  9919. this.results = [];
  9920. }
  9921. return FulFillmentAgregator;
  9922. }());
  9923. var InternalPromise = /** @class */ (function () {
  9924. function InternalPromise(resolver) {
  9925. var _this = this;
  9926. this._state = PromiseStates.Pending;
  9927. this._children = new Array();
  9928. this._rejectWasConsumed = false;
  9929. if (!resolver) {
  9930. return;
  9931. }
  9932. try {
  9933. resolver(function (value) {
  9934. _this._resolve(value);
  9935. }, function (reason) {
  9936. _this._reject(reason);
  9937. });
  9938. }
  9939. catch (e) {
  9940. this._reject(e);
  9941. }
  9942. }
  9943. InternalPromise.prototype.catch = function (onRejected) {
  9944. return this.then(undefined, onRejected);
  9945. };
  9946. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9947. var _this = this;
  9948. var newPromise = new InternalPromise();
  9949. newPromise._onFulfilled = onFulfilled;
  9950. newPromise._onRejected = onRejected;
  9951. // Composition
  9952. this._children.push(newPromise);
  9953. if (this._state !== PromiseStates.Pending) {
  9954. BABYLON.Tools.SetImmediate(function () {
  9955. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9956. var returnedValue = newPromise._resolve(_this._result);
  9957. if (returnedValue !== undefined && returnedValue !== null) {
  9958. if (returnedValue._state !== undefined) {
  9959. var returnedPromise = returnedValue;
  9960. newPromise._children.push(returnedPromise);
  9961. newPromise = returnedPromise;
  9962. }
  9963. else {
  9964. newPromise._result = returnedValue;
  9965. }
  9966. }
  9967. }
  9968. else {
  9969. newPromise._reject(_this._reason);
  9970. }
  9971. });
  9972. }
  9973. return newPromise;
  9974. };
  9975. InternalPromise.prototype._moveChildren = function (children) {
  9976. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9977. if (this._state === PromiseStates.Fulfilled) {
  9978. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9979. var child = _b[_i];
  9980. child._resolve(this._result);
  9981. }
  9982. }
  9983. else if (this._state === PromiseStates.Rejected) {
  9984. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9985. var child = _d[_c];
  9986. child._reject(this._reason);
  9987. }
  9988. }
  9989. var _a;
  9990. };
  9991. InternalPromise.prototype._resolve = function (value) {
  9992. try {
  9993. this._state = PromiseStates.Fulfilled;
  9994. var returnedValue = null;
  9995. if (this._onFulfilled) {
  9996. returnedValue = this._onFulfilled(value);
  9997. }
  9998. if (returnedValue !== undefined && returnedValue !== null) {
  9999. if (returnedValue._state !== undefined) {
  10000. // Transmit children
  10001. var returnedPromise = returnedValue;
  10002. returnedPromise._moveChildren(this._children);
  10003. value = returnedPromise._result;
  10004. }
  10005. else {
  10006. value = returnedValue;
  10007. }
  10008. }
  10009. this._result = value;
  10010. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10011. var child = _a[_i];
  10012. child._resolve(value);
  10013. }
  10014. this._children.length = 0;
  10015. delete this._onFulfilled;
  10016. delete this._onRejected;
  10017. }
  10018. catch (e) {
  10019. this._reject(e, true);
  10020. }
  10021. };
  10022. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10023. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10024. this._state = PromiseStates.Rejected;
  10025. this._reason = reason;
  10026. if (this._onRejected && !onLocalThrow) {
  10027. try {
  10028. this._onRejected(reason);
  10029. this._rejectWasConsumed = true;
  10030. }
  10031. catch (e) {
  10032. reason = e;
  10033. }
  10034. }
  10035. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10036. var child = _a[_i];
  10037. if (this._rejectWasConsumed) {
  10038. child._resolve(null);
  10039. }
  10040. else {
  10041. child._reject(reason);
  10042. }
  10043. }
  10044. this._children.length = 0;
  10045. delete this._onFulfilled;
  10046. delete this._onRejected;
  10047. };
  10048. InternalPromise.resolve = function (value) {
  10049. var newPromise = new InternalPromise();
  10050. newPromise._resolve(value);
  10051. return newPromise;
  10052. };
  10053. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10054. promise.then(function (value) {
  10055. agregator.results[index] = value;
  10056. agregator.count++;
  10057. if (agregator.count === agregator.target) {
  10058. agregator.rootPromise._resolve(agregator.results);
  10059. }
  10060. return null;
  10061. }, function (reason) {
  10062. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10063. agregator.rootPromise._reject(reason);
  10064. }
  10065. });
  10066. };
  10067. InternalPromise.all = function (promises) {
  10068. var newPromise = new InternalPromise();
  10069. var agregator = new FulFillmentAgregator();
  10070. agregator.target = promises.length;
  10071. agregator.rootPromise = newPromise;
  10072. if (promises.length) {
  10073. for (var index = 0; index < promises.length; index++) {
  10074. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10075. }
  10076. }
  10077. else {
  10078. newPromise._resolve([]);
  10079. }
  10080. return newPromise;
  10081. };
  10082. InternalPromise.race = function (promises) {
  10083. var newPromise = new InternalPromise();
  10084. if (promises.length) {
  10085. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10086. var promise = promises_1[_i];
  10087. promise.then(function (value) {
  10088. if (newPromise) {
  10089. newPromise._resolve(value);
  10090. newPromise = null;
  10091. }
  10092. return null;
  10093. }, function (reason) {
  10094. if (newPromise) {
  10095. newPromise._reject(reason);
  10096. newPromise = null;
  10097. }
  10098. });
  10099. }
  10100. }
  10101. return newPromise;
  10102. };
  10103. return InternalPromise;
  10104. }());
  10105. /**
  10106. * Helper class that provides a small promise polyfill
  10107. */
  10108. var PromisePolyfill = /** @class */ (function () {
  10109. function PromisePolyfill() {
  10110. }
  10111. /**
  10112. * Static function used to check if the polyfill is required
  10113. * If this is the case then the function will inject the polyfill to window.Promise
  10114. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10115. */
  10116. PromisePolyfill.Apply = function (force) {
  10117. if (force === void 0) { force = false; }
  10118. if (force || typeof Promise === 'undefined') {
  10119. var root = window;
  10120. root.Promise = InternalPromise;
  10121. }
  10122. };
  10123. return PromisePolyfill;
  10124. }());
  10125. BABYLON.PromisePolyfill = PromisePolyfill;
  10126. })(BABYLON || (BABYLON = {}));
  10127. //# sourceMappingURL=babylon.promise.js.map
  10128. "use strict";
  10129. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10130. var BABYLON;
  10131. (function (BABYLON) {
  10132. /**
  10133. * Helper class to push actions to a pool of workers.
  10134. */
  10135. var WorkerPool = /** @class */ (function () {
  10136. /**
  10137. * Constructor
  10138. * @param workers Array of workers to use for actions
  10139. */
  10140. function WorkerPool(workers) {
  10141. this._pendingActions = new Array();
  10142. this._workerInfos = workers.map(function (worker) { return ({
  10143. worker: worker,
  10144. active: false
  10145. }); });
  10146. }
  10147. /**
  10148. * Terminates all workers and clears any pending actions.
  10149. */
  10150. WorkerPool.prototype.dispose = function () {
  10151. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10152. var workerInfo = _a[_i];
  10153. workerInfo.worker.terminate();
  10154. }
  10155. delete this._workerInfos;
  10156. delete this._pendingActions;
  10157. };
  10158. /**
  10159. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10160. * pended until a worker has completed its action.
  10161. * @param action The action to perform. Call onComplete when the action is complete.
  10162. */
  10163. WorkerPool.prototype.push = function (action) {
  10164. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10165. var workerInfo = _a[_i];
  10166. if (!workerInfo.active) {
  10167. this._execute(workerInfo, action);
  10168. return;
  10169. }
  10170. }
  10171. this._pendingActions.push(action);
  10172. };
  10173. WorkerPool.prototype._execute = function (workerInfo, action) {
  10174. var _this = this;
  10175. workerInfo.active = true;
  10176. action(workerInfo.worker, function () {
  10177. workerInfo.active = false;
  10178. var nextAction = _this._pendingActions.shift();
  10179. if (nextAction) {
  10180. _this._execute(workerInfo, nextAction);
  10181. }
  10182. });
  10183. };
  10184. return WorkerPool;
  10185. }());
  10186. BABYLON.WorkerPool = WorkerPool;
  10187. })(BABYLON || (BABYLON = {}));
  10188. //# sourceMappingURL=babylon.workerPool.js.map
  10189. "use strict";
  10190. var BABYLON;
  10191. (function (BABYLON) {
  10192. var _AlphaState = /** @class */ (function () {
  10193. /**
  10194. * Initializes the state.
  10195. */
  10196. function _AlphaState() {
  10197. this._isAlphaBlendDirty = false;
  10198. this._isBlendFunctionParametersDirty = false;
  10199. this._isBlendEquationParametersDirty = false;
  10200. this._isBlendConstantsDirty = false;
  10201. this._alphaBlend = false;
  10202. this._blendFunctionParameters = new Array(4);
  10203. this._blendEquationParameters = new Array(2);
  10204. this._blendConstants = new Array(4);
  10205. this.reset();
  10206. }
  10207. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10208. get: function () {
  10209. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10210. },
  10211. enumerable: true,
  10212. configurable: true
  10213. });
  10214. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10215. get: function () {
  10216. return this._alphaBlend;
  10217. },
  10218. set: function (value) {
  10219. if (this._alphaBlend === value) {
  10220. return;
  10221. }
  10222. this._alphaBlend = value;
  10223. this._isAlphaBlendDirty = true;
  10224. },
  10225. enumerable: true,
  10226. configurable: true
  10227. });
  10228. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10229. if (this._blendConstants[0] === r &&
  10230. this._blendConstants[1] === g &&
  10231. this._blendConstants[2] === b &&
  10232. this._blendConstants[3] === a) {
  10233. return;
  10234. }
  10235. this._blendConstants[0] = r;
  10236. this._blendConstants[1] = g;
  10237. this._blendConstants[2] = b;
  10238. this._blendConstants[3] = a;
  10239. this._isBlendConstantsDirty = true;
  10240. };
  10241. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10242. if (this._blendFunctionParameters[0] === value0 &&
  10243. this._blendFunctionParameters[1] === value1 &&
  10244. this._blendFunctionParameters[2] === value2 &&
  10245. this._blendFunctionParameters[3] === value3) {
  10246. return;
  10247. }
  10248. this._blendFunctionParameters[0] = value0;
  10249. this._blendFunctionParameters[1] = value1;
  10250. this._blendFunctionParameters[2] = value2;
  10251. this._blendFunctionParameters[3] = value3;
  10252. this._isBlendFunctionParametersDirty = true;
  10253. };
  10254. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10255. if (this._blendEquationParameters[0] === rgb &&
  10256. this._blendEquationParameters[1] === alpha) {
  10257. return;
  10258. }
  10259. this._blendEquationParameters[0] = rgb;
  10260. this._blendEquationParameters[1] = alpha;
  10261. this._isBlendEquationParametersDirty = true;
  10262. };
  10263. _AlphaState.prototype.reset = function () {
  10264. this._alphaBlend = false;
  10265. this._blendFunctionParameters[0] = null;
  10266. this._blendFunctionParameters[1] = null;
  10267. this._blendFunctionParameters[2] = null;
  10268. this._blendFunctionParameters[3] = null;
  10269. this._blendEquationParameters[0] = null;
  10270. this._blendEquationParameters[1] = null;
  10271. this._blendConstants[0] = null;
  10272. this._blendConstants[1] = null;
  10273. this._blendConstants[2] = null;
  10274. this._blendConstants[3] = null;
  10275. this._isAlphaBlendDirty = true;
  10276. this._isBlendFunctionParametersDirty = false;
  10277. this._isBlendEquationParametersDirty = false;
  10278. this._isBlendConstantsDirty = false;
  10279. };
  10280. _AlphaState.prototype.apply = function (gl) {
  10281. if (!this.isDirty) {
  10282. return;
  10283. }
  10284. // Alpha blend
  10285. if (this._isAlphaBlendDirty) {
  10286. if (this._alphaBlend) {
  10287. gl.enable(gl.BLEND);
  10288. }
  10289. else {
  10290. gl.disable(gl.BLEND);
  10291. }
  10292. this._isAlphaBlendDirty = false;
  10293. }
  10294. // Alpha function
  10295. if (this._isBlendFunctionParametersDirty) {
  10296. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10297. this._isBlendFunctionParametersDirty = false;
  10298. }
  10299. // Alpha equation
  10300. if (this._isBlendEquationParametersDirty) {
  10301. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10302. this._isBlendEquationParametersDirty = false;
  10303. }
  10304. // Constants
  10305. if (this._isBlendConstantsDirty) {
  10306. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10307. this._isBlendConstantsDirty = false;
  10308. }
  10309. };
  10310. return _AlphaState;
  10311. }());
  10312. BABYLON._AlphaState = _AlphaState;
  10313. })(BABYLON || (BABYLON = {}));
  10314. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10315. "use strict";
  10316. var BABYLON;
  10317. (function (BABYLON) {
  10318. var _DepthCullingState = /** @class */ (function () {
  10319. /**
  10320. * Initializes the state.
  10321. */
  10322. function _DepthCullingState() {
  10323. this._isDepthTestDirty = false;
  10324. this._isDepthMaskDirty = false;
  10325. this._isDepthFuncDirty = false;
  10326. this._isCullFaceDirty = false;
  10327. this._isCullDirty = false;
  10328. this._isZOffsetDirty = false;
  10329. this._isFrontFaceDirty = false;
  10330. this.reset();
  10331. }
  10332. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10333. get: function () {
  10334. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10335. },
  10336. enumerable: true,
  10337. configurable: true
  10338. });
  10339. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10340. get: function () {
  10341. return this._zOffset;
  10342. },
  10343. set: function (value) {
  10344. if (this._zOffset === value) {
  10345. return;
  10346. }
  10347. this._zOffset = value;
  10348. this._isZOffsetDirty = true;
  10349. },
  10350. enumerable: true,
  10351. configurable: true
  10352. });
  10353. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10354. get: function () {
  10355. return this._cullFace;
  10356. },
  10357. set: function (value) {
  10358. if (this._cullFace === value) {
  10359. return;
  10360. }
  10361. this._cullFace = value;
  10362. this._isCullFaceDirty = true;
  10363. },
  10364. enumerable: true,
  10365. configurable: true
  10366. });
  10367. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10368. get: function () {
  10369. return this._cull;
  10370. },
  10371. set: function (value) {
  10372. if (this._cull === value) {
  10373. return;
  10374. }
  10375. this._cull = value;
  10376. this._isCullDirty = true;
  10377. },
  10378. enumerable: true,
  10379. configurable: true
  10380. });
  10381. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10382. get: function () {
  10383. return this._depthFunc;
  10384. },
  10385. set: function (value) {
  10386. if (this._depthFunc === value) {
  10387. return;
  10388. }
  10389. this._depthFunc = value;
  10390. this._isDepthFuncDirty = true;
  10391. },
  10392. enumerable: true,
  10393. configurable: true
  10394. });
  10395. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10396. get: function () {
  10397. return this._depthMask;
  10398. },
  10399. set: function (value) {
  10400. if (this._depthMask === value) {
  10401. return;
  10402. }
  10403. this._depthMask = value;
  10404. this._isDepthMaskDirty = true;
  10405. },
  10406. enumerable: true,
  10407. configurable: true
  10408. });
  10409. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10410. get: function () {
  10411. return this._depthTest;
  10412. },
  10413. set: function (value) {
  10414. if (this._depthTest === value) {
  10415. return;
  10416. }
  10417. this._depthTest = value;
  10418. this._isDepthTestDirty = true;
  10419. },
  10420. enumerable: true,
  10421. configurable: true
  10422. });
  10423. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10424. get: function () {
  10425. return this._frontFace;
  10426. },
  10427. set: function (value) {
  10428. if (this._frontFace === value) {
  10429. return;
  10430. }
  10431. this._frontFace = value;
  10432. this._isFrontFaceDirty = true;
  10433. },
  10434. enumerable: true,
  10435. configurable: true
  10436. });
  10437. _DepthCullingState.prototype.reset = function () {
  10438. this._depthMask = true;
  10439. this._depthTest = true;
  10440. this._depthFunc = null;
  10441. this._cullFace = null;
  10442. this._cull = null;
  10443. this._zOffset = 0;
  10444. this._frontFace = null;
  10445. this._isDepthTestDirty = true;
  10446. this._isDepthMaskDirty = true;
  10447. this._isDepthFuncDirty = false;
  10448. this._isCullFaceDirty = false;
  10449. this._isCullDirty = false;
  10450. this._isZOffsetDirty = false;
  10451. this._isFrontFaceDirty = false;
  10452. };
  10453. _DepthCullingState.prototype.apply = function (gl) {
  10454. if (!this.isDirty) {
  10455. return;
  10456. }
  10457. // Cull
  10458. if (this._isCullDirty) {
  10459. if (this.cull) {
  10460. gl.enable(gl.CULL_FACE);
  10461. }
  10462. else {
  10463. gl.disable(gl.CULL_FACE);
  10464. }
  10465. this._isCullDirty = false;
  10466. }
  10467. // Cull face
  10468. if (this._isCullFaceDirty) {
  10469. gl.cullFace(this.cullFace);
  10470. this._isCullFaceDirty = false;
  10471. }
  10472. // Depth mask
  10473. if (this._isDepthMaskDirty) {
  10474. gl.depthMask(this.depthMask);
  10475. this._isDepthMaskDirty = false;
  10476. }
  10477. // Depth test
  10478. if (this._isDepthTestDirty) {
  10479. if (this.depthTest) {
  10480. gl.enable(gl.DEPTH_TEST);
  10481. }
  10482. else {
  10483. gl.disable(gl.DEPTH_TEST);
  10484. }
  10485. this._isDepthTestDirty = false;
  10486. }
  10487. // Depth func
  10488. if (this._isDepthFuncDirty) {
  10489. gl.depthFunc(this.depthFunc);
  10490. this._isDepthFuncDirty = false;
  10491. }
  10492. // zOffset
  10493. if (this._isZOffsetDirty) {
  10494. if (this.zOffset) {
  10495. gl.enable(gl.POLYGON_OFFSET_FILL);
  10496. gl.polygonOffset(this.zOffset, 0);
  10497. }
  10498. else {
  10499. gl.disable(gl.POLYGON_OFFSET_FILL);
  10500. }
  10501. this._isZOffsetDirty = false;
  10502. }
  10503. // Front face
  10504. if (this._isFrontFaceDirty) {
  10505. gl.frontFace(this.frontFace);
  10506. this._isFrontFaceDirty = false;
  10507. }
  10508. };
  10509. return _DepthCullingState;
  10510. }());
  10511. BABYLON._DepthCullingState = _DepthCullingState;
  10512. })(BABYLON || (BABYLON = {}));
  10513. //# sourceMappingURL=babylon.depthCullingState.js.map
  10514. "use strict";
  10515. var BABYLON;
  10516. (function (BABYLON) {
  10517. var _StencilState = /** @class */ (function () {
  10518. function _StencilState() {
  10519. this._isStencilTestDirty = false;
  10520. this._isStencilMaskDirty = false;
  10521. this._isStencilFuncDirty = false;
  10522. this._isStencilOpDirty = false;
  10523. this.reset();
  10524. }
  10525. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10526. get: function () {
  10527. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10528. },
  10529. enumerable: true,
  10530. configurable: true
  10531. });
  10532. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10533. get: function () {
  10534. return this._stencilFunc;
  10535. },
  10536. set: function (value) {
  10537. if (this._stencilFunc === value) {
  10538. return;
  10539. }
  10540. this._stencilFunc = value;
  10541. this._isStencilFuncDirty = true;
  10542. },
  10543. enumerable: true,
  10544. configurable: true
  10545. });
  10546. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10547. get: function () {
  10548. return this._stencilFuncRef;
  10549. },
  10550. set: function (value) {
  10551. if (this._stencilFuncRef === value) {
  10552. return;
  10553. }
  10554. this._stencilFuncRef = value;
  10555. this._isStencilFuncDirty = true;
  10556. },
  10557. enumerable: true,
  10558. configurable: true
  10559. });
  10560. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10561. get: function () {
  10562. return this._stencilFuncMask;
  10563. },
  10564. set: function (value) {
  10565. if (this._stencilFuncMask === value) {
  10566. return;
  10567. }
  10568. this._stencilFuncMask = value;
  10569. this._isStencilFuncDirty = true;
  10570. },
  10571. enumerable: true,
  10572. configurable: true
  10573. });
  10574. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10575. get: function () {
  10576. return this._stencilOpStencilFail;
  10577. },
  10578. set: function (value) {
  10579. if (this._stencilOpStencilFail === value) {
  10580. return;
  10581. }
  10582. this._stencilOpStencilFail = value;
  10583. this._isStencilOpDirty = true;
  10584. },
  10585. enumerable: true,
  10586. configurable: true
  10587. });
  10588. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10589. get: function () {
  10590. return this._stencilOpDepthFail;
  10591. },
  10592. set: function (value) {
  10593. if (this._stencilOpDepthFail === value) {
  10594. return;
  10595. }
  10596. this._stencilOpDepthFail = value;
  10597. this._isStencilOpDirty = true;
  10598. },
  10599. enumerable: true,
  10600. configurable: true
  10601. });
  10602. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10603. get: function () {
  10604. return this._stencilOpStencilDepthPass;
  10605. },
  10606. set: function (value) {
  10607. if (this._stencilOpStencilDepthPass === value) {
  10608. return;
  10609. }
  10610. this._stencilOpStencilDepthPass = value;
  10611. this._isStencilOpDirty = true;
  10612. },
  10613. enumerable: true,
  10614. configurable: true
  10615. });
  10616. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10617. get: function () {
  10618. return this._stencilMask;
  10619. },
  10620. set: function (value) {
  10621. if (this._stencilMask === value) {
  10622. return;
  10623. }
  10624. this._stencilMask = value;
  10625. this._isStencilMaskDirty = true;
  10626. },
  10627. enumerable: true,
  10628. configurable: true
  10629. });
  10630. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10631. get: function () {
  10632. return this._stencilTest;
  10633. },
  10634. set: function (value) {
  10635. if (this._stencilTest === value) {
  10636. return;
  10637. }
  10638. this._stencilTest = value;
  10639. this._isStencilTestDirty = true;
  10640. },
  10641. enumerable: true,
  10642. configurable: true
  10643. });
  10644. _StencilState.prototype.reset = function () {
  10645. this._stencilTest = false;
  10646. this._stencilMask = 0xFF;
  10647. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10648. this._stencilFuncRef = 1;
  10649. this._stencilFuncMask = 0xFF;
  10650. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10651. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10652. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10653. this._isStencilTestDirty = true;
  10654. this._isStencilMaskDirty = true;
  10655. this._isStencilFuncDirty = true;
  10656. this._isStencilOpDirty = true;
  10657. };
  10658. _StencilState.prototype.apply = function (gl) {
  10659. if (!this.isDirty) {
  10660. return;
  10661. }
  10662. // Stencil test
  10663. if (this._isStencilTestDirty) {
  10664. if (this.stencilTest) {
  10665. gl.enable(gl.STENCIL_TEST);
  10666. }
  10667. else {
  10668. gl.disable(gl.STENCIL_TEST);
  10669. }
  10670. this._isStencilTestDirty = false;
  10671. }
  10672. // Stencil mask
  10673. if (this._isStencilMaskDirty) {
  10674. gl.stencilMask(this.stencilMask);
  10675. this._isStencilMaskDirty = false;
  10676. }
  10677. // Stencil func
  10678. if (this._isStencilFuncDirty) {
  10679. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10680. this._isStencilFuncDirty = false;
  10681. }
  10682. // Stencil op
  10683. if (this._isStencilOpDirty) {
  10684. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10685. this._isStencilOpDirty = false;
  10686. }
  10687. };
  10688. return _StencilState;
  10689. }());
  10690. BABYLON._StencilState = _StencilState;
  10691. })(BABYLON || (BABYLON = {}));
  10692. //# sourceMappingURL=babylon.stencilState.js.map
  10693. "use strict";
  10694. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10695. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10696. s = arguments[i];
  10697. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10698. t[p] = s[p];
  10699. }
  10700. return t;
  10701. };
  10702. var BABYLON;
  10703. (function (BABYLON) {
  10704. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10705. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10706. };
  10707. var compileRawShader = function (gl, source, type) {
  10708. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10709. gl.shaderSource(shader, source);
  10710. gl.compileShader(shader);
  10711. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10712. var log = gl.getShaderInfoLog(shader);
  10713. if (log) {
  10714. throw new Error(log);
  10715. }
  10716. }
  10717. if (!shader) {
  10718. throw new Error("Something went wrong while compile the shader.");
  10719. }
  10720. return shader;
  10721. };
  10722. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10723. var magFilter = gl.NEAREST;
  10724. var minFilter = gl.NEAREST;
  10725. switch (samplingMode) {
  10726. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10727. magFilter = gl.LINEAR;
  10728. if (generateMipMaps) {
  10729. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10730. }
  10731. else {
  10732. minFilter = gl.LINEAR;
  10733. }
  10734. break;
  10735. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10736. magFilter = gl.LINEAR;
  10737. if (generateMipMaps) {
  10738. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10739. }
  10740. else {
  10741. minFilter = gl.LINEAR;
  10742. }
  10743. break;
  10744. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10745. magFilter = gl.NEAREST;
  10746. if (generateMipMaps) {
  10747. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10748. }
  10749. else {
  10750. minFilter = gl.NEAREST;
  10751. }
  10752. break;
  10753. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10754. magFilter = gl.NEAREST;
  10755. if (generateMipMaps) {
  10756. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10757. }
  10758. else {
  10759. minFilter = gl.NEAREST;
  10760. }
  10761. break;
  10762. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10763. magFilter = gl.NEAREST;
  10764. if (generateMipMaps) {
  10765. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10766. }
  10767. else {
  10768. minFilter = gl.LINEAR;
  10769. }
  10770. break;
  10771. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10772. magFilter = gl.NEAREST;
  10773. if (generateMipMaps) {
  10774. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10775. }
  10776. else {
  10777. minFilter = gl.LINEAR;
  10778. }
  10779. break;
  10780. case BABYLON.Texture.NEAREST_LINEAR:
  10781. magFilter = gl.NEAREST;
  10782. minFilter = gl.LINEAR;
  10783. break;
  10784. case BABYLON.Texture.NEAREST_NEAREST:
  10785. magFilter = gl.NEAREST;
  10786. minFilter = gl.NEAREST;
  10787. break;
  10788. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10789. magFilter = gl.LINEAR;
  10790. if (generateMipMaps) {
  10791. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10792. }
  10793. else {
  10794. minFilter = gl.NEAREST;
  10795. }
  10796. break;
  10797. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10798. magFilter = gl.LINEAR;
  10799. if (generateMipMaps) {
  10800. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10801. }
  10802. else {
  10803. minFilter = gl.NEAREST;
  10804. }
  10805. break;
  10806. case BABYLON.Texture.LINEAR_LINEAR:
  10807. magFilter = gl.LINEAR;
  10808. minFilter = gl.LINEAR;
  10809. break;
  10810. case BABYLON.Texture.LINEAR_NEAREST:
  10811. magFilter = gl.LINEAR;
  10812. minFilter = gl.NEAREST;
  10813. break;
  10814. }
  10815. return {
  10816. min: minFilter,
  10817. mag: magFilter
  10818. };
  10819. };
  10820. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10821. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10822. var img;
  10823. var onload = function () {
  10824. loadedImages[index] = img;
  10825. loadedImages._internalCount++;
  10826. if (scene) {
  10827. scene._removePendingData(img);
  10828. }
  10829. if (loadedImages._internalCount === 6) {
  10830. onfinish(loadedImages);
  10831. }
  10832. };
  10833. var onerror = function (message, exception) {
  10834. if (scene) {
  10835. scene._removePendingData(img);
  10836. }
  10837. if (onErrorCallBack) {
  10838. onErrorCallBack(message, exception);
  10839. }
  10840. };
  10841. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10842. if (scene) {
  10843. scene._addPendingData(img);
  10844. }
  10845. };
  10846. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10847. if (onError === void 0) { onError = null; }
  10848. var loadedImages = [];
  10849. loadedImages._internalCount = 0;
  10850. for (var index = 0; index < 6; index++) {
  10851. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10852. }
  10853. };
  10854. var BufferPointer = /** @class */ (function () {
  10855. function BufferPointer() {
  10856. }
  10857. return BufferPointer;
  10858. }());
  10859. /**
  10860. * Interface for attribute information associated with buffer instanciation
  10861. */
  10862. var InstancingAttributeInfo = /** @class */ (function () {
  10863. function InstancingAttributeInfo() {
  10864. }
  10865. return InstancingAttributeInfo;
  10866. }());
  10867. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10868. /**
  10869. * Define options used to create a render target texture
  10870. */
  10871. var RenderTargetCreationOptions = /** @class */ (function () {
  10872. function RenderTargetCreationOptions() {
  10873. }
  10874. return RenderTargetCreationOptions;
  10875. }());
  10876. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10877. /**
  10878. * Define options used to create a depth texture
  10879. */
  10880. var DepthTextureCreationOptions = /** @class */ (function () {
  10881. function DepthTextureCreationOptions() {
  10882. }
  10883. return DepthTextureCreationOptions;
  10884. }());
  10885. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10886. /**
  10887. * Class used to describe the capabilities of the engine relatively to the current browser
  10888. */
  10889. var EngineCapabilities = /** @class */ (function () {
  10890. function EngineCapabilities() {
  10891. }
  10892. return EngineCapabilities;
  10893. }());
  10894. BABYLON.EngineCapabilities = EngineCapabilities;
  10895. /**
  10896. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  10897. */
  10898. var Engine = /** @class */ (function () {
  10899. /**
  10900. * Creates a new engine
  10901. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10902. * @param antialias defines enable antialiasing (default: false)
  10903. * @param options defines further options to be sent to the getContext() function
  10904. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10905. */
  10906. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10907. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10908. var _this = this;
  10909. // Public members
  10910. /**
  10911. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  10912. */
  10913. this.forcePOTTextures = false;
  10914. /**
  10915. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  10916. */
  10917. this.isFullscreen = false;
  10918. /**
  10919. * Gets a boolean indicating if the pointer is currently locked
  10920. */
  10921. this.isPointerLock = false;
  10922. /**
  10923. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  10924. */
  10925. this.cullBackFaces = true;
  10926. /**
  10927. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  10928. */
  10929. this.renderEvenInBackground = true;
  10930. /**
  10931. * Gets or sets a boolean indicating that cache can be kept between frames
  10932. */
  10933. this.preventCacheWipeBetweenFrames = false;
  10934. /**
  10935. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  10936. **/
  10937. this.enableOfflineSupport = false;
  10938. /**
  10939. * Gets the list of created scenes
  10940. */
  10941. this.scenes = new Array();
  10942. /**
  10943. * Gets the list of created postprocesses
  10944. */
  10945. this.postProcesses = new Array();
  10946. // Observables
  10947. /**
  10948. * Observable event triggered each time the rendering canvas is resized
  10949. */
  10950. this.onResizeObservable = new BABYLON.Observable();
  10951. /**
  10952. * Observable event triggered each time the canvas loses focus
  10953. */
  10954. this.onCanvasBlurObservable = new BABYLON.Observable();
  10955. /**
  10956. * Observable event triggered each time the canvas gains focus
  10957. */
  10958. this.onCanvasFocusObservable = new BABYLON.Observable();
  10959. /**
  10960. * Observable event triggered each time the canvas receives pointerout event
  10961. */
  10962. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10963. /**
  10964. * Observable event triggered before each texture is initialized
  10965. */
  10966. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10967. //WebVR
  10968. this._vrDisplay = undefined;
  10969. this._vrSupported = false;
  10970. this._vrExclusivePointerMode = false;
  10971. // Uniform buffers list
  10972. /**
  10973. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  10974. */
  10975. this.disableUniformBuffers = false;
  10976. /** @ignore */
  10977. this._uniformBuffers = new Array();
  10978. // Observables
  10979. /**
  10980. * Observable raised when the engine begins a new frame
  10981. */
  10982. this.onBeginFrameObservable = new BABYLON.Observable();
  10983. /**
  10984. * Observable raised when the engine ends the current frame
  10985. */
  10986. this.onEndFrameObservable = new BABYLON.Observable();
  10987. /**
  10988. * Observable raised when the engine is about to compile a shader
  10989. */
  10990. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10991. /**
  10992. * Observable raised when the engine has jsut compiled a shader
  10993. */
  10994. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10995. this._windowIsBackground = false;
  10996. this._webGLVersion = 1.0;
  10997. /** @ignore */
  10998. this._badOS = false;
  10999. /** @ignore */
  11000. this._badDesktopOS = false;
  11001. /**
  11002. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11003. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11004. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11005. */
  11006. this.disableTextureBindingOptimization = false;
  11007. /**
  11008. * Observable signaled when VR display mode changes
  11009. */
  11010. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11011. /**
  11012. * Observable signaled when VR request present is complete
  11013. */
  11014. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11015. /**
  11016. * Observable signaled when VR request present starts
  11017. */
  11018. this.onVRRequestPresentStart = new BABYLON.Observable();
  11019. this._colorWrite = true;
  11020. /** @ignore */
  11021. this._drawCalls = new BABYLON.PerfCounter();
  11022. /** @ignore */
  11023. this._textureCollisions = new BABYLON.PerfCounter();
  11024. this._renderingQueueLaunched = false;
  11025. this._activeRenderLoops = new Array();
  11026. // Deterministic lockstepMaxSteps
  11027. this._deterministicLockstep = false;
  11028. this._lockstepMaxSteps = 4;
  11029. // Lost context
  11030. /**
  11031. * Observable signaled when a context lost event is raised
  11032. */
  11033. this.onContextLostObservable = new BABYLON.Observable();
  11034. /**
  11035. * Observable signaled when a context restored event is raised
  11036. */
  11037. this.onContextRestoredObservable = new BABYLON.Observable();
  11038. this._contextWasLost = false;
  11039. this._doNotHandleContextLost = false;
  11040. // FPS
  11041. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11042. this._fps = 60;
  11043. this._deltaTime = 0;
  11044. /**
  11045. * Turn this value on if you want to pause FPS computation when in background
  11046. */
  11047. this.disablePerformanceMonitorInBackground = false;
  11048. // States
  11049. /** @ignore */
  11050. this._depthCullingState = new BABYLON._DepthCullingState();
  11051. /** @ignore */
  11052. this._stencilState = new BABYLON._StencilState();
  11053. /** @ignore */
  11054. this._alphaState = new BABYLON._AlphaState();
  11055. /** @ignore */
  11056. this._alphaMode = Engine.ALPHA_DISABLE;
  11057. // Cache
  11058. this._internalTexturesCache = new Array();
  11059. /** @ignore */
  11060. this._activeChannel = 0;
  11061. this._currentTextureChannel = -1;
  11062. /** @ignore */
  11063. this._boundTexturesCache = {};
  11064. this._compiledEffects = {};
  11065. this._vertexAttribArraysEnabled = [];
  11066. this._uintIndicesCurrentlySet = false;
  11067. this._currentBoundBuffer = new Array();
  11068. this._currentBufferPointers = new Array();
  11069. this._currentInstanceLocations = new Array();
  11070. this._currentInstanceBuffers = new Array();
  11071. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11072. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11073. this._vaoRecordInProgress = false;
  11074. this._mustWipeVertexAttributes = false;
  11075. this._nextFreeTextureSlots = new Array();
  11076. this._maxSimultaneousTextures = 0;
  11077. this._activeRequests = new Array();
  11078. // Hardware supported Compressed Textures
  11079. this._texturesSupported = new Array();
  11080. this._onVRFullScreenTriggered = function () {
  11081. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11082. //get the old size before we change
  11083. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11084. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11085. //get the width and height, change the render size
  11086. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11087. _this.setHardwareScalingLevel(1);
  11088. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11089. }
  11090. else {
  11091. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11092. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11093. }
  11094. };
  11095. this._boundUniforms = {};
  11096. // Register promises
  11097. BABYLON.PromisePolyfill.Apply();
  11098. var canvas = null;
  11099. Engine.Instances.push(this);
  11100. if (!canvasOrContext) {
  11101. return;
  11102. }
  11103. options = options || {};
  11104. if (canvasOrContext.getContext) {
  11105. canvas = canvasOrContext;
  11106. this._renderingCanvas = canvas;
  11107. if (antialias != null) {
  11108. options.antialias = antialias;
  11109. }
  11110. if (options.deterministicLockstep === undefined) {
  11111. options.deterministicLockstep = false;
  11112. }
  11113. if (options.lockstepMaxSteps === undefined) {
  11114. options.lockstepMaxSteps = 4;
  11115. }
  11116. if (options.preserveDrawingBuffer === undefined) {
  11117. options.preserveDrawingBuffer = false;
  11118. }
  11119. if (options.audioEngine === undefined) {
  11120. options.audioEngine = true;
  11121. }
  11122. if (options.stencil === undefined) {
  11123. options.stencil = true;
  11124. }
  11125. this._deterministicLockstep = options.deterministicLockstep;
  11126. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11127. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11128. // Exceptions
  11129. if (navigator && navigator.userAgent) {
  11130. var ua = navigator.userAgent;
  11131. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11132. var exception = _a[_i];
  11133. var key = exception.key;
  11134. var targets = exception.targets;
  11135. if (ua.indexOf(key) > -1) {
  11136. if (exception.capture && exception.captureConstraint) {
  11137. var capture = exception.capture;
  11138. var constraint = exception.captureConstraint;
  11139. var regex = new RegExp(capture);
  11140. var matches = regex.exec(ua);
  11141. if (matches && matches.length > 0) {
  11142. var capturedValue = parseInt(matches[matches.length - 1]);
  11143. if (capturedValue >= constraint) {
  11144. continue;
  11145. }
  11146. }
  11147. }
  11148. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11149. var target = targets_1[_b];
  11150. switch (target) {
  11151. case "uniformBuffer":
  11152. this.disableUniformBuffers = true;
  11153. break;
  11154. case "textureBindingOptimization":
  11155. this.disableTextureBindingOptimization = true;
  11156. break;
  11157. }
  11158. }
  11159. }
  11160. }
  11161. }
  11162. // GL
  11163. if (!options.disableWebGL2Support) {
  11164. try {
  11165. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11166. if (this._gl) {
  11167. this._webGLVersion = 2.0;
  11168. }
  11169. }
  11170. catch (e) {
  11171. // Do nothing
  11172. }
  11173. }
  11174. if (!this._gl) {
  11175. if (!canvas) {
  11176. throw new Error("The provided canvas is null or undefined.");
  11177. }
  11178. try {
  11179. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11180. }
  11181. catch (e) {
  11182. throw new Error("WebGL not supported");
  11183. }
  11184. }
  11185. if (!this._gl) {
  11186. throw new Error("WebGL not supported");
  11187. }
  11188. this._onCanvasFocus = function () {
  11189. _this.onCanvasFocusObservable.notifyObservers(_this);
  11190. };
  11191. this._onCanvasBlur = function () {
  11192. _this.onCanvasBlurObservable.notifyObservers(_this);
  11193. };
  11194. canvas.addEventListener("focus", this._onCanvasFocus);
  11195. canvas.addEventListener("blur", this._onCanvasBlur);
  11196. this._onBlur = function () {
  11197. if (_this.disablePerformanceMonitorInBackground) {
  11198. _this._performanceMonitor.disable();
  11199. }
  11200. _this._windowIsBackground = true;
  11201. };
  11202. this._onFocus = function () {
  11203. if (_this.disablePerformanceMonitorInBackground) {
  11204. _this._performanceMonitor.enable();
  11205. }
  11206. _this._windowIsBackground = false;
  11207. };
  11208. this._onCanvasPointerOut = function (ev) {
  11209. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11210. };
  11211. window.addEventListener("blur", this._onBlur);
  11212. window.addEventListener("focus", this._onFocus);
  11213. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11214. // Context lost
  11215. if (!this._doNotHandleContextLost) {
  11216. this._onContextLost = function (evt) {
  11217. evt.preventDefault();
  11218. _this._contextWasLost = true;
  11219. BABYLON.Tools.Warn("WebGL context lost.");
  11220. _this.onContextLostObservable.notifyObservers(_this);
  11221. };
  11222. this._onContextRestored = function (evt) {
  11223. // Adding a timeout to avoid race condition at browser level
  11224. setTimeout(function () {
  11225. // Rebuild gl context
  11226. _this._initGLContext();
  11227. // Rebuild effects
  11228. _this._rebuildEffects();
  11229. // Rebuild textures
  11230. _this._rebuildInternalTextures();
  11231. // Rebuild buffers
  11232. _this._rebuildBuffers();
  11233. // Cache
  11234. _this.wipeCaches(true);
  11235. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11236. _this.onContextRestoredObservable.notifyObservers(_this);
  11237. _this._contextWasLost = false;
  11238. }, 0);
  11239. };
  11240. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11241. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11242. }
  11243. }
  11244. else {
  11245. this._gl = canvasOrContext;
  11246. this._renderingCanvas = this._gl.canvas;
  11247. if (this._gl.renderbufferStorageMultisample) {
  11248. this._webGLVersion = 2.0;
  11249. }
  11250. options.stencil = this._gl.getContextAttributes().stencil;
  11251. }
  11252. // Viewport
  11253. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11254. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11255. this.resize();
  11256. this._isStencilEnable = options.stencil ? true : false;
  11257. this._initGLContext();
  11258. if (canvas) {
  11259. // Fullscreen
  11260. this._onFullscreenChange = function () {
  11261. if (document.fullscreen !== undefined) {
  11262. _this.isFullscreen = document.fullscreen;
  11263. }
  11264. else if (document.mozFullScreen !== undefined) {
  11265. _this.isFullscreen = document.mozFullScreen;
  11266. }
  11267. else if (document.webkitIsFullScreen !== undefined) {
  11268. _this.isFullscreen = document.webkitIsFullScreen;
  11269. }
  11270. else if (document.msIsFullScreen !== undefined) {
  11271. _this.isFullscreen = document.msIsFullScreen;
  11272. }
  11273. // Pointer lock
  11274. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11275. canvas.requestPointerLock = canvas.requestPointerLock ||
  11276. canvas.msRequestPointerLock ||
  11277. canvas.mozRequestPointerLock ||
  11278. canvas.webkitRequestPointerLock;
  11279. if (canvas.requestPointerLock) {
  11280. canvas.requestPointerLock();
  11281. }
  11282. }
  11283. };
  11284. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11285. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11286. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11287. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11288. // Pointer lock
  11289. this._onPointerLockChange = function () {
  11290. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11291. document.webkitPointerLockElement === canvas ||
  11292. document.msPointerLockElement === canvas ||
  11293. document.pointerLockElement === canvas);
  11294. };
  11295. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11296. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11297. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11298. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11299. this._onVRDisplayPointerRestricted = function () {
  11300. if (canvas) {
  11301. canvas.requestPointerLock();
  11302. }
  11303. };
  11304. this._onVRDisplayPointerUnrestricted = function () {
  11305. document.exitPointerLock();
  11306. };
  11307. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11308. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11309. }
  11310. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11311. Engine.audioEngine = new BABYLON.AudioEngine();
  11312. }
  11313. // Prepare buffer pointers
  11314. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11315. this._currentBufferPointers[i] = new BufferPointer();
  11316. }
  11317. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11318. // Load WebVR Devices
  11319. if (options.autoEnableWebVR) {
  11320. this.initWebVR();
  11321. }
  11322. // Detect if we are running on a faulty buggy OS.
  11323. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11324. // Detect if we are running on a faulty buggy desktop OS.
  11325. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11326. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11327. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11328. }
  11329. Object.defineProperty(Engine, "LastCreatedEngine", {
  11330. /**
  11331. * Gets the latest created engine
  11332. */
  11333. get: function () {
  11334. if (Engine.Instances.length === 0) {
  11335. return null;
  11336. }
  11337. return Engine.Instances[Engine.Instances.length - 1];
  11338. },
  11339. enumerable: true,
  11340. configurable: true
  11341. });
  11342. Object.defineProperty(Engine, "LastCreatedScene", {
  11343. /**
  11344. * Gets the latest created scene
  11345. */
  11346. get: function () {
  11347. var lastCreatedEngine = Engine.LastCreatedEngine;
  11348. if (!lastCreatedEngine) {
  11349. return null;
  11350. }
  11351. if (lastCreatedEngine.scenes.length === 0) {
  11352. return null;
  11353. }
  11354. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11355. },
  11356. enumerable: true,
  11357. configurable: true
  11358. });
  11359. /**
  11360. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11361. * @param flag defines which part of the materials must be marked as dirty
  11362. * @param predicate defines a predicate used to filter which materials should be affected
  11363. */
  11364. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11365. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11366. var engine = Engine.Instances[engineIndex];
  11367. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11368. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11369. }
  11370. }
  11371. };
  11372. Object.defineProperty(Engine, "NEVER", {
  11373. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11374. get: function () {
  11375. return Engine._NEVER;
  11376. },
  11377. enumerable: true,
  11378. configurable: true
  11379. });
  11380. Object.defineProperty(Engine, "ALWAYS", {
  11381. /** 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 */
  11382. get: function () {
  11383. return Engine._ALWAYS;
  11384. },
  11385. enumerable: true,
  11386. configurable: true
  11387. });
  11388. Object.defineProperty(Engine, "LESS", {
  11389. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11390. get: function () {
  11391. return Engine._LESS;
  11392. },
  11393. enumerable: true,
  11394. configurable: true
  11395. });
  11396. Object.defineProperty(Engine, "EQUAL", {
  11397. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11398. get: function () {
  11399. return Engine._EQUAL;
  11400. },
  11401. enumerable: true,
  11402. configurable: true
  11403. });
  11404. Object.defineProperty(Engine, "LEQUAL", {
  11405. /** 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 */
  11406. get: function () {
  11407. return Engine._LEQUAL;
  11408. },
  11409. enumerable: true,
  11410. configurable: true
  11411. });
  11412. Object.defineProperty(Engine, "GREATER", {
  11413. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11414. get: function () {
  11415. return Engine._GREATER;
  11416. },
  11417. enumerable: true,
  11418. configurable: true
  11419. });
  11420. Object.defineProperty(Engine, "GEQUAL", {
  11421. /** 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 */
  11422. get: function () {
  11423. return Engine._GEQUAL;
  11424. },
  11425. enumerable: true,
  11426. configurable: true
  11427. });
  11428. Object.defineProperty(Engine, "NOTEQUAL", {
  11429. /** 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 */
  11430. get: function () {
  11431. return Engine._NOTEQUAL;
  11432. },
  11433. enumerable: true,
  11434. configurable: true
  11435. });
  11436. Object.defineProperty(Engine, "KEEP", {
  11437. /** Passed to stencilOperation to specify that stencil value must be kept */
  11438. get: function () {
  11439. return Engine._KEEP;
  11440. },
  11441. enumerable: true,
  11442. configurable: true
  11443. });
  11444. Object.defineProperty(Engine, "REPLACE", {
  11445. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11446. get: function () {
  11447. return Engine._REPLACE;
  11448. },
  11449. enumerable: true,
  11450. configurable: true
  11451. });
  11452. Object.defineProperty(Engine, "INCR", {
  11453. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11454. get: function () {
  11455. return Engine._INCR;
  11456. },
  11457. enumerable: true,
  11458. configurable: true
  11459. });
  11460. Object.defineProperty(Engine, "DECR", {
  11461. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11462. get: function () {
  11463. return Engine._DECR;
  11464. },
  11465. enumerable: true,
  11466. configurable: true
  11467. });
  11468. Object.defineProperty(Engine, "INVERT", {
  11469. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11470. get: function () {
  11471. return Engine._INVERT;
  11472. },
  11473. enumerable: true,
  11474. configurable: true
  11475. });
  11476. Object.defineProperty(Engine, "INCR_WRAP", {
  11477. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11478. get: function () {
  11479. return Engine._INCR_WRAP;
  11480. },
  11481. enumerable: true,
  11482. configurable: true
  11483. });
  11484. Object.defineProperty(Engine, "DECR_WRAP", {
  11485. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11486. get: function () {
  11487. return Engine._DECR_WRAP;
  11488. },
  11489. enumerable: true,
  11490. configurable: true
  11491. });
  11492. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11493. // Alpha
  11494. /** Defines that alpha blending is disabled */
  11495. get: function () {
  11496. return Engine._ALPHA_DISABLE;
  11497. },
  11498. enumerable: true,
  11499. configurable: true
  11500. });
  11501. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11502. /** Defines that alpha blending to SRC + DEST */
  11503. get: function () {
  11504. return Engine._ALPHA_ONEONE;
  11505. },
  11506. enumerable: true,
  11507. configurable: true
  11508. });
  11509. Object.defineProperty(Engine, "ALPHA_ADD", {
  11510. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11511. get: function () {
  11512. return Engine._ALPHA_ADD;
  11513. },
  11514. enumerable: true,
  11515. configurable: true
  11516. });
  11517. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11518. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11519. get: function () {
  11520. return Engine._ALPHA_COMBINE;
  11521. },
  11522. enumerable: true,
  11523. configurable: true
  11524. });
  11525. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11526. /** Defines that alpha blending to DEST - SRC * DEST */
  11527. get: function () {
  11528. return Engine._ALPHA_SUBTRACT;
  11529. },
  11530. enumerable: true,
  11531. configurable: true
  11532. });
  11533. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11534. /** Defines that alpha blending to SRC * DEST */
  11535. get: function () {
  11536. return Engine._ALPHA_MULTIPLY;
  11537. },
  11538. enumerable: true,
  11539. configurable: true
  11540. });
  11541. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11542. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11543. get: function () {
  11544. return Engine._ALPHA_MAXIMIZED;
  11545. },
  11546. enumerable: true,
  11547. configurable: true
  11548. });
  11549. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11550. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11551. get: function () {
  11552. return Engine._ALPHA_PREMULTIPLIED;
  11553. },
  11554. enumerable: true,
  11555. configurable: true
  11556. });
  11557. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11558. /**
  11559. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11560. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11561. */
  11562. get: function () {
  11563. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11564. },
  11565. enumerable: true,
  11566. configurable: true
  11567. });
  11568. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11569. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11570. get: function () {
  11571. return Engine._ALPHA_INTERPOLATE;
  11572. },
  11573. enumerable: true,
  11574. configurable: true
  11575. });
  11576. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11577. /**
  11578. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11579. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11580. */
  11581. get: function () {
  11582. return Engine._ALPHA_SCREENMODE;
  11583. },
  11584. enumerable: true,
  11585. configurable: true
  11586. });
  11587. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11588. // Delays
  11589. /** Defines that the ressource is not delayed*/
  11590. get: function () {
  11591. return Engine._DELAYLOADSTATE_NONE;
  11592. },
  11593. enumerable: true,
  11594. configurable: true
  11595. });
  11596. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11597. /** Defines that the ressource was successfully delay loaded */
  11598. get: function () {
  11599. return Engine._DELAYLOADSTATE_LOADED;
  11600. },
  11601. enumerable: true,
  11602. configurable: true
  11603. });
  11604. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11605. /** Defines that the ressource is currently delay loading */
  11606. get: function () {
  11607. return Engine._DELAYLOADSTATE_LOADING;
  11608. },
  11609. enumerable: true,
  11610. configurable: true
  11611. });
  11612. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11613. /** Defines that the ressource is delayed and has not started loading */
  11614. get: function () {
  11615. return Engine._DELAYLOADSTATE_NOTLOADED;
  11616. },
  11617. enumerable: true,
  11618. configurable: true
  11619. });
  11620. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11621. /** ALPHA */
  11622. get: function () {
  11623. return Engine._TEXTUREFORMAT_ALPHA;
  11624. },
  11625. enumerable: true,
  11626. configurable: true
  11627. });
  11628. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11629. /** LUMINANCE */
  11630. get: function () {
  11631. return Engine._TEXTUREFORMAT_LUMINANCE;
  11632. },
  11633. enumerable: true,
  11634. configurable: true
  11635. });
  11636. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11637. /**
  11638. * R32F
  11639. */
  11640. get: function () {
  11641. return Engine._TEXTUREFORMAT_R32F;
  11642. },
  11643. enumerable: true,
  11644. configurable: true
  11645. });
  11646. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11647. /**
  11648. * RG32F
  11649. */
  11650. get: function () {
  11651. return Engine._TEXTUREFORMAT_RG32F;
  11652. },
  11653. enumerable: true,
  11654. configurable: true
  11655. });
  11656. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11657. /**
  11658. * RGB32F
  11659. */
  11660. get: function () {
  11661. return Engine._TEXTUREFORMAT_RGB32F;
  11662. },
  11663. enumerable: true,
  11664. configurable: true
  11665. });
  11666. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11667. /**
  11668. * RGBA32F
  11669. */
  11670. get: function () {
  11671. return Engine._TEXTUREFORMAT_RGBA32F;
  11672. },
  11673. enumerable: true,
  11674. configurable: true
  11675. });
  11676. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11677. /** LUMINANCE_ALPHA */
  11678. get: function () {
  11679. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11685. /** RGB */
  11686. get: function () {
  11687. return Engine._TEXTUREFORMAT_RGB;
  11688. },
  11689. enumerable: true,
  11690. configurable: true
  11691. });
  11692. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11693. /** RGBA */
  11694. get: function () {
  11695. return Engine._TEXTUREFORMAT_RGBA;
  11696. },
  11697. enumerable: true,
  11698. configurable: true
  11699. });
  11700. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11701. /** UNSIGNED_INT */
  11702. get: function () {
  11703. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11704. },
  11705. enumerable: true,
  11706. configurable: true
  11707. });
  11708. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11709. /** FLOAT */
  11710. get: function () {
  11711. return Engine._TEXTURETYPE_FLOAT;
  11712. },
  11713. enumerable: true,
  11714. configurable: true
  11715. });
  11716. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11717. /** HALF_FLOAT */
  11718. get: function () {
  11719. return Engine._TEXTURETYPE_HALF_FLOAT;
  11720. },
  11721. enumerable: true,
  11722. configurable: true
  11723. });
  11724. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11725. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11726. get: function () {
  11727. return Engine._SCALEMODE_FLOOR;
  11728. },
  11729. enumerable: true,
  11730. configurable: true
  11731. });
  11732. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11733. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11734. get: function () {
  11735. return Engine._SCALEMODE_NEAREST;
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11741. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11742. get: function () {
  11743. return Engine._SCALEMODE_CEILING;
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. Object.defineProperty(Engine, "Version", {
  11749. /**
  11750. * Returns the current version of the framework
  11751. */
  11752. get: function () {
  11753. return "3.2.0-beta.4";
  11754. },
  11755. enumerable: true,
  11756. configurable: true
  11757. });
  11758. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11759. /**
  11760. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11761. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11762. */
  11763. get: function () {
  11764. return this._vrExclusivePointerMode;
  11765. },
  11766. enumerable: true,
  11767. configurable: true
  11768. });
  11769. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11770. /**
  11771. * Gets a boolean indicating that the engine supports uniform buffers
  11772. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11773. */
  11774. get: function () {
  11775. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11776. },
  11777. enumerable: true,
  11778. configurable: true
  11779. });
  11780. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11781. /**
  11782. * Gets a boolean indicating that only power of 2 textures are supported
  11783. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11784. */
  11785. get: function () {
  11786. return this._webGLVersion < 2 || this.forcePOTTextures;
  11787. },
  11788. enumerable: true,
  11789. configurable: true
  11790. });
  11791. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11792. /**
  11793. * Gets the performance monitor attached to this engine
  11794. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11795. */
  11796. get: function () {
  11797. return this._performanceMonitor;
  11798. },
  11799. enumerable: true,
  11800. configurable: true
  11801. });
  11802. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11803. /**
  11804. * Gets the list of texture formats supported
  11805. */
  11806. get: function () {
  11807. return this._texturesSupported;
  11808. },
  11809. enumerable: true,
  11810. configurable: true
  11811. });
  11812. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11813. /**
  11814. * Gets the list of texture formats in use
  11815. */
  11816. get: function () {
  11817. return this._textureFormatInUse;
  11818. },
  11819. enumerable: true,
  11820. configurable: true
  11821. });
  11822. Object.defineProperty(Engine.prototype, "currentViewport", {
  11823. /**
  11824. * Gets the current viewport
  11825. */
  11826. get: function () {
  11827. return this._cachedViewport;
  11828. },
  11829. enumerable: true,
  11830. configurable: true
  11831. });
  11832. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11833. /**
  11834. * Gets the default empty texture
  11835. */
  11836. get: function () {
  11837. if (!this._emptyTexture) {
  11838. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11839. }
  11840. return this._emptyTexture;
  11841. },
  11842. enumerable: true,
  11843. configurable: true
  11844. });
  11845. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11846. /**
  11847. * Gets the default empty 3D texture
  11848. */
  11849. get: function () {
  11850. if (!this._emptyTexture3D) {
  11851. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11852. }
  11853. return this._emptyTexture3D;
  11854. },
  11855. enumerable: true,
  11856. configurable: true
  11857. });
  11858. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11859. /**
  11860. * Gets the default empty cube texture
  11861. */
  11862. get: function () {
  11863. if (!this._emptyCubeTexture) {
  11864. var faceData = new Uint8Array(4);
  11865. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11866. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11867. }
  11868. return this._emptyCubeTexture;
  11869. },
  11870. enumerable: true,
  11871. configurable: true
  11872. });
  11873. Engine.prototype._rebuildInternalTextures = function () {
  11874. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11875. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11876. var internalTexture = currentState_1[_i];
  11877. internalTexture._rebuild();
  11878. }
  11879. };
  11880. Engine.prototype._rebuildEffects = function () {
  11881. for (var key in this._compiledEffects) {
  11882. var effect = this._compiledEffects[key];
  11883. effect._prepareEffect();
  11884. }
  11885. BABYLON.Effect.ResetCache();
  11886. };
  11887. Engine.prototype._rebuildBuffers = function () {
  11888. // Index / Vertex
  11889. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11890. var scene = _a[_i];
  11891. scene.resetCachedMaterial();
  11892. scene._rebuildGeometries();
  11893. scene._rebuildTextures();
  11894. }
  11895. // Uniforms
  11896. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11897. var uniformBuffer = _c[_b];
  11898. uniformBuffer._rebuild();
  11899. }
  11900. };
  11901. Engine.prototype._initGLContext = function () {
  11902. // Caps
  11903. this._caps = new EngineCapabilities();
  11904. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11905. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11906. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11907. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11908. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11909. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11910. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11911. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11912. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11913. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11914. // Infos
  11915. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11916. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11917. if (rendererInfo != null) {
  11918. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11919. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11920. }
  11921. if (!this._glVendor) {
  11922. this._glVendor = "Unknown vendor";
  11923. }
  11924. if (!this._glRenderer) {
  11925. this._glRenderer = "Unknown renderer";
  11926. }
  11927. // Constants
  11928. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11929. if (this._gl.RGBA16F !== 0x881A) {
  11930. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11931. }
  11932. if (this._gl.RGBA32F !== 0x8814) {
  11933. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11934. }
  11935. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11936. this._gl.DEPTH24_STENCIL8 = 35056;
  11937. }
  11938. // Extensions
  11939. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11940. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11941. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11942. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11943. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11944. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11945. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11946. 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');
  11947. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11948. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11949. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11950. this._caps.highPrecisionShaderSupported = true;
  11951. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11952. if (this._caps.timerQuery) {
  11953. if (this._webGLVersion === 1) {
  11954. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11955. }
  11956. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11957. }
  11958. // Checks if some of the format renders first to allow the use of webgl inspector.
  11959. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11960. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11961. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11962. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11963. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11964. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11965. if (this._webGLVersion > 1) {
  11966. this._gl.HALF_FLOAT_OES = 0x140B;
  11967. }
  11968. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11969. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11970. // Draw buffers
  11971. if (this._webGLVersion > 1) {
  11972. this._caps.drawBuffersExtension = true;
  11973. }
  11974. else {
  11975. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11976. if (drawBuffersExtension !== null) {
  11977. this._caps.drawBuffersExtension = true;
  11978. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11979. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11980. for (var i = 0; i < 16; i++) {
  11981. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11982. }
  11983. }
  11984. else {
  11985. this._caps.drawBuffersExtension = false;
  11986. }
  11987. }
  11988. // Depth Texture
  11989. if (this._webGLVersion > 1) {
  11990. this._caps.depthTextureExtension = true;
  11991. }
  11992. else {
  11993. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11994. if (depthTextureExtension != null) {
  11995. this._caps.depthTextureExtension = true;
  11996. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11997. }
  11998. }
  11999. // Vertex array object
  12000. if (this._webGLVersion > 1) {
  12001. this._caps.vertexArrayObject = true;
  12002. }
  12003. else {
  12004. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12005. if (vertexArrayObjectExtension != null) {
  12006. this._caps.vertexArrayObject = true;
  12007. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12008. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12009. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12010. }
  12011. else {
  12012. this._caps.vertexArrayObject = false;
  12013. }
  12014. }
  12015. // Instances count
  12016. if (this._webGLVersion > 1) {
  12017. this._caps.instancedArrays = true;
  12018. }
  12019. else {
  12020. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12021. if (instanceExtension != null) {
  12022. this._caps.instancedArrays = true;
  12023. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12024. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12025. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12026. }
  12027. else {
  12028. this._caps.instancedArrays = false;
  12029. }
  12030. }
  12031. // Intelligently add supported compressed formats in order to check for.
  12032. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12033. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12034. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12035. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12036. if (this._caps.astc)
  12037. this.texturesSupported.push('-astc.ktx');
  12038. if (this._caps.s3tc)
  12039. this.texturesSupported.push('-dxt.ktx');
  12040. if (this._caps.pvrtc)
  12041. this.texturesSupported.push('-pvrtc.ktx');
  12042. if (this._caps.etc2)
  12043. this.texturesSupported.push('-etc2.ktx');
  12044. if (this._caps.etc1)
  12045. this.texturesSupported.push('-etc1.ktx');
  12046. if (this._gl.getShaderPrecisionFormat) {
  12047. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12048. if (highp) {
  12049. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12050. }
  12051. }
  12052. // Depth buffer
  12053. this.setDepthBuffer(true);
  12054. this.setDepthFunctionToLessOrEqual();
  12055. this.setDepthWrite(true);
  12056. // Texture maps
  12057. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12058. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12059. this._nextFreeTextureSlots.push(slot);
  12060. }
  12061. };
  12062. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12063. /**
  12064. * Gets version of the current webGL context
  12065. */
  12066. get: function () {
  12067. return this._webGLVersion;
  12068. },
  12069. enumerable: true,
  12070. configurable: true
  12071. });
  12072. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12073. /**
  12074. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12075. */
  12076. get: function () {
  12077. return this._isStencilEnable;
  12078. },
  12079. enumerable: true,
  12080. configurable: true
  12081. });
  12082. Engine.prototype._prepareWorkingCanvas = function () {
  12083. if (this._workingCanvas) {
  12084. return;
  12085. }
  12086. this._workingCanvas = document.createElement("canvas");
  12087. var context = this._workingCanvas.getContext("2d");
  12088. if (context) {
  12089. this._workingContext = context;
  12090. }
  12091. };
  12092. /**
  12093. * Reset the texture cache to empty state
  12094. */
  12095. Engine.prototype.resetTextureCache = function () {
  12096. for (var key in this._boundTexturesCache) {
  12097. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12098. continue;
  12099. }
  12100. var boundTexture = this._boundTexturesCache[key];
  12101. if (boundTexture) {
  12102. this._removeDesignatedSlot(boundTexture);
  12103. }
  12104. this._boundTexturesCache[key] = null;
  12105. }
  12106. if (!this.disableTextureBindingOptimization) {
  12107. this._nextFreeTextureSlots = [];
  12108. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12109. this._nextFreeTextureSlots.push(slot);
  12110. }
  12111. }
  12112. this._currentTextureChannel = -1;
  12113. };
  12114. /**
  12115. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12116. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12117. * @returns true if engine is in deterministic lock step mode
  12118. */
  12119. Engine.prototype.isDeterministicLockStep = function () {
  12120. return this._deterministicLockstep;
  12121. };
  12122. /**
  12123. * Gets the max steps when engine is running in deterministic lock step
  12124. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12125. * @returns the max steps
  12126. */
  12127. Engine.prototype.getLockstepMaxSteps = function () {
  12128. return this._lockstepMaxSteps;
  12129. };
  12130. /**
  12131. * Gets an object containing information about the current webGL context
  12132. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12133. */
  12134. Engine.prototype.getGlInfo = function () {
  12135. return {
  12136. vendor: this._glVendor,
  12137. renderer: this._glRenderer,
  12138. version: this._glVersion
  12139. };
  12140. };
  12141. /**
  12142. * Gets current aspect ratio
  12143. * @param camera defines the camera to use to get the aspect ratio
  12144. * @param useScreen defines if screen size must be used (or the current render target if any)
  12145. * @returns a number defining the aspect ratio
  12146. */
  12147. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12148. if (useScreen === void 0) { useScreen = false; }
  12149. var viewport = camera.viewport;
  12150. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12151. };
  12152. /**
  12153. * Gets the current render width
  12154. * @param useScreen defines if screen size must be used (or the current render target if any)
  12155. * @returns a number defining the current render width
  12156. */
  12157. Engine.prototype.getRenderWidth = function (useScreen) {
  12158. if (useScreen === void 0) { useScreen = false; }
  12159. if (!useScreen && this._currentRenderTarget) {
  12160. return this._currentRenderTarget.width;
  12161. }
  12162. return this._gl.drawingBufferWidth;
  12163. };
  12164. /**
  12165. * Gets the current render height
  12166. * @param useScreen defines if screen size must be used (or the current render target if any)
  12167. * @returns a number defining the current render height
  12168. */
  12169. Engine.prototype.getRenderHeight = function (useScreen) {
  12170. if (useScreen === void 0) { useScreen = false; }
  12171. if (!useScreen && this._currentRenderTarget) {
  12172. return this._currentRenderTarget.height;
  12173. }
  12174. return this._gl.drawingBufferHeight;
  12175. };
  12176. /**
  12177. * Gets the HTML canvas attached with the current webGL context
  12178. * @returns a HTML canvas
  12179. */
  12180. Engine.prototype.getRenderingCanvas = function () {
  12181. return this._renderingCanvas;
  12182. };
  12183. /**
  12184. * Gets the client rect of the HTML canvas attached with the current webGL context
  12185. * @returns a client rectanglee
  12186. */
  12187. Engine.prototype.getRenderingCanvasClientRect = function () {
  12188. if (!this._renderingCanvas) {
  12189. return null;
  12190. }
  12191. return this._renderingCanvas.getBoundingClientRect();
  12192. };
  12193. /**
  12194. * Defines the hardware scaling level.
  12195. * By default the hardware scaling level is computed from the window device ratio.
  12196. * 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.
  12197. * @param level defines the level to use
  12198. */
  12199. Engine.prototype.setHardwareScalingLevel = function (level) {
  12200. this._hardwareScalingLevel = level;
  12201. this.resize();
  12202. };
  12203. /**
  12204. * Gets the current hardware scaling level.
  12205. * By default the hardware scaling level is computed from the window device ratio.
  12206. * 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.
  12207. * @returns a number indicating the current hardware scaling level
  12208. */
  12209. Engine.prototype.getHardwareScalingLevel = function () {
  12210. return this._hardwareScalingLevel;
  12211. };
  12212. /**
  12213. * Gets the list of loaded textures
  12214. * @returns an array containing all loaded textures
  12215. */
  12216. Engine.prototype.getLoadedTexturesCache = function () {
  12217. return this._internalTexturesCache;
  12218. };
  12219. /**
  12220. * Gets the object containing all engine capabilities
  12221. * @returns the EngineCapabilities object
  12222. */
  12223. Engine.prototype.getCaps = function () {
  12224. return this._caps;
  12225. };
  12226. Object.defineProperty(Engine.prototype, "drawCalls", {
  12227. /** @ignore */
  12228. get: function () {
  12229. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12230. return 0;
  12231. },
  12232. enumerable: true,
  12233. configurable: true
  12234. });
  12235. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12236. /** @ignore */
  12237. get: function () {
  12238. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12239. return null;
  12240. },
  12241. enumerable: true,
  12242. configurable: true
  12243. });
  12244. /**
  12245. * Gets the current depth function
  12246. * @returns a number defining the depth function
  12247. */
  12248. Engine.prototype.getDepthFunction = function () {
  12249. return this._depthCullingState.depthFunc;
  12250. };
  12251. /**
  12252. * Sets the current depth function
  12253. * @param depthFunc defines the function to use
  12254. */
  12255. Engine.prototype.setDepthFunction = function (depthFunc) {
  12256. this._depthCullingState.depthFunc = depthFunc;
  12257. };
  12258. /**
  12259. * Sets the current depth function to GREATER
  12260. */
  12261. Engine.prototype.setDepthFunctionToGreater = function () {
  12262. this._depthCullingState.depthFunc = this._gl.GREATER;
  12263. };
  12264. /**
  12265. * Sets the current depth function to GEQUAL
  12266. */
  12267. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12268. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12269. };
  12270. /**
  12271. * Sets the current depth function to LESS
  12272. */
  12273. Engine.prototype.setDepthFunctionToLess = function () {
  12274. this._depthCullingState.depthFunc = this._gl.LESS;
  12275. };
  12276. /**
  12277. * Sets the current depth function to LEQUAL
  12278. */
  12279. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12280. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12281. };
  12282. /**
  12283. * Gets a boolean indicating if stencil buffer is enabled
  12284. * @returns the current stencil buffer state
  12285. */
  12286. Engine.prototype.getStencilBuffer = function () {
  12287. return this._stencilState.stencilTest;
  12288. };
  12289. /**
  12290. * Enable or disable the stencil buffer
  12291. * @param enable defines if the stencil buffer must be enabled or disabled
  12292. */
  12293. Engine.prototype.setStencilBuffer = function (enable) {
  12294. this._stencilState.stencilTest = enable;
  12295. };
  12296. /**
  12297. * Gets the current stencil mask
  12298. * @returns a number defining the new stencil mask to use
  12299. */
  12300. Engine.prototype.getStencilMask = function () {
  12301. return this._stencilState.stencilMask;
  12302. };
  12303. /**
  12304. * Sets the current stencil mask
  12305. * @param mask defines the new stencil mask to use
  12306. */
  12307. Engine.prototype.setStencilMask = function (mask) {
  12308. this._stencilState.stencilMask = mask;
  12309. };
  12310. /**
  12311. * Gets the current stencil function
  12312. * @returns a number defining the stencil function to use
  12313. */
  12314. Engine.prototype.getStencilFunction = function () {
  12315. return this._stencilState.stencilFunc;
  12316. };
  12317. /**
  12318. * Gets the current stencil reference value
  12319. * @returns a number defining the stencil reference value to use
  12320. */
  12321. Engine.prototype.getStencilFunctionReference = function () {
  12322. return this._stencilState.stencilFuncRef;
  12323. };
  12324. /**
  12325. * Gets the current stencil mask
  12326. * @returns a number defining the stencil mask to use
  12327. */
  12328. Engine.prototype.getStencilFunctionMask = function () {
  12329. return this._stencilState.stencilFuncMask;
  12330. };
  12331. /**
  12332. * Sets the current stencil function
  12333. * @param stencilFunc defines the new stencil function to use
  12334. */
  12335. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12336. this._stencilState.stencilFunc = stencilFunc;
  12337. };
  12338. /**
  12339. * Sets the current stencil reference
  12340. * @param reference defines the new stencil reference to use
  12341. */
  12342. Engine.prototype.setStencilFunctionReference = function (reference) {
  12343. this._stencilState.stencilFuncRef = reference;
  12344. };
  12345. /**
  12346. * Sets the current stencil mask
  12347. * @param mask defines the new stencil mask to use
  12348. */
  12349. Engine.prototype.setStencilFunctionMask = function (mask) {
  12350. this._stencilState.stencilFuncMask = mask;
  12351. };
  12352. /**
  12353. * Gets the current stencil operation when stencil fails
  12354. * @returns a number defining stencil operation to use when stencil fails
  12355. */
  12356. Engine.prototype.getStencilOperationFail = function () {
  12357. return this._stencilState.stencilOpStencilFail;
  12358. };
  12359. /**
  12360. * Gets the current stencil operation when depth fails
  12361. * @returns a number defining stencil operation to use when depth fails
  12362. */
  12363. Engine.prototype.getStencilOperationDepthFail = function () {
  12364. return this._stencilState.stencilOpDepthFail;
  12365. };
  12366. /**
  12367. * Gets the current stencil operation when stencil passes
  12368. * @returns a number defining stencil operation to use when stencil passes
  12369. */
  12370. Engine.prototype.getStencilOperationPass = function () {
  12371. return this._stencilState.stencilOpStencilDepthPass;
  12372. };
  12373. /**
  12374. * Sets the stencil operation to use when stencil fails
  12375. * @param operation defines the stencil operation to use when stencil fails
  12376. */
  12377. Engine.prototype.setStencilOperationFail = function (operation) {
  12378. this._stencilState.stencilOpStencilFail = operation;
  12379. };
  12380. /**
  12381. * Sets the stencil operation to use when depth fails
  12382. * @param operation defines the stencil operation to use when depth fails
  12383. */
  12384. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12385. this._stencilState.stencilOpDepthFail = operation;
  12386. };
  12387. /**
  12388. * Sets the stencil operation to use when stencil passes
  12389. * @param operation defines the stencil operation to use when stencil passes
  12390. */
  12391. Engine.prototype.setStencilOperationPass = function (operation) {
  12392. this._stencilState.stencilOpStencilDepthPass = operation;
  12393. };
  12394. /**
  12395. * Sets a boolean indicating if the dithering state is enabled or disabled
  12396. * @param value defines the dithering state
  12397. */
  12398. Engine.prototype.setDitheringState = function (value) {
  12399. if (value) {
  12400. this._gl.enable(this._gl.DITHER);
  12401. }
  12402. else {
  12403. this._gl.disable(this._gl.DITHER);
  12404. }
  12405. };
  12406. /**
  12407. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12408. * @param value defines the rasterizer state
  12409. */
  12410. Engine.prototype.setRasterizerState = function (value) {
  12411. if (value) {
  12412. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12413. }
  12414. else {
  12415. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12416. }
  12417. };
  12418. /**
  12419. * stop executing a render loop function and remove it from the execution array
  12420. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12421. */
  12422. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12423. if (!renderFunction) {
  12424. this._activeRenderLoops = [];
  12425. return;
  12426. }
  12427. var index = this._activeRenderLoops.indexOf(renderFunction);
  12428. if (index >= 0) {
  12429. this._activeRenderLoops.splice(index, 1);
  12430. }
  12431. };
  12432. /** @ignore */
  12433. Engine.prototype._renderLoop = function () {
  12434. if (!this._contextWasLost) {
  12435. var shouldRender = true;
  12436. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12437. shouldRender = false;
  12438. }
  12439. if (shouldRender) {
  12440. // Start new frame
  12441. this.beginFrame();
  12442. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12443. var renderFunction = this._activeRenderLoops[index];
  12444. renderFunction();
  12445. }
  12446. // Present
  12447. this.endFrame();
  12448. }
  12449. }
  12450. if (this._activeRenderLoops.length > 0) {
  12451. // Register new frame
  12452. var requester = null;
  12453. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12454. requester = this._vrDisplay;
  12455. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12456. }
  12457. else {
  12458. this._renderingQueueLaunched = false;
  12459. }
  12460. };
  12461. /**
  12462. * Register and execute a render loop. The engine can have more than one render function
  12463. * @param renderFunction defines the function to continuously execute
  12464. */
  12465. Engine.prototype.runRenderLoop = function (renderFunction) {
  12466. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12467. return;
  12468. }
  12469. this._activeRenderLoops.push(renderFunction);
  12470. if (!this._renderingQueueLaunched) {
  12471. this._renderingQueueLaunched = true;
  12472. this._bindedRenderFunction = this._renderLoop.bind(this);
  12473. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12474. }
  12475. };
  12476. /**
  12477. * Toggle full screen mode
  12478. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12479. * @param options defines an option object to be sent to the requestFullscreen function
  12480. */
  12481. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12482. if (this.isFullscreen) {
  12483. BABYLON.Tools.ExitFullscreen();
  12484. }
  12485. else {
  12486. this._pointerLockRequested = requestPointerLock;
  12487. if (this._renderingCanvas) {
  12488. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12489. }
  12490. }
  12491. };
  12492. /**
  12493. * Clear the current render buffer or the current render target (if any is set up)
  12494. * @param color defines the color to use
  12495. * @param backBuffer defines if the back buffer must be cleared
  12496. * @param depth defines if the depth buffer must be cleared
  12497. * @param stencil defines if the stencil buffer must be cleared
  12498. */
  12499. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12500. if (stencil === void 0) { stencil = false; }
  12501. this.applyStates();
  12502. var mode = 0;
  12503. if (backBuffer && color) {
  12504. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12505. mode |= this._gl.COLOR_BUFFER_BIT;
  12506. }
  12507. if (depth) {
  12508. this._gl.clearDepth(1.0);
  12509. mode |= this._gl.DEPTH_BUFFER_BIT;
  12510. }
  12511. if (stencil) {
  12512. this._gl.clearStencil(0);
  12513. mode |= this._gl.STENCIL_BUFFER_BIT;
  12514. }
  12515. this._gl.clear(mode);
  12516. };
  12517. /**
  12518. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12519. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12520. * @param y defines the y-coordinate of the corner of the clear rectangle
  12521. * @param width defines the width of the clear rectangle
  12522. * @param height defines the height of the clear rectangle
  12523. * @param clearColor defines the clear color
  12524. */
  12525. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12526. var gl = this._gl;
  12527. // Save state
  12528. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12529. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12530. // Change state
  12531. gl.enable(gl.SCISSOR_TEST);
  12532. gl.scissor(x, y, width, height);
  12533. // Clear
  12534. this.clear(clearColor, true, true, true);
  12535. // Restore state
  12536. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12537. if (curScissor === true) {
  12538. gl.enable(gl.SCISSOR_TEST);
  12539. }
  12540. else {
  12541. gl.disable(gl.SCISSOR_TEST);
  12542. }
  12543. };
  12544. /**
  12545. * Set the WebGL's viewport
  12546. * @param viewport defines the viewport element to be used
  12547. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12548. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12549. */
  12550. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12551. var width = requiredWidth || this.getRenderWidth();
  12552. var height = requiredHeight || this.getRenderHeight();
  12553. var x = viewport.x || 0;
  12554. var y = viewport.y || 0;
  12555. this._cachedViewport = viewport;
  12556. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12557. };
  12558. /**
  12559. * Directly set the WebGL Viewport
  12560. * @param x defines the x coordinate of the viewport (in screen space)
  12561. * @param y defines the y coordinate of the viewport (in screen space)
  12562. * @param width defines the width of the viewport (in screen space)
  12563. * @param height defines the height of the viewport (in screen space)
  12564. * @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
  12565. */
  12566. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12567. var currentViewport = this._cachedViewport;
  12568. this._cachedViewport = null;
  12569. this._gl.viewport(x, y, width, height);
  12570. return currentViewport;
  12571. };
  12572. /**
  12573. * Begin a new frame
  12574. */
  12575. Engine.prototype.beginFrame = function () {
  12576. this.onBeginFrameObservable.notifyObservers(this);
  12577. this._measureFps();
  12578. };
  12579. /**
  12580. * Enf the current frame
  12581. */
  12582. Engine.prototype.endFrame = function () {
  12583. // Force a flush in case we are using a bad OS.
  12584. if (this._badOS) {
  12585. this.flushFramebuffer();
  12586. }
  12587. // Submit frame to the vr device, if enabled
  12588. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12589. // TODO: We should only submit the frame if we read frameData successfully.
  12590. this._vrDisplay.submitFrame();
  12591. }
  12592. this.onEndFrameObservable.notifyObservers(this);
  12593. };
  12594. /**
  12595. * Resize the view according to the canvas' size
  12596. */
  12597. Engine.prototype.resize = function () {
  12598. // We're not resizing the size of the canvas while in VR mode & presenting
  12599. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12600. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12601. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12602. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12603. }
  12604. };
  12605. /**
  12606. * Force a specific size of the canvas
  12607. * @param width defines the new canvas' width
  12608. * @param height defines the new canvas' height
  12609. */
  12610. Engine.prototype.setSize = function (width, height) {
  12611. if (!this._renderingCanvas) {
  12612. return;
  12613. }
  12614. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12615. return;
  12616. }
  12617. this._renderingCanvas.width = width;
  12618. this._renderingCanvas.height = height;
  12619. for (var index = 0; index < this.scenes.length; index++) {
  12620. var scene = this.scenes[index];
  12621. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12622. var cam = scene.cameras[camIndex];
  12623. cam._currentRenderId = 0;
  12624. }
  12625. }
  12626. if (this.onResizeObservable.hasObservers) {
  12627. this.onResizeObservable.notifyObservers(this);
  12628. }
  12629. };
  12630. // WebVR functions
  12631. /**
  12632. * Gets a boolean indicating if a webVR device was detected
  12633. * @returns true if a webVR device was detected
  12634. */
  12635. Engine.prototype.isVRDevicePresent = function () {
  12636. return !!this._vrDisplay;
  12637. };
  12638. /**
  12639. * Gets the current webVR device
  12640. * @returns the current webVR device (or null)
  12641. */
  12642. Engine.prototype.getVRDevice = function () {
  12643. return this._vrDisplay;
  12644. };
  12645. /**
  12646. * Initializes a webVR display and starts listening to display change events
  12647. * The onVRDisplayChangedObservable will be notified upon these changes
  12648. * @returns The onVRDisplayChangedObservable
  12649. */
  12650. Engine.prototype.initWebVR = function () {
  12651. this.initWebVRAsync();
  12652. return this.onVRDisplayChangedObservable;
  12653. };
  12654. /**
  12655. * Initializes a webVR display and starts listening to display change events
  12656. * The onVRDisplayChangedObservable will be notified upon these changes
  12657. * @returns A promise containing a VRDisplay and if vr is supported
  12658. */
  12659. Engine.prototype.initWebVRAsync = function () {
  12660. var _this = this;
  12661. var notifyObservers = function () {
  12662. var eventArgs = {
  12663. vrDisplay: _this._vrDisplay,
  12664. vrSupported: _this._vrSupported
  12665. };
  12666. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12667. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12668. };
  12669. if (!this._onVrDisplayConnect) {
  12670. this._onVrDisplayConnect = function (event) {
  12671. _this._vrDisplay = event.display;
  12672. notifyObservers();
  12673. };
  12674. this._onVrDisplayDisconnect = function () {
  12675. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12676. _this._vrDisplay = undefined;
  12677. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12678. notifyObservers();
  12679. };
  12680. this._onVrDisplayPresentChange = function () {
  12681. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12682. };
  12683. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12684. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12685. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12686. }
  12687. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12688. this._webVRInitPromise.then(notifyObservers);
  12689. return this._webVRInitPromise;
  12690. };
  12691. /**
  12692. * Call this function to switch to webVR mode
  12693. * Will do nothing if webVR is not supported or if there is no webVR device
  12694. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12695. */
  12696. Engine.prototype.enableVR = function () {
  12697. var _this = this;
  12698. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12699. var onResolved = function () {
  12700. _this.onVRRequestPresentComplete.notifyObservers(true);
  12701. _this._onVRFullScreenTriggered();
  12702. };
  12703. var onRejected = function () {
  12704. _this.onVRRequestPresentComplete.notifyObservers(false);
  12705. };
  12706. this.onVRRequestPresentStart.notifyObservers(this);
  12707. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12708. }
  12709. };
  12710. /**
  12711. * Call this function to leave webVR mode
  12712. * Will do nothing if webVR is not supported or if there is no webVR device
  12713. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12714. */
  12715. Engine.prototype.disableVR = function () {
  12716. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12717. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12718. }
  12719. };
  12720. Engine.prototype._getVRDisplaysAsync = function () {
  12721. var _this = this;
  12722. return new Promise(function (res, rej) {
  12723. if (navigator.getVRDisplays) {
  12724. navigator.getVRDisplays().then(function (devices) {
  12725. _this._vrSupported = true;
  12726. // note that devices may actually be an empty array. This is fine;
  12727. // we expect this._vrDisplay to be undefined in this case.
  12728. _this._vrDisplay = devices[0];
  12729. res({
  12730. vrDisplay: _this._vrDisplay,
  12731. vrSupported: _this._vrSupported
  12732. });
  12733. });
  12734. }
  12735. else {
  12736. _this._vrDisplay = undefined;
  12737. _this._vrSupported = false;
  12738. res({
  12739. vrDisplay: _this._vrDisplay,
  12740. vrSupported: _this._vrSupported
  12741. });
  12742. }
  12743. });
  12744. };
  12745. /**
  12746. * Binds the frame buffer to the specified texture.
  12747. * @param texture The texture to render to or null for the default canvas
  12748. * @param faceIndex The face of the texture to render to in case of cube texture
  12749. * @param requiredWidth The width of the target to render to
  12750. * @param requiredHeight The height of the target to render to
  12751. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12752. * @param depthStencilTexture The depth stencil texture to use to render
  12753. */
  12754. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12755. if (this._currentRenderTarget) {
  12756. this.unBindFramebuffer(this._currentRenderTarget);
  12757. }
  12758. this._currentRenderTarget = texture;
  12759. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12760. var gl = this._gl;
  12761. if (texture.isCube) {
  12762. if (faceIndex === undefined) {
  12763. faceIndex = 0;
  12764. }
  12765. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12766. if (depthStencilTexture) {
  12767. if (depthStencilTexture._generateStencilBuffer) {
  12768. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12769. }
  12770. else {
  12771. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12772. }
  12773. }
  12774. }
  12775. if (this._cachedViewport && !forceFullscreenViewport) {
  12776. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12777. }
  12778. else {
  12779. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12780. }
  12781. this.wipeCaches();
  12782. };
  12783. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12784. if (this._currentFramebuffer !== framebuffer) {
  12785. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12786. this._currentFramebuffer = framebuffer;
  12787. }
  12788. };
  12789. /**
  12790. * Unbind the current render target texture from the webGL context
  12791. * @param texture defines the render target texture to unbind
  12792. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12793. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12794. */
  12795. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12796. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12797. this._currentRenderTarget = null;
  12798. // If MSAA, we need to bitblt back to main texture
  12799. var gl = this._gl;
  12800. if (texture._MSAAFramebuffer) {
  12801. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12802. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12803. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12804. }
  12805. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12806. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12807. gl.generateMipmap(gl.TEXTURE_2D);
  12808. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12809. }
  12810. if (onBeforeUnbind) {
  12811. if (texture._MSAAFramebuffer) {
  12812. // Bind the correct framebuffer
  12813. this.bindUnboundFramebuffer(texture._framebuffer);
  12814. }
  12815. onBeforeUnbind();
  12816. }
  12817. this.bindUnboundFramebuffer(null);
  12818. };
  12819. /**
  12820. * Unbind a list of render target textures from the webGL context
  12821. * This is used only when drawBuffer extension or webGL2 are active
  12822. * @param textures defines the render target textures to unbind
  12823. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12824. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12825. */
  12826. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12827. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12828. this._currentRenderTarget = null;
  12829. // If MSAA, we need to bitblt back to main texture
  12830. var gl = this._gl;
  12831. if (textures[0]._MSAAFramebuffer) {
  12832. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12833. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12834. var attachments = textures[0]._attachments;
  12835. if (!attachments) {
  12836. attachments = new Array(textures.length);
  12837. textures[0]._attachments = attachments;
  12838. }
  12839. for (var i = 0; i < textures.length; i++) {
  12840. var texture = textures[i];
  12841. for (var j = 0; j < attachments.length; j++) {
  12842. attachments[j] = gl.NONE;
  12843. }
  12844. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12845. gl.readBuffer(attachments[i]);
  12846. gl.drawBuffers(attachments);
  12847. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12848. }
  12849. for (var i = 0; i < attachments.length; i++) {
  12850. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12851. }
  12852. gl.drawBuffers(attachments);
  12853. }
  12854. for (var i = 0; i < textures.length; i++) {
  12855. var texture = textures[i];
  12856. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12857. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12858. gl.generateMipmap(gl.TEXTURE_2D);
  12859. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12860. }
  12861. }
  12862. if (onBeforeUnbind) {
  12863. if (textures[0]._MSAAFramebuffer) {
  12864. // Bind the correct framebuffer
  12865. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12866. }
  12867. onBeforeUnbind();
  12868. }
  12869. this.bindUnboundFramebuffer(null);
  12870. };
  12871. /**
  12872. * Force the mipmap generation for the given render target texture
  12873. * @param texture defines the render target texture to use
  12874. */
  12875. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12876. if (texture.generateMipMaps) {
  12877. var gl = this._gl;
  12878. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12879. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12880. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12881. }
  12882. };
  12883. /**
  12884. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12885. */
  12886. Engine.prototype.flushFramebuffer = function () {
  12887. this._gl.flush();
  12888. };
  12889. /**
  12890. * Unbind the current render target and bind the default framebuffer
  12891. */
  12892. Engine.prototype.restoreDefaultFramebuffer = function () {
  12893. if (this._currentRenderTarget) {
  12894. this.unBindFramebuffer(this._currentRenderTarget);
  12895. }
  12896. else {
  12897. this.bindUnboundFramebuffer(null);
  12898. }
  12899. if (this._cachedViewport) {
  12900. this.setViewport(this._cachedViewport);
  12901. }
  12902. this.wipeCaches();
  12903. };
  12904. // UBOs
  12905. /**
  12906. * Create an uniform buffer
  12907. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12908. * @param elements defines the content of the uniform buffer
  12909. * @returns the webGL uniform buffer
  12910. */
  12911. Engine.prototype.createUniformBuffer = function (elements) {
  12912. var ubo = this._gl.createBuffer();
  12913. if (!ubo) {
  12914. throw new Error("Unable to create uniform buffer");
  12915. }
  12916. this.bindUniformBuffer(ubo);
  12917. if (elements instanceof Float32Array) {
  12918. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12919. }
  12920. else {
  12921. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12922. }
  12923. this.bindUniformBuffer(null);
  12924. ubo.references = 1;
  12925. return ubo;
  12926. };
  12927. /**
  12928. * Create a dynamic uniform buffer
  12929. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12930. * @param elements defines the content of the uniform buffer
  12931. * @returns the webGL uniform buffer
  12932. */
  12933. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12934. var ubo = this._gl.createBuffer();
  12935. if (!ubo) {
  12936. throw new Error("Unable to create dynamic uniform buffer");
  12937. }
  12938. this.bindUniformBuffer(ubo);
  12939. if (elements instanceof Float32Array) {
  12940. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12941. }
  12942. else {
  12943. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12944. }
  12945. this.bindUniformBuffer(null);
  12946. ubo.references = 1;
  12947. return ubo;
  12948. };
  12949. /**
  12950. * Update an existing uniform buffer
  12951. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12952. * @param uniformBuffer defines the target uniform buffer
  12953. * @param elements defines the content to update
  12954. * @param offset defines the offset in the uniform buffer where update should start
  12955. * @param count defines the size of the data to update
  12956. */
  12957. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12958. this.bindUniformBuffer(uniformBuffer);
  12959. if (offset === undefined) {
  12960. offset = 0;
  12961. }
  12962. if (count === undefined) {
  12963. if (elements instanceof Float32Array) {
  12964. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12965. }
  12966. else {
  12967. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12968. }
  12969. }
  12970. else {
  12971. if (elements instanceof Float32Array) {
  12972. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12973. }
  12974. else {
  12975. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12976. }
  12977. }
  12978. this.bindUniformBuffer(null);
  12979. };
  12980. // VBOs
  12981. Engine.prototype._resetVertexBufferBinding = function () {
  12982. this.bindArrayBuffer(null);
  12983. this._cachedVertexBuffers = null;
  12984. };
  12985. /**
  12986. * Creates a vertex buffer
  12987. * @param data the data for the vertex buffer
  12988. * @returns the new WebGL static buffer
  12989. */
  12990. Engine.prototype.createVertexBuffer = function (data) {
  12991. var vbo = this._gl.createBuffer();
  12992. if (!vbo) {
  12993. throw new Error("Unable to create vertex buffer");
  12994. }
  12995. this.bindArrayBuffer(vbo);
  12996. if (data instanceof Array) {
  12997. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  12998. }
  12999. else {
  13000. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13001. }
  13002. this._resetVertexBufferBinding();
  13003. vbo.references = 1;
  13004. return vbo;
  13005. };
  13006. /**
  13007. * Creates a dynamic vertex buffer
  13008. * @param data the data for the dynamic vertex buffer
  13009. * @returns the new WebGL dynamic buffer
  13010. */
  13011. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13012. var vbo = this._gl.createBuffer();
  13013. if (!vbo) {
  13014. throw new Error("Unable to create dynamic vertex buffer");
  13015. }
  13016. this.bindArrayBuffer(vbo);
  13017. if (data instanceof Array) {
  13018. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13019. }
  13020. else {
  13021. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13022. }
  13023. this._resetVertexBufferBinding();
  13024. vbo.references = 1;
  13025. return vbo;
  13026. };
  13027. /**
  13028. * Update a dynamic index buffer
  13029. * @param indexBuffer defines the target index buffer
  13030. * @param indices defines the data to update
  13031. * @param offset defines the offset in the target index buffer where update should start
  13032. */
  13033. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13034. if (offset === void 0) { offset = 0; }
  13035. // Force cache update
  13036. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13037. this.bindIndexBuffer(indexBuffer);
  13038. var arrayBuffer;
  13039. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13040. arrayBuffer = indices;
  13041. }
  13042. else {
  13043. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13044. }
  13045. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13046. this._resetIndexBufferBinding();
  13047. };
  13048. /**
  13049. * Updates a dynamic vertex buffer.
  13050. * @param vertexBuffer the vertex buffer to update
  13051. * @param data the data used to update the vertex buffer
  13052. * @param byteOffset the byte offset of the data
  13053. * @param byteLength the byte length of the data
  13054. */
  13055. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13056. this.bindArrayBuffer(vertexBuffer);
  13057. if (byteOffset === undefined) {
  13058. byteOffset = 0;
  13059. }
  13060. if (byteLength === undefined) {
  13061. if (data instanceof Array) {
  13062. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13063. }
  13064. else {
  13065. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13066. }
  13067. }
  13068. else {
  13069. if (data instanceof Array) {
  13070. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13071. }
  13072. else {
  13073. if (data instanceof ArrayBuffer) {
  13074. data = new Uint8Array(data, byteOffset, byteLength);
  13075. }
  13076. else {
  13077. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13078. }
  13079. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13080. }
  13081. }
  13082. this._resetVertexBufferBinding();
  13083. };
  13084. Engine.prototype._resetIndexBufferBinding = function () {
  13085. this.bindIndexBuffer(null);
  13086. this._cachedIndexBuffer = null;
  13087. };
  13088. /**
  13089. * Creates a new index buffer
  13090. * @param indices defines the content of the index buffer
  13091. * @param updatable defines if the index buffer must be updatable
  13092. * @returns a new webGL buffer
  13093. */
  13094. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13095. var vbo = this._gl.createBuffer();
  13096. if (!vbo) {
  13097. throw new Error("Unable to create index buffer");
  13098. }
  13099. this.bindIndexBuffer(vbo);
  13100. // Check for 32 bits indices
  13101. var arrayBuffer;
  13102. var need32Bits = false;
  13103. if (indices instanceof Uint16Array) {
  13104. arrayBuffer = indices;
  13105. }
  13106. else {
  13107. //check 32 bit support
  13108. if (this._caps.uintIndices) {
  13109. if (indices instanceof Uint32Array) {
  13110. arrayBuffer = indices;
  13111. need32Bits = true;
  13112. }
  13113. else {
  13114. //number[] or Int32Array, check if 32 bit is necessary
  13115. for (var index = 0; index < indices.length; index++) {
  13116. if (indices[index] > 65535) {
  13117. need32Bits = true;
  13118. break;
  13119. }
  13120. }
  13121. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13122. }
  13123. }
  13124. else {
  13125. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13126. arrayBuffer = new Uint16Array(indices);
  13127. }
  13128. }
  13129. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13130. this._resetIndexBufferBinding();
  13131. vbo.references = 1;
  13132. vbo.is32Bits = need32Bits;
  13133. return vbo;
  13134. };
  13135. /**
  13136. * Bind a webGL buffer to the webGL context
  13137. * @param buffer defines the buffer to bind
  13138. */
  13139. Engine.prototype.bindArrayBuffer = function (buffer) {
  13140. if (!this._vaoRecordInProgress) {
  13141. this._unbindVertexArrayObject();
  13142. }
  13143. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13144. };
  13145. /**
  13146. * Bind an uniform buffer to the current webGL context
  13147. * @param buffer defines the buffer to bind
  13148. */
  13149. Engine.prototype.bindUniformBuffer = function (buffer) {
  13150. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13151. };
  13152. /**
  13153. * Bind a buffer to the current webGL context at a given location
  13154. * @param buffer defines the buffer to bind
  13155. * @param location defines the index where to bind the buffer
  13156. */
  13157. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13158. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13159. };
  13160. /**
  13161. * Bind a specific block at a given index in a specific shader program
  13162. * @param shaderProgram defines the shader program
  13163. * @param blockName defines the block name
  13164. * @param index defines the index where to bind the block
  13165. */
  13166. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13167. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13168. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13169. };
  13170. ;
  13171. Engine.prototype.bindIndexBuffer = function (buffer) {
  13172. if (!this._vaoRecordInProgress) {
  13173. this._unbindVertexArrayObject();
  13174. }
  13175. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13176. };
  13177. Engine.prototype.bindBuffer = function (buffer, target) {
  13178. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13179. this._gl.bindBuffer(target, buffer);
  13180. this._currentBoundBuffer[target] = buffer;
  13181. }
  13182. };
  13183. /**
  13184. * update the bound buffer with the given data
  13185. * @param data defines the data to update
  13186. */
  13187. Engine.prototype.updateArrayBuffer = function (data) {
  13188. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13189. };
  13190. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13191. var pointer = this._currentBufferPointers[indx];
  13192. var changed = false;
  13193. if (!pointer.active) {
  13194. changed = true;
  13195. pointer.active = true;
  13196. pointer.index = indx;
  13197. pointer.size = size;
  13198. pointer.type = type;
  13199. pointer.normalized = normalized;
  13200. pointer.stride = stride;
  13201. pointer.offset = offset;
  13202. pointer.buffer = buffer;
  13203. }
  13204. else {
  13205. if (pointer.buffer !== buffer) {
  13206. pointer.buffer = buffer;
  13207. changed = true;
  13208. }
  13209. if (pointer.size !== size) {
  13210. pointer.size = size;
  13211. changed = true;
  13212. }
  13213. if (pointer.type !== type) {
  13214. pointer.type = type;
  13215. changed = true;
  13216. }
  13217. if (pointer.normalized !== normalized) {
  13218. pointer.normalized = normalized;
  13219. changed = true;
  13220. }
  13221. if (pointer.stride !== stride) {
  13222. pointer.stride = stride;
  13223. changed = true;
  13224. }
  13225. if (pointer.offset !== offset) {
  13226. pointer.offset = offset;
  13227. changed = true;
  13228. }
  13229. }
  13230. if (changed || this._vaoRecordInProgress) {
  13231. this.bindArrayBuffer(buffer);
  13232. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13233. }
  13234. };
  13235. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13236. if (indexBuffer == null) {
  13237. return;
  13238. }
  13239. if (this._cachedIndexBuffer !== indexBuffer) {
  13240. this._cachedIndexBuffer = indexBuffer;
  13241. this.bindIndexBuffer(indexBuffer);
  13242. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13243. }
  13244. };
  13245. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13246. var attributes = effect.getAttributesNames();
  13247. if (!this._vaoRecordInProgress) {
  13248. this._unbindVertexArrayObject();
  13249. }
  13250. this.unbindAllAttributes();
  13251. for (var index = 0; index < attributes.length; index++) {
  13252. var order = effect.getAttributeLocation(index);
  13253. if (order >= 0) {
  13254. var vertexBuffer = vertexBuffers[attributes[index]];
  13255. if (!vertexBuffer) {
  13256. continue;
  13257. }
  13258. this._gl.enableVertexAttribArray(order);
  13259. if (!this._vaoRecordInProgress) {
  13260. this._vertexAttribArraysEnabled[order] = true;
  13261. }
  13262. var buffer = vertexBuffer.getBuffer();
  13263. if (buffer) {
  13264. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13265. if (vertexBuffer.getIsInstanced()) {
  13266. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13267. if (!this._vaoRecordInProgress) {
  13268. this._currentInstanceLocations.push(order);
  13269. this._currentInstanceBuffers.push(buffer);
  13270. }
  13271. }
  13272. }
  13273. }
  13274. }
  13275. };
  13276. /**
  13277. * Records a vertex array object
  13278. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13279. * @param vertexBuffers defines the list of vertex buffers to store
  13280. * @param indexBuffer defines the index buffer to store
  13281. * @param effect defines the effect to store
  13282. * @returns the new vertex array object
  13283. */
  13284. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13285. var vao = this._gl.createVertexArray();
  13286. this._vaoRecordInProgress = true;
  13287. this._gl.bindVertexArray(vao);
  13288. this._mustWipeVertexAttributes = true;
  13289. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13290. this.bindIndexBuffer(indexBuffer);
  13291. this._vaoRecordInProgress = false;
  13292. this._gl.bindVertexArray(null);
  13293. return vao;
  13294. };
  13295. /**
  13296. * Bind a specific vertex array object
  13297. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13298. * @param vertexArrayObject defines the vertex array object to bind
  13299. * @param indexBuffer defines the index buffer to bind
  13300. */
  13301. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13302. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13303. this._cachedVertexArrayObject = vertexArrayObject;
  13304. this._gl.bindVertexArray(vertexArrayObject);
  13305. this._cachedVertexBuffers = null;
  13306. this._cachedIndexBuffer = null;
  13307. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13308. this._mustWipeVertexAttributes = true;
  13309. }
  13310. };
  13311. /**
  13312. * Bind webGl buffers directly to the webGL context
  13313. * @param vertexBuffer defines the vertex buffer to bind
  13314. * @param indexBuffer defines the index buffer to bind
  13315. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13316. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13317. * @param effect defines the effect associated with the vertex buffer
  13318. */
  13319. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13320. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13321. this._cachedVertexBuffers = vertexBuffer;
  13322. this._cachedEffectForVertexBuffers = effect;
  13323. var attributesCount = effect.getAttributesCount();
  13324. this._unbindVertexArrayObject();
  13325. this.unbindAllAttributes();
  13326. var offset = 0;
  13327. for (var index = 0; index < attributesCount; index++) {
  13328. if (index < vertexDeclaration.length) {
  13329. var order = effect.getAttributeLocation(index);
  13330. if (order >= 0) {
  13331. this._gl.enableVertexAttribArray(order);
  13332. this._vertexAttribArraysEnabled[order] = true;
  13333. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13334. }
  13335. offset += vertexDeclaration[index] * 4;
  13336. }
  13337. }
  13338. }
  13339. this._bindIndexBufferWithCache(indexBuffer);
  13340. };
  13341. Engine.prototype._unbindVertexArrayObject = function () {
  13342. if (!this._cachedVertexArrayObject) {
  13343. return;
  13344. }
  13345. this._cachedVertexArrayObject = null;
  13346. this._gl.bindVertexArray(null);
  13347. };
  13348. /**
  13349. * Bind a list of vertex buffers to the webGL context
  13350. * @param vertexBuffers defines the list of vertex buffers to bind
  13351. * @param indexBuffer defines the index buffer to bind
  13352. * @param effect defines the effect associated with the vertex buffers
  13353. */
  13354. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13355. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13356. this._cachedVertexBuffers = vertexBuffers;
  13357. this._cachedEffectForVertexBuffers = effect;
  13358. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13359. }
  13360. this._bindIndexBufferWithCache(indexBuffer);
  13361. };
  13362. /**
  13363. * Unbind all instance attributes
  13364. */
  13365. Engine.prototype.unbindInstanceAttributes = function () {
  13366. var boundBuffer;
  13367. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13368. var instancesBuffer = this._currentInstanceBuffers[i];
  13369. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13370. boundBuffer = instancesBuffer;
  13371. this.bindArrayBuffer(instancesBuffer);
  13372. }
  13373. var offsetLocation = this._currentInstanceLocations[i];
  13374. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13375. }
  13376. this._currentInstanceBuffers.length = 0;
  13377. this._currentInstanceLocations.length = 0;
  13378. };
  13379. /**
  13380. * Release and free the memory of a vertex array object
  13381. * @param vao defines the vertex array object to delete
  13382. */
  13383. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13384. this._gl.deleteVertexArray(vao);
  13385. };
  13386. /** @ignore */
  13387. Engine.prototype._releaseBuffer = function (buffer) {
  13388. buffer.references--;
  13389. if (buffer.references === 0) {
  13390. this._gl.deleteBuffer(buffer);
  13391. return true;
  13392. }
  13393. return false;
  13394. };
  13395. /**
  13396. * Creates a webGL buffer to use with instanciation
  13397. * @param capacity defines the size of the buffer
  13398. * @returns the webGL buffer
  13399. */
  13400. Engine.prototype.createInstancesBuffer = function (capacity) {
  13401. var buffer = this._gl.createBuffer();
  13402. if (!buffer) {
  13403. throw new Error("Unable to create instance buffer");
  13404. }
  13405. buffer.capacity = capacity;
  13406. this.bindArrayBuffer(buffer);
  13407. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13408. return buffer;
  13409. };
  13410. /**
  13411. * Delete a webGL buffer used with instanciation
  13412. * @param buffer defines the webGL buffer to delete
  13413. */
  13414. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13415. this._gl.deleteBuffer(buffer);
  13416. };
  13417. /**
  13418. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13419. * @param instancesBuffer defines the webGL buffer to update and bind
  13420. * @param data defines the data to store in the buffer
  13421. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13422. */
  13423. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13424. this.bindArrayBuffer(instancesBuffer);
  13425. if (data) {
  13426. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13427. }
  13428. if (offsetLocations[0].index !== undefined) {
  13429. var stride = 0;
  13430. for (var i = 0; i < offsetLocations.length; i++) {
  13431. var ai = offsetLocations[i];
  13432. stride += ai.attributeSize * 4;
  13433. }
  13434. for (var i = 0; i < offsetLocations.length; i++) {
  13435. var ai = offsetLocations[i];
  13436. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13437. this._gl.enableVertexAttribArray(ai.index);
  13438. this._vertexAttribArraysEnabled[ai.index] = true;
  13439. }
  13440. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13441. this._gl.vertexAttribDivisor(ai.index, 1);
  13442. this._currentInstanceLocations.push(ai.index);
  13443. this._currentInstanceBuffers.push(instancesBuffer);
  13444. }
  13445. }
  13446. else {
  13447. for (var index = 0; index < 4; index++) {
  13448. var offsetLocation = offsetLocations[index];
  13449. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13450. this._gl.enableVertexAttribArray(offsetLocation);
  13451. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13452. }
  13453. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13454. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13455. this._currentInstanceLocations.push(offsetLocation);
  13456. this._currentInstanceBuffers.push(instancesBuffer);
  13457. }
  13458. }
  13459. };
  13460. /**
  13461. * Apply all cached states (depth, culling, stencil and alpha)
  13462. */
  13463. Engine.prototype.applyStates = function () {
  13464. this._depthCullingState.apply(this._gl);
  13465. this._stencilState.apply(this._gl);
  13466. this._alphaState.apply(this._gl);
  13467. };
  13468. /**
  13469. * Send a draw order
  13470. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13471. * @param indexStart defines the starting index
  13472. * @param indexCount defines the number of index to draw
  13473. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13474. */
  13475. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13476. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13477. };
  13478. /**
  13479. * Draw a list of points
  13480. * @param verticesStart defines the index of first vertex to draw
  13481. * @param verticesCount defines the count of vertices to draw
  13482. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13483. */
  13484. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13485. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13486. };
  13487. /**
  13488. * Draw a list of unindexed primitives
  13489. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13490. * @param verticesStart defines the index of first vertex to draw
  13491. * @param verticesCount defines the count of vertices to draw
  13492. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13493. */
  13494. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13495. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13496. };
  13497. /**
  13498. * Draw a list of indexed primitives
  13499. * @param fillMode defines the primitive to use
  13500. * @param indexStart defines the starting index
  13501. * @param indexCount defines the number of index to draw
  13502. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13503. */
  13504. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13505. // Apply states
  13506. this.applyStates();
  13507. this._drawCalls.addCount(1, false);
  13508. // Render
  13509. var drawMode = this._drawMode(fillMode);
  13510. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13511. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13512. if (instancesCount) {
  13513. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13514. }
  13515. else {
  13516. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13517. }
  13518. };
  13519. /**
  13520. * Draw a list of unindexed primitives
  13521. * @param fillMode defines the primitive to use
  13522. * @param verticesStart defines the index of first vertex to draw
  13523. * @param verticesCount defines the count of vertices to draw
  13524. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13525. */
  13526. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13527. // Apply states
  13528. this.applyStates();
  13529. this._drawCalls.addCount(1, false);
  13530. var drawMode = this._drawMode(fillMode);
  13531. if (instancesCount) {
  13532. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13533. }
  13534. else {
  13535. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13536. }
  13537. };
  13538. Engine.prototype._drawMode = function (fillMode) {
  13539. switch (fillMode) {
  13540. // Triangle views
  13541. case BABYLON.Material.TriangleFillMode:
  13542. return this._gl.TRIANGLES;
  13543. case BABYLON.Material.PointFillMode:
  13544. return this._gl.POINTS;
  13545. case BABYLON.Material.WireFrameFillMode:
  13546. return this._gl.LINES;
  13547. // Draw modes
  13548. case BABYLON.Material.PointListDrawMode:
  13549. return this._gl.POINTS;
  13550. case BABYLON.Material.LineListDrawMode:
  13551. return this._gl.LINES;
  13552. case BABYLON.Material.LineLoopDrawMode:
  13553. return this._gl.LINE_LOOP;
  13554. case BABYLON.Material.LineStripDrawMode:
  13555. return this._gl.LINE_STRIP;
  13556. case BABYLON.Material.TriangleStripDrawMode:
  13557. return this._gl.TRIANGLE_STRIP;
  13558. case BABYLON.Material.TriangleFanDrawMode:
  13559. return this._gl.TRIANGLE_FAN;
  13560. default:
  13561. return this._gl.TRIANGLES;
  13562. }
  13563. };
  13564. // Shaders
  13565. /** @ignore */
  13566. Engine.prototype._releaseEffect = function (effect) {
  13567. if (this._compiledEffects[effect._key]) {
  13568. delete this._compiledEffects[effect._key];
  13569. this._deleteProgram(effect.getProgram());
  13570. }
  13571. };
  13572. /** @ignore */
  13573. Engine.prototype._deleteProgram = function (program) {
  13574. if (program) {
  13575. program.__SPECTOR_rebuildProgram = null;
  13576. if (program.transformFeedback) {
  13577. this.deleteTransformFeedback(program.transformFeedback);
  13578. program.transformFeedback = null;
  13579. }
  13580. this._gl.deleteProgram(program);
  13581. }
  13582. };
  13583. /**
  13584. * Create a new effect (used to store vertex/fragment shaders)
  13585. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13586. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13587. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13588. * @param samplers defines an array of string used to represent textures
  13589. * @param defines defines the string containing the defines to use to compile the shaders
  13590. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13591. * @param onCompiled defines a function to call when the effect creation is successful
  13592. * @param onError defines a function to call when the effect creation has failed
  13593. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13594. * @returns the new Effect
  13595. */
  13596. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13597. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13598. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13599. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13600. if (this._compiledEffects[name]) {
  13601. var compiledEffect = this._compiledEffects[name];
  13602. if (onCompiled && compiledEffect.isReady()) {
  13603. onCompiled(compiledEffect);
  13604. }
  13605. return compiledEffect;
  13606. }
  13607. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13608. effect._key = name;
  13609. this._compiledEffects[name] = effect;
  13610. return effect;
  13611. };
  13612. /**
  13613. * Create an effect to use with particle systems
  13614. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13615. * @param uniformsNames defines a list of attribute names
  13616. * @param samplers defines an array of string used to represent textures
  13617. * @param defines defines the string containing the defines to use to compile the shaders
  13618. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13619. * @param onCompiled defines a function to call when the effect creation is successful
  13620. * @param onError defines a function to call when the effect creation has failed
  13621. * @returns the new Effect
  13622. */
  13623. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13624. if (uniformsNames === void 0) { uniformsNames = []; }
  13625. if (samplers === void 0) { samplers = []; }
  13626. if (defines === void 0) { defines = ""; }
  13627. return this.createEffect({
  13628. vertex: "particles",
  13629. fragmentElement: fragmentName
  13630. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13631. };
  13632. /**
  13633. * Directly creates a webGL program
  13634. * @param vertexCode defines the vertex shader code to use
  13635. * @param fragmentCode defines the fragment shader code to use
  13636. * @param context defines the webGL context to use (if not set, the current one will be used)
  13637. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13638. * @returns the new webGL program
  13639. */
  13640. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13641. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13642. context = context || this._gl;
  13643. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13644. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13645. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13646. };
  13647. /**
  13648. * Creates a webGL program
  13649. * @param vertexCode defines the vertex shader code to use
  13650. * @param fragmentCode defines the fragment shader code to use
  13651. * @param defines defines the string containing the defines to use to compile the shaders
  13652. * @param context defines the webGL context to use (if not set, the current one will be used)
  13653. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13654. * @returns the new webGL program
  13655. */
  13656. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13657. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13658. context = context || this._gl;
  13659. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13660. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13661. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13662. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13663. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13664. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13665. return program;
  13666. };
  13667. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13668. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13669. var shaderProgram = context.createProgram();
  13670. if (!shaderProgram) {
  13671. throw new Error("Unable to create program");
  13672. }
  13673. context.attachShader(shaderProgram, vertexShader);
  13674. context.attachShader(shaderProgram, fragmentShader);
  13675. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13676. var transformFeedback = this.createTransformFeedback();
  13677. this.bindTransformFeedback(transformFeedback);
  13678. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13679. shaderProgram.transformFeedback = transformFeedback;
  13680. }
  13681. context.linkProgram(shaderProgram);
  13682. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13683. this.bindTransformFeedback(null);
  13684. }
  13685. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13686. if (!linked) {
  13687. context.validateProgram(shaderProgram);
  13688. var error = context.getProgramInfoLog(shaderProgram);
  13689. if (error) {
  13690. throw new Error(error);
  13691. }
  13692. }
  13693. context.deleteShader(vertexShader);
  13694. context.deleteShader(fragmentShader);
  13695. return shaderProgram;
  13696. };
  13697. /**
  13698. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13699. * @param shaderProgram defines the webGL program to use
  13700. * @param uniformsNames defines the list of uniform names
  13701. * @returns an array of webGL uniform locations
  13702. */
  13703. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13704. var results = new Array();
  13705. for (var index = 0; index < uniformsNames.length; index++) {
  13706. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13707. }
  13708. return results;
  13709. };
  13710. /**
  13711. * Gets the lsit of active attributes for a given webGL program
  13712. * @param shaderProgram defines the webGL program to use
  13713. * @param attributesNames defines the list of attribute names to get
  13714. * @returns an array of indices indicating the offset of each attribute
  13715. */
  13716. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13717. var results = [];
  13718. for (var index = 0; index < attributesNames.length; index++) {
  13719. try {
  13720. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13721. }
  13722. catch (e) {
  13723. results.push(-1);
  13724. }
  13725. }
  13726. return results;
  13727. };
  13728. /**
  13729. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13730. * @param effect defines the effect to activate
  13731. */
  13732. Engine.prototype.enableEffect = function (effect) {
  13733. if (!effect) {
  13734. return;
  13735. }
  13736. // Use program
  13737. this.bindSamplers(effect);
  13738. this._currentEffect = effect;
  13739. if (effect.onBind) {
  13740. effect.onBind(effect);
  13741. }
  13742. effect.onBindObservable.notifyObservers(effect);
  13743. };
  13744. /**
  13745. * Set the value of an uniform to an array of int32
  13746. * @param uniform defines the webGL uniform location where to store the value
  13747. * @param array defines the array of int32 to store
  13748. */
  13749. Engine.prototype.setIntArray = function (uniform, array) {
  13750. if (!uniform)
  13751. return;
  13752. this._gl.uniform1iv(uniform, array);
  13753. };
  13754. /**
  13755. * Set the value of an uniform to an array of int32 (stored as vec2)
  13756. * @param uniform defines the webGL uniform location where to store the value
  13757. * @param array defines the array of int32 to store
  13758. */
  13759. Engine.prototype.setIntArray2 = function (uniform, array) {
  13760. if (!uniform || array.length % 2 !== 0)
  13761. return;
  13762. this._gl.uniform2iv(uniform, array);
  13763. };
  13764. /**
  13765. * Set the value of an uniform to an array of int32 (stored as vec3)
  13766. * @param uniform defines the webGL uniform location where to store the value
  13767. * @param array defines the array of int32 to store
  13768. */
  13769. Engine.prototype.setIntArray3 = function (uniform, array) {
  13770. if (!uniform || array.length % 3 !== 0)
  13771. return;
  13772. this._gl.uniform3iv(uniform, array);
  13773. };
  13774. /**
  13775. * Set the value of an uniform to an array of int32 (stored as vec4)
  13776. * @param uniform defines the webGL uniform location where to store the value
  13777. * @param array defines the array of int32 to store
  13778. */
  13779. Engine.prototype.setIntArray4 = function (uniform, array) {
  13780. if (!uniform || array.length % 4 !== 0)
  13781. return;
  13782. this._gl.uniform4iv(uniform, array);
  13783. };
  13784. /**
  13785. * Set the value of an uniform to an array of float32
  13786. * @param uniform defines the webGL uniform location where to store the value
  13787. * @param array defines the array of float32 to store
  13788. */
  13789. Engine.prototype.setFloatArray = function (uniform, array) {
  13790. if (!uniform)
  13791. return;
  13792. this._gl.uniform1fv(uniform, array);
  13793. };
  13794. /**
  13795. * Set the value of an uniform to an array of float32 (stored as vec2)
  13796. * @param uniform defines the webGL uniform location where to store the value
  13797. * @param array defines the array of float32 to store
  13798. */
  13799. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13800. if (!uniform || array.length % 2 !== 0)
  13801. return;
  13802. this._gl.uniform2fv(uniform, array);
  13803. };
  13804. /**
  13805. * Set the value of an uniform to an array of float32 (stored as vec3)
  13806. * @param uniform defines the webGL uniform location where to store the value
  13807. * @param array defines the array of float32 to store
  13808. */
  13809. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13810. if (!uniform || array.length % 3 !== 0)
  13811. return;
  13812. this._gl.uniform3fv(uniform, array);
  13813. };
  13814. /**
  13815. * Set the value of an uniform to an array of float32 (stored as vec4)
  13816. * @param uniform defines the webGL uniform location where to store the value
  13817. * @param array defines the array of float32 to store
  13818. */
  13819. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13820. if (!uniform || array.length % 4 !== 0)
  13821. return;
  13822. this._gl.uniform4fv(uniform, array);
  13823. };
  13824. /**
  13825. * Set the value of an uniform to an array of number
  13826. * @param uniform defines the webGL uniform location where to store the value
  13827. * @param array defines the array of number to store
  13828. */
  13829. Engine.prototype.setArray = function (uniform, array) {
  13830. if (!uniform)
  13831. return;
  13832. this._gl.uniform1fv(uniform, array);
  13833. };
  13834. /**
  13835. * Set the value of an uniform to an array of number (stored as vec2)
  13836. * @param uniform defines the webGL uniform location where to store the value
  13837. * @param array defines the array of number to store
  13838. */
  13839. Engine.prototype.setArray2 = function (uniform, array) {
  13840. if (!uniform || array.length % 2 !== 0)
  13841. return;
  13842. this._gl.uniform2fv(uniform, array);
  13843. };
  13844. /**
  13845. * Set the value of an uniform to an array of number (stored as vec3)
  13846. * @param uniform defines the webGL uniform location where to store the value
  13847. * @param array defines the array of number to store
  13848. */
  13849. Engine.prototype.setArray3 = function (uniform, array) {
  13850. if (!uniform || array.length % 3 !== 0)
  13851. return;
  13852. this._gl.uniform3fv(uniform, array);
  13853. };
  13854. /**
  13855. * Set the value of an uniform to an array of number (stored as vec4)
  13856. * @param uniform defines the webGL uniform location where to store the value
  13857. * @param array defines the array of number to store
  13858. */
  13859. Engine.prototype.setArray4 = function (uniform, array) {
  13860. if (!uniform || array.length % 4 !== 0)
  13861. return;
  13862. this._gl.uniform4fv(uniform, array);
  13863. };
  13864. /**
  13865. * Set the value of an uniform to an array of float32 (stored as matrices)
  13866. * @param uniform defines the webGL uniform location where to store the value
  13867. * @param matrices defines the array of float32 to store
  13868. */
  13869. Engine.prototype.setMatrices = function (uniform, matrices) {
  13870. if (!uniform)
  13871. return;
  13872. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13873. };
  13874. /**
  13875. * Set the value of an uniform to a matrix
  13876. * @param uniform defines the webGL uniform location where to store the value
  13877. * @param matrix defines the matrix to store
  13878. */
  13879. Engine.prototype.setMatrix = function (uniform, matrix) {
  13880. if (!uniform)
  13881. return;
  13882. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13883. };
  13884. /**
  13885. * Set the value of an uniform to a matrix (3x3)
  13886. * @param uniform defines the webGL uniform location where to store the value
  13887. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13888. */
  13889. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13890. if (!uniform)
  13891. return;
  13892. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13893. };
  13894. /**
  13895. * Set the value of an uniform to a matrix (2x2)
  13896. * @param uniform defines the webGL uniform location where to store the value
  13897. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13898. */
  13899. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13900. if (!uniform)
  13901. return;
  13902. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13903. };
  13904. /**
  13905. * Set the value of an uniform to a number (int)
  13906. * @param uniform defines the webGL uniform location where to store the value
  13907. * @param value defines the int number to store
  13908. */
  13909. Engine.prototype.setInt = function (uniform, value) {
  13910. if (!uniform)
  13911. return;
  13912. this._gl.uniform1i(uniform, value);
  13913. };
  13914. /**
  13915. * Set the value of an uniform to a number (float)
  13916. * @param uniform defines the webGL uniform location where to store the value
  13917. * @param value defines the float number to store
  13918. */
  13919. Engine.prototype.setFloat = function (uniform, value) {
  13920. if (!uniform)
  13921. return;
  13922. this._gl.uniform1f(uniform, value);
  13923. };
  13924. /**
  13925. * Set the value of an uniform to a vec2
  13926. * @param uniform defines the webGL uniform location where to store the value
  13927. * @param x defines the 1st component of the value
  13928. * @param y defines the 2nd component of the value
  13929. */
  13930. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13931. if (!uniform)
  13932. return;
  13933. this._gl.uniform2f(uniform, x, y);
  13934. };
  13935. /**
  13936. * Set the value of an uniform to a vec3
  13937. * @param uniform defines the webGL uniform location where to store the value
  13938. * @param x defines the 1st component of the value
  13939. * @param y defines the 2nd component of the value
  13940. * @param z defines the 3rd component of the value
  13941. */
  13942. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13943. if (!uniform)
  13944. return;
  13945. this._gl.uniform3f(uniform, x, y, z);
  13946. };
  13947. /**
  13948. * Set the value of an uniform to a boolean
  13949. * @param uniform defines the webGL uniform location where to store the value
  13950. * @param bool defines the boolean to store
  13951. */
  13952. Engine.prototype.setBool = function (uniform, bool) {
  13953. if (!uniform)
  13954. return;
  13955. this._gl.uniform1i(uniform, bool);
  13956. };
  13957. /**
  13958. * Set the value of an uniform to a vec4
  13959. * @param uniform defines the webGL uniform location where to store the value
  13960. * @param x defines the 1st component of the value
  13961. * @param y defines the 2nd component of the value
  13962. * @param z defines the 3rd component of the value
  13963. * @param w defines the 4th component of the value
  13964. */
  13965. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13966. if (!uniform)
  13967. return;
  13968. this._gl.uniform4f(uniform, x, y, z, w);
  13969. };
  13970. /**
  13971. * Set the value of an uniform to a Color3
  13972. * @param uniform defines the webGL uniform location where to store the value
  13973. * @param color3 defines the color to store
  13974. */
  13975. Engine.prototype.setColor3 = function (uniform, color3) {
  13976. if (!uniform)
  13977. return;
  13978. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  13979. };
  13980. /**
  13981. * Set the value of an uniform to a Color3 and an alpha value
  13982. * @param uniform defines the webGL uniform location where to store the value
  13983. * @param color3 defines the color to store
  13984. * @param alpha defines the alpha component to store
  13985. */
  13986. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  13987. if (!uniform)
  13988. return;
  13989. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  13990. };
  13991. /**
  13992. * Sets a Color4 on a uniform variable
  13993. * @param uniform defines the uniform location
  13994. * @param color4 defines the value to be set
  13995. */
  13996. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  13997. if (!uniform)
  13998. return;
  13999. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14000. };
  14001. // States
  14002. /**
  14003. * Set various states to the webGL context
  14004. * @param culling defines backface culling state
  14005. * @param zOffset defines the value to apply to zOffset (0 by default)
  14006. * @param force defines if states must be applied even if cache is up to date
  14007. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14008. */
  14009. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14010. if (zOffset === void 0) { zOffset = 0; }
  14011. if (reverseSide === void 0) { reverseSide = false; }
  14012. // Culling
  14013. if (this._depthCullingState.cull !== culling || force) {
  14014. this._depthCullingState.cull = culling;
  14015. }
  14016. // Cull face
  14017. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14018. if (this._depthCullingState.cullFace !== cullFace || force) {
  14019. this._depthCullingState.cullFace = cullFace;
  14020. }
  14021. // Z offset
  14022. this.setZOffset(zOffset);
  14023. // Front face
  14024. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14025. if (this._depthCullingState.frontFace !== frontFace || force) {
  14026. this._depthCullingState.frontFace = frontFace;
  14027. }
  14028. };
  14029. /**
  14030. * Set the z offset to apply to current rendering
  14031. * @param value defines the offset to apply
  14032. */
  14033. Engine.prototype.setZOffset = function (value) {
  14034. this._depthCullingState.zOffset = value;
  14035. };
  14036. /**
  14037. * Gets the current value of the zOffset
  14038. * @returns the current zOffset state
  14039. */
  14040. Engine.prototype.getZOffset = function () {
  14041. return this._depthCullingState.zOffset;
  14042. };
  14043. /**
  14044. * Enable or disable depth buffering
  14045. * @param enable defines the state to set
  14046. */
  14047. Engine.prototype.setDepthBuffer = function (enable) {
  14048. this._depthCullingState.depthTest = enable;
  14049. };
  14050. /**
  14051. * Gets a boolean indicating if depth writing is enabled
  14052. * @returns the current depth writing state
  14053. */
  14054. Engine.prototype.getDepthWrite = function () {
  14055. return this._depthCullingState.depthMask;
  14056. };
  14057. /**
  14058. * Enable or disable depth writing
  14059. * @param enable defines the state to set
  14060. */
  14061. Engine.prototype.setDepthWrite = function (enable) {
  14062. this._depthCullingState.depthMask = enable;
  14063. };
  14064. /**
  14065. * Enable or disable color writing
  14066. * @param enable defines the state to set
  14067. */
  14068. Engine.prototype.setColorWrite = function (enable) {
  14069. this._gl.colorMask(enable, enable, enable, enable);
  14070. this._colorWrite = enable;
  14071. };
  14072. /**
  14073. * Gets a boolean indicating if color writing is enabled
  14074. * @returns the current color writing state
  14075. */
  14076. Engine.prototype.getColorWrite = function () {
  14077. return this._colorWrite;
  14078. };
  14079. /**
  14080. * Sets alpha constants used by some alpha blending modes
  14081. * @param r defines the red component
  14082. * @param g defines the green component
  14083. * @param b defines the blue component
  14084. * @param a defines the alpha component
  14085. */
  14086. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14087. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14088. };
  14089. /**
  14090. * Sets the current alpha mode
  14091. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14092. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14093. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14094. */
  14095. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14096. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14097. if (this._alphaMode === mode) {
  14098. return;
  14099. }
  14100. switch (mode) {
  14101. case Engine.ALPHA_DISABLE:
  14102. this._alphaState.alphaBlend = false;
  14103. break;
  14104. case Engine.ALPHA_PREMULTIPLIED:
  14105. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14106. this._alphaState.alphaBlend = true;
  14107. break;
  14108. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14109. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14110. this._alphaState.alphaBlend = true;
  14111. break;
  14112. case Engine.ALPHA_COMBINE:
  14113. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14114. this._alphaState.alphaBlend = true;
  14115. break;
  14116. case Engine.ALPHA_ONEONE:
  14117. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14118. this._alphaState.alphaBlend = true;
  14119. break;
  14120. case Engine.ALPHA_ADD:
  14121. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14122. this._alphaState.alphaBlend = true;
  14123. break;
  14124. case Engine.ALPHA_SUBTRACT:
  14125. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14126. this._alphaState.alphaBlend = true;
  14127. break;
  14128. case Engine.ALPHA_MULTIPLY:
  14129. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14130. this._alphaState.alphaBlend = true;
  14131. break;
  14132. case Engine.ALPHA_MAXIMIZED:
  14133. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14134. this._alphaState.alphaBlend = true;
  14135. break;
  14136. case Engine.ALPHA_INTERPOLATE:
  14137. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14138. this._alphaState.alphaBlend = true;
  14139. break;
  14140. case Engine.ALPHA_SCREENMODE:
  14141. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14142. this._alphaState.alphaBlend = true;
  14143. break;
  14144. }
  14145. if (!noDepthWriteChange) {
  14146. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14147. }
  14148. this._alphaMode = mode;
  14149. };
  14150. /**
  14151. * Gets the current alpha mode
  14152. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14153. * @returns the current alpha mode
  14154. */
  14155. Engine.prototype.getAlphaMode = function () {
  14156. return this._alphaMode;
  14157. };
  14158. // Textures
  14159. /**
  14160. * Force the entire cache to be cleared
  14161. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14162. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14163. */
  14164. Engine.prototype.wipeCaches = function (bruteForce) {
  14165. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14166. return;
  14167. }
  14168. this._currentEffect = null;
  14169. if (bruteForce) {
  14170. this.resetTextureCache();
  14171. this._currentProgram = null;
  14172. this._stencilState.reset();
  14173. this._depthCullingState.reset();
  14174. this.setDepthFunctionToLessOrEqual();
  14175. this._alphaState.reset();
  14176. }
  14177. this._resetVertexBufferBinding();
  14178. this._cachedIndexBuffer = null;
  14179. this._cachedEffectForVertexBuffers = null;
  14180. this._unbindVertexArrayObject();
  14181. this.bindIndexBuffer(null);
  14182. };
  14183. /**
  14184. * Set the compressed texture format to use, based on the formats you have, and the formats
  14185. * supported by the hardware / browser.
  14186. *
  14187. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14188. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14189. * to API arguments needed to compressed textures. This puts the burden on the container
  14190. * generator to house the arcane code for determining these for current & future formats.
  14191. *
  14192. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14193. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14194. *
  14195. * Note: The result of this call is not taken into account when a texture is base64.
  14196. *
  14197. * @param formatsAvailable defines the list of those format families you have created
  14198. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14199. *
  14200. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14201. * @returns The extension selected.
  14202. */
  14203. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14204. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14205. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14206. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14207. return this._textureFormatInUse = this._texturesSupported[i];
  14208. }
  14209. }
  14210. }
  14211. // actively set format to nothing, to allow this to be called more than once
  14212. // and possibly fail the 2nd time
  14213. this._textureFormatInUse = null;
  14214. return null;
  14215. };
  14216. /** @ignore */
  14217. Engine.prototype._createTexture = function () {
  14218. var texture = this._gl.createTexture();
  14219. if (!texture) {
  14220. throw new Error("Unable to create texture");
  14221. }
  14222. return texture;
  14223. };
  14224. /**
  14225. * Usually called from BABYLON.Texture.ts.
  14226. * Passed information to create a WebGLTexture
  14227. * @param urlArg defines a value which contains one of the following:
  14228. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14229. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14230. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14231. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14232. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14233. * @param scene needed for loading to the correct scene
  14234. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14235. * @param onLoad optional callback to be called upon successful completion
  14236. * @param onError optional callback to be called upon failure
  14237. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14238. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14239. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14240. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14241. */
  14242. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14243. var _this = this;
  14244. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14245. if (onLoad === void 0) { onLoad = null; }
  14246. if (onError === void 0) { onError = null; }
  14247. if (buffer === void 0) { buffer = null; }
  14248. if (fallback === void 0) { fallback = null; }
  14249. if (format === void 0) { format = null; }
  14250. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14251. var fromData = url.substr(0, 5) === "data:";
  14252. var fromBlob = url.substr(0, 5) === "blob:";
  14253. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14254. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14255. // establish the file extension, if possible
  14256. var lastDot = url.lastIndexOf('.');
  14257. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14258. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14259. var isTGA = (extension.indexOf(".tga") === 0);
  14260. // determine if a ktx file should be substituted
  14261. var isKTX = false;
  14262. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14263. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14264. isKTX = true;
  14265. }
  14266. if (scene) {
  14267. scene._addPendingData(texture);
  14268. }
  14269. texture.url = url;
  14270. texture.generateMipMaps = !noMipmap;
  14271. texture.samplingMode = samplingMode;
  14272. texture.invertY = invertY;
  14273. if (!this._doNotHandleContextLost) {
  14274. // Keep a link to the buffer only if we plan to handle context lost
  14275. texture._buffer = buffer;
  14276. }
  14277. var onLoadObserver = null;
  14278. if (onLoad && !fallback) {
  14279. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14280. }
  14281. if (!fallback)
  14282. this._internalTexturesCache.push(texture);
  14283. var onerror = function (message, exception) {
  14284. if (scene) {
  14285. scene._removePendingData(texture);
  14286. }
  14287. if (onLoadObserver) {
  14288. texture.onLoadedObservable.remove(onLoadObserver);
  14289. }
  14290. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14291. if (isKTX) {
  14292. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14293. }
  14294. else if (BABYLON.Tools.UseFallbackTexture) {
  14295. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14296. }
  14297. if (onError) {
  14298. onError(message || "Unknown error", exception);
  14299. }
  14300. };
  14301. var callback = null;
  14302. // processing for non-image formats
  14303. if (isKTX || isTGA || isDDS) {
  14304. if (isKTX) {
  14305. callback = function (data) {
  14306. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14307. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14308. ktx.uploadLevels(_this._gl, !noMipmap);
  14309. return false;
  14310. }, samplingMode);
  14311. };
  14312. }
  14313. else if (isTGA) {
  14314. callback = function (arrayBuffer) {
  14315. var data = new Uint8Array(arrayBuffer);
  14316. var header = BABYLON.TGATools.GetTGAHeader(data);
  14317. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14318. BABYLON.TGATools.UploadContent(_this._gl, data);
  14319. return false;
  14320. }, samplingMode);
  14321. };
  14322. }
  14323. else if (isDDS) {
  14324. callback = function (data) {
  14325. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14326. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14327. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14328. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14329. return false;
  14330. }, samplingMode);
  14331. };
  14332. }
  14333. if (!buffer) {
  14334. this._loadFile(url, function (data) {
  14335. if (callback) {
  14336. callback(data);
  14337. }
  14338. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14339. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14340. });
  14341. }
  14342. else {
  14343. if (callback) {
  14344. callback(buffer);
  14345. }
  14346. }
  14347. // image format processing
  14348. }
  14349. else {
  14350. var onload = function (img) {
  14351. if (fromBlob && !_this._doNotHandleContextLost) {
  14352. // We need to store the image if we need to rebuild the texture
  14353. // in case of a webgl context lost
  14354. texture._buffer = img;
  14355. }
  14356. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14357. var gl = _this._gl;
  14358. var isPot = (img.width === potWidth && img.height === potHeight);
  14359. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14360. if (isPot) {
  14361. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14362. return false;
  14363. }
  14364. // Using shaders to rescale because canvas.drawImage is lossy
  14365. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14366. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14367. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14368. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14369. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14370. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14371. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14372. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14373. _this._releaseTexture(source);
  14374. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14375. continuationCallback();
  14376. });
  14377. return true;
  14378. }, samplingMode);
  14379. };
  14380. if (!fromData || isBase64)
  14381. if (buffer instanceof HTMLImageElement) {
  14382. onload(buffer);
  14383. }
  14384. else {
  14385. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14386. }
  14387. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14388. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14389. else
  14390. onload(buffer);
  14391. }
  14392. return texture;
  14393. };
  14394. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14395. var _this = this;
  14396. var rtt = this.createRenderTargetTexture({
  14397. width: destination.width,
  14398. height: destination.height,
  14399. }, {
  14400. generateMipMaps: false,
  14401. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14402. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14403. generateDepthBuffer: false,
  14404. generateStencilBuffer: false
  14405. });
  14406. if (!this._rescalePostProcess) {
  14407. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14408. }
  14409. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14410. _this._rescalePostProcess.onApply = function (effect) {
  14411. effect._bindTexture("textureSampler", source);
  14412. };
  14413. var hostingScene = scene;
  14414. if (!hostingScene) {
  14415. hostingScene = _this.scenes[_this.scenes.length - 1];
  14416. }
  14417. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14418. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14419. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14420. _this.unBindFramebuffer(rtt);
  14421. _this._releaseTexture(rtt);
  14422. if (onComplete) {
  14423. onComplete();
  14424. }
  14425. });
  14426. };
  14427. /**
  14428. * Update a raw texture
  14429. * @param texture defines the texture to update
  14430. * @param data defines the data to store in the texture
  14431. * @param format defines the format of the data
  14432. * @param invertY defines if data must be stored with Y axis inverted
  14433. * @param compression defines the compression used (null by default)
  14434. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14435. */
  14436. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14437. if (compression === void 0) { compression = null; }
  14438. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14439. if (!texture) {
  14440. return;
  14441. }
  14442. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14443. var internalFormat = this._getInternalFormat(format);
  14444. var textureType = this._getWebGLTextureType(type);
  14445. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14446. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14447. if (!this._doNotHandleContextLost) {
  14448. texture._bufferView = data;
  14449. texture.format = format;
  14450. texture.type = type;
  14451. texture.invertY = invertY;
  14452. texture._compression = compression;
  14453. }
  14454. if (texture.width % 4 !== 0) {
  14455. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14456. }
  14457. if (compression && data) {
  14458. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14459. }
  14460. else {
  14461. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14462. }
  14463. if (texture.generateMipMaps) {
  14464. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14465. }
  14466. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14467. // this.resetTextureCache();
  14468. texture.isReady = true;
  14469. };
  14470. /**
  14471. * Creates a raw texture
  14472. * @param data defines the data to store in the texture
  14473. * @param width defines the width of the texture
  14474. * @param height defines the height of the texture
  14475. * @param format defines the format of the data
  14476. * @param generateMipMaps defines if the engine should generate the mip levels
  14477. * @param invertY defines if data must be stored with Y axis inverted
  14478. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14479. * @param compression defines the compression used (null by default)
  14480. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14481. * @returns the raw texture inside an InternalTexture
  14482. */
  14483. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14484. if (compression === void 0) { compression = null; }
  14485. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14486. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14487. texture.baseWidth = width;
  14488. texture.baseHeight = height;
  14489. texture.width = width;
  14490. texture.height = height;
  14491. texture.format = format;
  14492. texture.generateMipMaps = generateMipMaps;
  14493. texture.samplingMode = samplingMode;
  14494. texture.invertY = invertY;
  14495. texture._compression = compression;
  14496. texture.type = type;
  14497. if (!this._doNotHandleContextLost) {
  14498. texture._bufferView = data;
  14499. }
  14500. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14501. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14502. // Filters
  14503. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14504. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14505. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14506. if (generateMipMaps) {
  14507. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14508. }
  14509. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14510. this._internalTexturesCache.push(texture);
  14511. return texture;
  14512. };
  14513. /**
  14514. * Creates a dynamic texture
  14515. * @param width defines the width of the texture
  14516. * @param height defines the height of the texture
  14517. * @param generateMipMaps defines if the engine should generate the mip levels
  14518. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14519. * @returns the dynamic texture inside an InternalTexture
  14520. */
  14521. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14522. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14523. texture.baseWidth = width;
  14524. texture.baseHeight = height;
  14525. if (generateMipMaps) {
  14526. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14527. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14528. }
  14529. // this.resetTextureCache();
  14530. texture.width = width;
  14531. texture.height = height;
  14532. texture.isReady = false;
  14533. texture.generateMipMaps = generateMipMaps;
  14534. texture.samplingMode = samplingMode;
  14535. this.updateTextureSamplingMode(samplingMode, texture);
  14536. this._internalTexturesCache.push(texture);
  14537. return texture;
  14538. };
  14539. /**
  14540. * Update the sampling mode of a given texture
  14541. * @param samplingMode defines the required sampling mode
  14542. * @param texture defines the texture to update
  14543. */
  14544. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14545. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14546. if (texture.isCube) {
  14547. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14548. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14549. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14550. }
  14551. else if (texture.is3D) {
  14552. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14553. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14554. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14555. }
  14556. else {
  14557. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14558. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14559. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14560. }
  14561. texture.samplingMode = samplingMode;
  14562. };
  14563. /**
  14564. * Update the content of a dynamic texture
  14565. * @param texture defines the texture to update
  14566. * @param canvas defines the canvas containing the source
  14567. * @param invertY defines if data must be stored with Y axis inverted
  14568. * @param premulAlpha defines if alpha is stored as premultiplied
  14569. * @param format defines the format of the data
  14570. */
  14571. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14572. if (premulAlpha === void 0) { premulAlpha = false; }
  14573. if (!texture) {
  14574. return;
  14575. }
  14576. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14577. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14578. if (premulAlpha) {
  14579. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14580. }
  14581. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14582. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14583. if (texture.generateMipMaps) {
  14584. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14585. }
  14586. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14587. if (premulAlpha) {
  14588. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14589. }
  14590. texture.isReady = true;
  14591. };
  14592. /**
  14593. * Update a video texture
  14594. * @param texture defines the texture to update
  14595. * @param video defines the video element to use
  14596. * @param invertY defines if data must be stored with Y axis inverted
  14597. */
  14598. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14599. if (!texture || texture._isDisabled) {
  14600. return;
  14601. }
  14602. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14603. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14604. try {
  14605. // Testing video texture support
  14606. if (this._videoTextureSupported === undefined) {
  14607. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14608. if (this._gl.getError() !== 0) {
  14609. this._videoTextureSupported = false;
  14610. }
  14611. else {
  14612. this._videoTextureSupported = true;
  14613. }
  14614. }
  14615. // Copy video through the current working canvas if video texture is not supported
  14616. if (!this._videoTextureSupported) {
  14617. if (!texture._workingCanvas) {
  14618. texture._workingCanvas = document.createElement("canvas");
  14619. var context = texture._workingCanvas.getContext("2d");
  14620. if (!context) {
  14621. throw new Error("Unable to get 2d context");
  14622. }
  14623. texture._workingContext = context;
  14624. texture._workingCanvas.width = texture.width;
  14625. texture._workingCanvas.height = texture.height;
  14626. }
  14627. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14628. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14629. }
  14630. else {
  14631. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14632. }
  14633. if (texture.generateMipMaps) {
  14634. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14635. }
  14636. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14637. // this.resetTextureCache();
  14638. texture.isReady = true;
  14639. }
  14640. catch (ex) {
  14641. // Something unexpected
  14642. // Let's disable the texture
  14643. texture._isDisabled = true;
  14644. }
  14645. };
  14646. /**
  14647. * Updates a depth texture Comparison Mode and Function.
  14648. * If the comparison Function is equal to 0, the mode will be set to none.
  14649. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14650. * @param texture The texture to set the comparison function for
  14651. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14652. */
  14653. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14654. if (this.webGLVersion === 1) {
  14655. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14656. return;
  14657. }
  14658. var gl = this._gl;
  14659. if (texture.isCube) {
  14660. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14661. if (comparisonFunction === 0) {
  14662. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14663. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14664. }
  14665. else {
  14666. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14667. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14668. }
  14669. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14670. }
  14671. else {
  14672. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14673. if (comparisonFunction === 0) {
  14674. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14675. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14676. }
  14677. else {
  14678. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14679. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14680. }
  14681. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14682. }
  14683. texture._comparisonFunction = comparisonFunction;
  14684. };
  14685. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14686. var width = size.width || size;
  14687. var height = size.height || size;
  14688. internalTexture.baseWidth = width;
  14689. internalTexture.baseHeight = height;
  14690. internalTexture.width = width;
  14691. internalTexture.height = height;
  14692. internalTexture.isReady = true;
  14693. internalTexture.samples = 1;
  14694. internalTexture.generateMipMaps = false;
  14695. internalTexture._generateDepthBuffer = true;
  14696. internalTexture._generateStencilBuffer = generateStencil;
  14697. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14698. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14699. internalTexture._comparisonFunction = comparisonFunction;
  14700. var gl = this._gl;
  14701. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14702. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14703. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14704. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14705. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14706. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14707. if (comparisonFunction === 0) {
  14708. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14709. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14710. }
  14711. else {
  14712. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14713. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14714. }
  14715. };
  14716. /**
  14717. * Creates a depth stencil texture.
  14718. * This is only available in WebGL 2 or with the depth texture extension available.
  14719. * @param size The size of face edge in the texture.
  14720. * @param options The options defining the texture.
  14721. * @returns The texture
  14722. */
  14723. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14724. if (options.isCube) {
  14725. var width = size.width || size;
  14726. return this._createDepthStencilCubeTexture(width, options);
  14727. }
  14728. else {
  14729. return this._createDepthStencilTexture(size, options);
  14730. }
  14731. };
  14732. /**
  14733. * Creates a depth stencil texture.
  14734. * This is only available in WebGL 2 or with the depth texture extension available.
  14735. * @param size The size of face edge in the texture.
  14736. * @param options The options defining the texture.
  14737. * @returns The texture
  14738. */
  14739. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14740. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14741. if (!this._caps.depthTextureExtension) {
  14742. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14743. return internalTexture;
  14744. }
  14745. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14746. var gl = this._gl;
  14747. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14748. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14749. if (this.webGLVersion > 1) {
  14750. if (internalOptions.generateStencil) {
  14751. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14752. }
  14753. else {
  14754. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14755. }
  14756. }
  14757. else {
  14758. if (internalOptions.generateStencil) {
  14759. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14760. }
  14761. else {
  14762. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14763. }
  14764. }
  14765. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14766. return internalTexture;
  14767. };
  14768. /**
  14769. * Creates a depth stencil cube texture.
  14770. * This is only available in WebGL 2.
  14771. * @param size The size of face edge in the cube texture.
  14772. * @param options The options defining the cube texture.
  14773. * @returns The cube texture
  14774. */
  14775. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14776. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14777. internalTexture.isCube = true;
  14778. if (this.webGLVersion === 1) {
  14779. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14780. return internalTexture;
  14781. }
  14782. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14783. var gl = this._gl;
  14784. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14785. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14786. // Create the depth/stencil buffer
  14787. for (var face = 0; face < 6; face++) {
  14788. if (internalOptions.generateStencil) {
  14789. 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);
  14790. }
  14791. else {
  14792. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14793. }
  14794. }
  14795. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14796. return internalTexture;
  14797. };
  14798. /**
  14799. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14800. * @param renderTarget The render target to set the frame buffer for
  14801. */
  14802. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14803. // Create the framebuffer
  14804. var internalTexture = renderTarget.getInternalTexture();
  14805. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14806. return;
  14807. }
  14808. var gl = this._gl;
  14809. var depthStencilTexture = renderTarget.depthStencilTexture;
  14810. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14811. if (depthStencilTexture.isCube) {
  14812. if (depthStencilTexture._generateStencilBuffer) {
  14813. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14814. }
  14815. else {
  14816. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14817. }
  14818. }
  14819. else {
  14820. if (depthStencilTexture._generateStencilBuffer) {
  14821. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14822. }
  14823. else {
  14824. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14825. }
  14826. }
  14827. this.bindUnboundFramebuffer(null);
  14828. };
  14829. /**
  14830. * Creates a new render target texture
  14831. * @param size defines the size of the texture
  14832. * @param options defines the options used to create the texture
  14833. * @returns a new render target texture stored in an InternalTexture
  14834. */
  14835. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14836. var fullOptions = new RenderTargetCreationOptions();
  14837. if (options !== undefined && typeof options === "object") {
  14838. fullOptions.generateMipMaps = options.generateMipMaps;
  14839. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14840. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14841. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14842. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  14843. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  14844. }
  14845. else {
  14846. fullOptions.generateMipMaps = options;
  14847. fullOptions.generateDepthBuffer = true;
  14848. fullOptions.generateStencilBuffer = false;
  14849. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14850. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14851. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  14852. }
  14853. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14854. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14855. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14856. }
  14857. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14858. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14859. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14860. }
  14861. var gl = this._gl;
  14862. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14863. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14864. var width = size.width || size;
  14865. var height = size.height || size;
  14866. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  14867. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14868. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14869. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14870. }
  14871. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14872. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14873. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14874. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14875. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  14876. // Create the framebuffer
  14877. var framebuffer = gl.createFramebuffer();
  14878. this.bindUnboundFramebuffer(framebuffer);
  14879. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14880. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  14881. if (fullOptions.generateMipMaps) {
  14882. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14883. }
  14884. // Unbind
  14885. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14886. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14887. this.bindUnboundFramebuffer(null);
  14888. texture._framebuffer = framebuffer;
  14889. texture.baseWidth = width;
  14890. texture.baseHeight = height;
  14891. texture.width = width;
  14892. texture.height = height;
  14893. texture.isReady = true;
  14894. texture.samples = 1;
  14895. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  14896. texture.samplingMode = fullOptions.samplingMode;
  14897. texture.type = fullOptions.type;
  14898. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14899. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  14900. // this.resetTextureCache();
  14901. this._internalTexturesCache.push(texture);
  14902. return texture;
  14903. };
  14904. /**
  14905. * Create a multi render target texture
  14906. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  14907. * @param size defines the size of the texture
  14908. * @param options defines the creation options
  14909. * @returns the cube texture as an InternalTexture
  14910. */
  14911. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  14912. var generateMipMaps = false;
  14913. var generateDepthBuffer = true;
  14914. var generateStencilBuffer = false;
  14915. var generateDepthTexture = false;
  14916. var textureCount = 1;
  14917. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  14918. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14919. var types = new Array();
  14920. var samplingModes = new Array();
  14921. if (options !== undefined) {
  14922. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  14923. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14924. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  14925. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  14926. textureCount = options.textureCount || 1;
  14927. if (options.types) {
  14928. types = options.types;
  14929. }
  14930. if (options.samplingModes) {
  14931. samplingModes = options.samplingModes;
  14932. }
  14933. }
  14934. var gl = this._gl;
  14935. // Create the framebuffer
  14936. var framebuffer = gl.createFramebuffer();
  14937. this.bindUnboundFramebuffer(framebuffer);
  14938. var width = size.width || size;
  14939. var height = size.height || size;
  14940. var textures = [];
  14941. var attachments = [];
  14942. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  14943. for (var i = 0; i < textureCount; i++) {
  14944. var samplingMode = samplingModes[i] || defaultSamplingMode;
  14945. var type = types[i] || defaultType;
  14946. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14947. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14948. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14949. }
  14950. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14951. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14952. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14953. }
  14954. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14955. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14956. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14957. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14958. }
  14959. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  14960. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  14961. textures.push(texture);
  14962. attachments.push(attachment);
  14963. gl.activeTexture(gl["TEXTURE" + i]);
  14964. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  14965. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14966. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14967. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14968. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14969. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14970. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14971. if (generateMipMaps) {
  14972. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14973. }
  14974. // Unbind
  14975. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14976. texture._framebuffer = framebuffer;
  14977. texture._depthStencilBuffer = depthStencilBuffer;
  14978. texture.baseWidth = width;
  14979. texture.baseHeight = height;
  14980. texture.width = width;
  14981. texture.height = height;
  14982. texture.isReady = true;
  14983. texture.samples = 1;
  14984. texture.generateMipMaps = generateMipMaps;
  14985. texture.samplingMode = samplingMode;
  14986. texture.type = type;
  14987. texture._generateDepthBuffer = generateDepthBuffer;
  14988. texture._generateStencilBuffer = generateStencilBuffer;
  14989. texture._attachments = attachments;
  14990. this._internalTexturesCache.push(texture);
  14991. }
  14992. if (generateDepthTexture && this._caps.depthTextureExtension) {
  14993. // Depth texture
  14994. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  14995. gl.activeTexture(gl.TEXTURE0);
  14996. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  14997. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14998. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14999. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15000. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15001. 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);
  15002. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15003. depthTexture._framebuffer = framebuffer;
  15004. depthTexture.baseWidth = width;
  15005. depthTexture.baseHeight = height;
  15006. depthTexture.width = width;
  15007. depthTexture.height = height;
  15008. depthTexture.isReady = true;
  15009. depthTexture.samples = 1;
  15010. depthTexture.generateMipMaps = generateMipMaps;
  15011. depthTexture.samplingMode = gl.NEAREST;
  15012. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15013. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15014. textures.push(depthTexture);
  15015. this._internalTexturesCache.push(depthTexture);
  15016. }
  15017. gl.drawBuffers(attachments);
  15018. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15019. this.bindUnboundFramebuffer(null);
  15020. this.resetTextureCache();
  15021. return textures;
  15022. };
  15023. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15024. if (samples === void 0) { samples = 1; }
  15025. var depthStencilBuffer = null;
  15026. var gl = this._gl;
  15027. // Create the depth/stencil buffer
  15028. if (generateStencilBuffer) {
  15029. depthStencilBuffer = gl.createRenderbuffer();
  15030. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15031. if (samples > 1) {
  15032. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15033. }
  15034. else {
  15035. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15036. }
  15037. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15038. }
  15039. else if (generateDepthBuffer) {
  15040. depthStencilBuffer = gl.createRenderbuffer();
  15041. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15042. if (samples > 1) {
  15043. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15044. }
  15045. else {
  15046. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15047. }
  15048. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15049. }
  15050. return depthStencilBuffer;
  15051. };
  15052. /**
  15053. * Updates the sample count of a render target texture
  15054. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15055. * @param texture defines the texture to update
  15056. * @param samples defines the sample count to set
  15057. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15058. */
  15059. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15060. if (this.webGLVersion < 2 || !texture) {
  15061. return 1;
  15062. }
  15063. if (texture.samples === samples) {
  15064. return samples;
  15065. }
  15066. var gl = this._gl;
  15067. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15068. // Dispose previous render buffers
  15069. if (texture._depthStencilBuffer) {
  15070. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15071. texture._depthStencilBuffer = null;
  15072. }
  15073. if (texture._MSAAFramebuffer) {
  15074. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15075. texture._MSAAFramebuffer = null;
  15076. }
  15077. if (texture._MSAARenderBuffer) {
  15078. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15079. texture._MSAARenderBuffer = null;
  15080. }
  15081. if (samples > 1) {
  15082. var framebuffer = gl.createFramebuffer();
  15083. if (!framebuffer) {
  15084. throw new Error("Unable to create multi sampled framebuffer");
  15085. }
  15086. texture._MSAAFramebuffer = framebuffer;
  15087. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15088. var colorRenderbuffer = gl.createRenderbuffer();
  15089. if (!colorRenderbuffer) {
  15090. throw new Error("Unable to create multi sampled framebuffer");
  15091. }
  15092. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15093. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15094. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15095. texture._MSAARenderBuffer = colorRenderbuffer;
  15096. }
  15097. else {
  15098. this.bindUnboundFramebuffer(texture._framebuffer);
  15099. }
  15100. texture.samples = samples;
  15101. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15102. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15103. this.bindUnboundFramebuffer(null);
  15104. return samples;
  15105. };
  15106. /**
  15107. * Update the sample count for a given multiple render target texture
  15108. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15109. * @param textures defines the textures to update
  15110. * @param samples defines the sample count to set
  15111. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15112. */
  15113. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15114. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15115. return 1;
  15116. }
  15117. if (textures[0].samples === samples) {
  15118. return samples;
  15119. }
  15120. var gl = this._gl;
  15121. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15122. // Dispose previous render buffers
  15123. if (textures[0]._depthStencilBuffer) {
  15124. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15125. textures[0]._depthStencilBuffer = null;
  15126. }
  15127. if (textures[0]._MSAAFramebuffer) {
  15128. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15129. textures[0]._MSAAFramebuffer = null;
  15130. }
  15131. for (var i = 0; i < textures.length; i++) {
  15132. if (textures[i]._MSAARenderBuffer) {
  15133. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15134. textures[i]._MSAARenderBuffer = null;
  15135. }
  15136. }
  15137. if (samples > 1) {
  15138. var framebuffer = gl.createFramebuffer();
  15139. if (!framebuffer) {
  15140. throw new Error("Unable to create multi sampled framebuffer");
  15141. }
  15142. this.bindUnboundFramebuffer(framebuffer);
  15143. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15144. var attachments = [];
  15145. for (var i = 0; i < textures.length; i++) {
  15146. var texture = textures[i];
  15147. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15148. var colorRenderbuffer = gl.createRenderbuffer();
  15149. if (!colorRenderbuffer) {
  15150. throw new Error("Unable to create multi sampled framebuffer");
  15151. }
  15152. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15153. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15154. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15155. texture._MSAAFramebuffer = framebuffer;
  15156. texture._MSAARenderBuffer = colorRenderbuffer;
  15157. texture.samples = samples;
  15158. texture._depthStencilBuffer = depthStencilBuffer;
  15159. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15160. attachments.push(attachment);
  15161. }
  15162. gl.drawBuffers(attachments);
  15163. }
  15164. else {
  15165. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15166. }
  15167. this.bindUnboundFramebuffer(null);
  15168. return samples;
  15169. };
  15170. /** @ignore */
  15171. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15172. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15173. };
  15174. /** @ignore */
  15175. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15176. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15177. };
  15178. /**
  15179. * Creates a new render target cube texture
  15180. * @param size defines the size of the texture
  15181. * @param options defines the options used to create the texture
  15182. * @returns a new render target cube texture stored in an InternalTexture
  15183. */
  15184. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15185. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15186. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15187. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15188. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15189. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15190. }
  15191. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15192. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15193. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15194. }
  15195. var gl = this._gl;
  15196. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15197. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15198. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15199. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15200. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15201. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15202. }
  15203. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15204. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15205. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15206. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15207. for (var face = 0; face < 6; face++) {
  15208. 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);
  15209. }
  15210. // Create the framebuffer
  15211. var framebuffer = gl.createFramebuffer();
  15212. this.bindUnboundFramebuffer(framebuffer);
  15213. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15214. // MipMaps
  15215. if (fullOptions.generateMipMaps) {
  15216. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15217. }
  15218. // Unbind
  15219. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15220. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15221. this.bindUnboundFramebuffer(null);
  15222. texture._framebuffer = framebuffer;
  15223. texture.width = size;
  15224. texture.height = size;
  15225. texture.isReady = true;
  15226. texture.isCube = true;
  15227. texture.samples = 1;
  15228. texture.generateMipMaps = fullOptions.generateMipMaps;
  15229. texture.samplingMode = fullOptions.samplingMode;
  15230. texture.type = fullOptions.type;
  15231. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15232. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15233. this._internalTexturesCache.push(texture);
  15234. return texture;
  15235. };
  15236. /**
  15237. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15238. * @param rootUrl defines the url where the file to load is located
  15239. * @param scene defines the current scene
  15240. * @param scale defines scale to apply to the mip map selection
  15241. * @param offset defines offset to apply to the mip map selection
  15242. * @param onLoad defines an optional callback raised when the texture is loaded
  15243. * @param onError defines an optional callback raised if there is an issue to load the texture
  15244. * @param format defines the format of the data
  15245. * @param forcedExtension defines the extension to use to pick the right loader
  15246. * @returns the cube texture as an InternalTexture
  15247. */
  15248. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15249. var _this = this;
  15250. if (onLoad === void 0) { onLoad = null; }
  15251. if (onError === void 0) { onError = null; }
  15252. if (forcedExtension === void 0) { forcedExtension = null; }
  15253. var callback = function (loadData) {
  15254. if (!loadData) {
  15255. if (onLoad) {
  15256. onLoad(null);
  15257. }
  15258. return;
  15259. }
  15260. var texture = loadData.texture;
  15261. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15262. texture._lodGenerationScale = scale;
  15263. texture._lodGenerationOffset = offset;
  15264. if (_this._caps.textureLOD) {
  15265. // Do not add extra process if texture lod is supported.
  15266. if (onLoad) {
  15267. onLoad(texture);
  15268. }
  15269. return;
  15270. }
  15271. var mipSlices = 3;
  15272. var gl = _this._gl;
  15273. var width = loadData.width;
  15274. if (!width) {
  15275. return;
  15276. }
  15277. var textures = [];
  15278. for (var i = 0; i < mipSlices; i++) {
  15279. //compute LOD from even spacing in smoothness (matching shader calculation)
  15280. var smoothness = i / (mipSlices - 1);
  15281. var roughness = 1 - smoothness;
  15282. var minLODIndex = offset; // roughness = 0
  15283. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15284. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15285. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15286. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15287. glTextureFromLod.isCube = true;
  15288. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15289. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15290. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15291. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15292. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15293. if (loadData.isDDS) {
  15294. var info = loadData.info;
  15295. var data = loadData.data;
  15296. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15297. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15298. }
  15299. else {
  15300. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15301. }
  15302. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15303. // Wrap in a base texture for easy binding.
  15304. var lodTexture = new BABYLON.BaseTexture(scene);
  15305. lodTexture.isCube = true;
  15306. lodTexture._texture = glTextureFromLod;
  15307. glTextureFromLod.isReady = true;
  15308. textures.push(lodTexture);
  15309. }
  15310. texture._lodTextureHigh = textures[2];
  15311. texture._lodTextureMid = textures[1];
  15312. texture._lodTextureLow = textures[0];
  15313. if (onLoad) {
  15314. onLoad(texture);
  15315. }
  15316. };
  15317. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  15318. };
  15319. /**
  15320. * Creates a cube texture
  15321. * @param rootUrl defines the url where the files to load is located
  15322. * @param scene defines the current scene
  15323. * @param files defines the list of files to load (1 per face)
  15324. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15325. * @param onLoad defines an optional callback raised when the texture is loaded
  15326. * @param onError defines an optional callback raised if there is an issue to load the texture
  15327. * @param format defines the format of the data
  15328. * @param forcedExtension defines the extension to use to pick the right loader
  15329. * @returns the cube texture as an InternalTexture
  15330. */
  15331. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  15332. var _this = this;
  15333. if (onLoad === void 0) { onLoad = null; }
  15334. if (onError === void 0) { onError = null; }
  15335. if (forcedExtension === void 0) { forcedExtension = null; }
  15336. var gl = this._gl;
  15337. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15338. texture.isCube = true;
  15339. texture.url = rootUrl;
  15340. texture.generateMipMaps = !noMipmap;
  15341. if (!this._doNotHandleContextLost) {
  15342. texture._extension = forcedExtension;
  15343. texture._files = files;
  15344. }
  15345. var isKTX = false;
  15346. var isDDS = false;
  15347. var lastDot = rootUrl.lastIndexOf('.');
  15348. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15349. if (this._textureFormatInUse) {
  15350. extension = this._textureFormatInUse;
  15351. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15352. isKTX = true;
  15353. }
  15354. else {
  15355. isDDS = (extension === ".dds");
  15356. }
  15357. var onerror = function (request, exception) {
  15358. if (onError && request) {
  15359. onError(request.status + " " + request.statusText, exception);
  15360. }
  15361. };
  15362. if (isKTX) {
  15363. this._loadFile(rootUrl, function (data) {
  15364. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15365. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15366. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15367. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15368. ktx.uploadLevels(_this._gl, !noMipmap);
  15369. _this.setCubeMapTextureParams(gl, loadMipmap);
  15370. texture.width = ktx.pixelWidth;
  15371. texture.height = ktx.pixelHeight;
  15372. texture.isReady = true;
  15373. }, undefined, undefined, true, onerror);
  15374. }
  15375. else if (isDDS) {
  15376. if (files && files.length === 6) {
  15377. this._cascadeLoadFiles(scene, function (imgs) {
  15378. var info;
  15379. var loadMipmap = false;
  15380. var width = 0;
  15381. for (var index = 0; index < imgs.length; index++) {
  15382. var data = imgs[index];
  15383. info = BABYLON.DDSTools.GetDDSInfo(data);
  15384. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15385. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15386. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15387. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15388. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15389. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15390. }
  15391. texture.width = info.width;
  15392. texture.height = info.height;
  15393. texture.type = info.textureType;
  15394. width = info.width;
  15395. }
  15396. _this.setCubeMapTextureParams(gl, loadMipmap);
  15397. texture.isReady = true;
  15398. if (onLoad) {
  15399. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15400. }
  15401. }, files, onError);
  15402. }
  15403. else {
  15404. this._loadFile(rootUrl, function (data) {
  15405. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15406. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15407. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15408. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15409. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15410. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15411. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15412. }
  15413. _this.setCubeMapTextureParams(gl, loadMipmap);
  15414. texture.width = info.width;
  15415. texture.height = info.height;
  15416. texture.isReady = true;
  15417. texture.type = info.textureType;
  15418. if (onLoad) {
  15419. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15420. }
  15421. }, undefined, undefined, true, onerror);
  15422. }
  15423. }
  15424. else {
  15425. if (!files) {
  15426. throw new Error("Cannot load cubemap because files were not defined");
  15427. }
  15428. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15429. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15430. var height = width;
  15431. _this._prepareWorkingCanvas();
  15432. if (!_this._workingCanvas || !_this._workingContext) {
  15433. return;
  15434. }
  15435. _this._workingCanvas.width = width;
  15436. _this._workingCanvas.height = height;
  15437. var faces = [
  15438. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15439. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15440. ];
  15441. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15442. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15443. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15444. for (var index = 0; index < faces.length; index++) {
  15445. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15446. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15447. }
  15448. if (!noMipmap) {
  15449. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15450. }
  15451. _this.setCubeMapTextureParams(gl, !noMipmap);
  15452. texture.width = width;
  15453. texture.height = height;
  15454. texture.isReady = true;
  15455. if (format) {
  15456. texture.format = format;
  15457. }
  15458. texture.onLoadedObservable.notifyObservers(texture);
  15459. texture.onLoadedObservable.clear();
  15460. if (onLoad) {
  15461. onLoad();
  15462. }
  15463. }, files, onError);
  15464. }
  15465. this._internalTexturesCache.push(texture);
  15466. return texture;
  15467. };
  15468. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15469. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15470. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15471. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15472. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15473. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15474. // this.resetTextureCache();
  15475. };
  15476. /**
  15477. * Update a raw cube texture
  15478. * @param texture defines the texture to udpdate
  15479. * @param data defines the data to store
  15480. * @param format defines the data format
  15481. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15482. * @param invertY defines if data must be stored with Y axis inverted
  15483. * @param compression defines the compression used (null by default)
  15484. * @param level defines which level of the texture to update
  15485. */
  15486. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15487. if (compression === void 0) { compression = null; }
  15488. if (level === void 0) { level = 0; }
  15489. texture._bufferViewArray = data;
  15490. texture.format = format;
  15491. texture.type = type;
  15492. texture.invertY = invertY;
  15493. texture._compression = compression;
  15494. var gl = this._gl;
  15495. var textureType = this._getWebGLTextureType(type);
  15496. var internalFormat = this._getInternalFormat(format);
  15497. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15498. var needConversion = false;
  15499. if (internalFormat === gl.RGB) {
  15500. internalFormat = gl.RGBA;
  15501. needConversion = true;
  15502. }
  15503. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15504. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15505. if (texture.width % 4 !== 0) {
  15506. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15507. }
  15508. // Data are known to be in +X +Y +Z -X -Y -Z
  15509. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15510. var faceData = data[faceIndex];
  15511. if (compression) {
  15512. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15513. }
  15514. else {
  15515. if (needConversion) {
  15516. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15517. }
  15518. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15519. }
  15520. }
  15521. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15522. if (isPot && texture.generateMipMaps && level === 0) {
  15523. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15524. }
  15525. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15526. // this.resetTextureCache();
  15527. texture.isReady = true;
  15528. };
  15529. /**
  15530. * Creates a new raw cube texture
  15531. * @param data defines the array of data to use to create each face
  15532. * @param size defines the size of the textures
  15533. * @param format defines the format of the data
  15534. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15535. * @param generateMipMaps defines if the engine should generate the mip levels
  15536. * @param invertY defines if data must be stored with Y axis inverted
  15537. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15538. * @param compression defines the compression used (null by default)
  15539. * @returns the cube texture as an InternalTexture
  15540. */
  15541. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15542. if (compression === void 0) { compression = null; }
  15543. var gl = this._gl;
  15544. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15545. texture.isCube = true;
  15546. texture.generateMipMaps = generateMipMaps;
  15547. texture.format = format;
  15548. texture.type = type;
  15549. if (!this._doNotHandleContextLost) {
  15550. texture._bufferViewArray = data;
  15551. }
  15552. var textureType = this._getWebGLTextureType(type);
  15553. var internalFormat = this._getInternalFormat(format);
  15554. if (internalFormat === gl.RGB) {
  15555. internalFormat = gl.RGBA;
  15556. }
  15557. var width = size;
  15558. var height = width;
  15559. texture.width = width;
  15560. texture.height = height;
  15561. // Double check on POT to generate Mips.
  15562. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15563. if (!isPot) {
  15564. generateMipMaps = false;
  15565. }
  15566. // Upload data if needed. The texture won't be ready until then.
  15567. if (data) {
  15568. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15569. }
  15570. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15571. // Filters
  15572. if (data && generateMipMaps) {
  15573. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15574. }
  15575. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15576. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15577. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15578. }
  15579. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15580. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15581. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15582. }
  15583. else {
  15584. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15585. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15586. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15587. }
  15588. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15589. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15590. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15591. return texture;
  15592. };
  15593. /**
  15594. * Creates a new raw cube texture from a specified url
  15595. * @param url defines the url where the data is located
  15596. * @param scene defines the current scene
  15597. * @param size defines the size of the textures
  15598. * @param format defines the format of the data
  15599. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15600. * @param noMipmap defines if the engine should avoid generating the mip levels
  15601. * @param callback defines a callback used to extract texture data from loaded data
  15602. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15603. * @param onLoad defines a callback called when texture is loaded
  15604. * @param onError defines a callback called if there is an error
  15605. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15606. * @param invertY defines if data must be stored with Y axis inverted
  15607. * @returns the cube texture as an InternalTexture
  15608. */
  15609. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15610. var _this = this;
  15611. if (onLoad === void 0) { onLoad = null; }
  15612. if (onError === void 0) { onError = null; }
  15613. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15614. if (invertY === void 0) { invertY = false; }
  15615. var gl = this._gl;
  15616. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15617. scene._addPendingData(texture);
  15618. texture.url = url;
  15619. this._internalTexturesCache.push(texture);
  15620. var onerror = function (request, exception) {
  15621. scene._removePendingData(texture);
  15622. if (onError && request) {
  15623. onError(request.status + " " + request.statusText, exception);
  15624. }
  15625. };
  15626. var internalCallback = function (data) {
  15627. var width = texture.width;
  15628. var faceDataArrays = callback(data);
  15629. if (!faceDataArrays) {
  15630. return;
  15631. }
  15632. if (mipmapGenerator) {
  15633. var textureType = _this._getWebGLTextureType(type);
  15634. var internalFormat = _this._getInternalFormat(format);
  15635. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15636. var needConversion = false;
  15637. if (internalFormat === gl.RGB) {
  15638. internalFormat = gl.RGBA;
  15639. needConversion = true;
  15640. }
  15641. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15642. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15643. var mipData = mipmapGenerator(faceDataArrays);
  15644. for (var level = 0; level < mipData.length; level++) {
  15645. var mipSize = width >> level;
  15646. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15647. var mipFaceData = mipData[level][faceIndex];
  15648. if (needConversion) {
  15649. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15650. }
  15651. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15652. }
  15653. }
  15654. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15655. }
  15656. else {
  15657. texture.generateMipMaps = !noMipmap;
  15658. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15659. }
  15660. texture.isReady = true;
  15661. // this.resetTextureCache();
  15662. scene._removePendingData(texture);
  15663. if (onLoad) {
  15664. onLoad();
  15665. }
  15666. };
  15667. this._loadFile(url, function (data) {
  15668. internalCallback(data);
  15669. }, undefined, scene.database, true, onerror);
  15670. return texture;
  15671. };
  15672. ;
  15673. /**
  15674. * Update a raw 3D texture
  15675. * @param texture defines the texture to update
  15676. * @param data defines the data to store
  15677. * @param format defines the data format
  15678. * @param invertY defines if data must be stored with Y axis inverted
  15679. * @param compression defines the used compression (can be null)
  15680. */
  15681. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15682. if (compression === void 0) { compression = null; }
  15683. var internalFormat = this._getInternalFormat(format);
  15684. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15685. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15686. if (!this._doNotHandleContextLost) {
  15687. texture._bufferView = data;
  15688. texture.format = format;
  15689. texture.invertY = invertY;
  15690. texture._compression = compression;
  15691. }
  15692. if (texture.width % 4 !== 0) {
  15693. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15694. }
  15695. if (compression && data) {
  15696. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15697. }
  15698. else {
  15699. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15700. }
  15701. if (texture.generateMipMaps) {
  15702. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15703. }
  15704. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15705. // this.resetTextureCache();
  15706. texture.isReady = true;
  15707. };
  15708. /**
  15709. * Creates a new raw 3D texture
  15710. * @param data defines the data used to create the texture
  15711. * @param width defines the width of the texture
  15712. * @param height defines the height of the texture
  15713. * @param depth defines the depth of the texture
  15714. * @param format defines the format of the texture
  15715. * @param generateMipMaps defines if the engine must generate mip levels
  15716. * @param invertY defines if data must be stored with Y axis inverted
  15717. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15718. * @param compression defines the compressed used (can be null)
  15719. * @returns a new raw 3D texture (stored in an InternalTexture)
  15720. */
  15721. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15722. if (compression === void 0) { compression = null; }
  15723. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15724. texture.baseWidth = width;
  15725. texture.baseHeight = height;
  15726. texture.baseDepth = depth;
  15727. texture.width = width;
  15728. texture.height = height;
  15729. texture.depth = depth;
  15730. texture.format = format;
  15731. texture.generateMipMaps = generateMipMaps;
  15732. texture.samplingMode = samplingMode;
  15733. texture.is3D = true;
  15734. if (!this._doNotHandleContextLost) {
  15735. texture._bufferView = data;
  15736. }
  15737. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15738. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15739. // Filters
  15740. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15741. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15742. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15743. if (generateMipMaps) {
  15744. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15745. }
  15746. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15747. this._internalTexturesCache.push(texture);
  15748. return texture;
  15749. };
  15750. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15751. var gl = this._gl;
  15752. if (!gl) {
  15753. return;
  15754. }
  15755. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15756. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15757. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15758. if (!noMipmap && !isCompressed) {
  15759. gl.generateMipmap(gl.TEXTURE_2D);
  15760. }
  15761. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15762. // this.resetTextureCache();
  15763. if (scene) {
  15764. scene._removePendingData(texture);
  15765. }
  15766. texture.onLoadedObservable.notifyObservers(texture);
  15767. texture.onLoadedObservable.clear();
  15768. };
  15769. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15770. var _this = this;
  15771. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15772. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  15773. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  15774. var gl = this._gl;
  15775. if (!gl) {
  15776. return;
  15777. }
  15778. if (!texture._webGLTexture) {
  15779. // this.resetTextureCache();
  15780. if (scene) {
  15781. scene._removePendingData(texture);
  15782. }
  15783. return;
  15784. }
  15785. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15786. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15787. texture.baseWidth = width;
  15788. texture.baseHeight = height;
  15789. texture.width = potWidth;
  15790. texture.height = potHeight;
  15791. texture.isReady = true;
  15792. if (processFunction(potWidth, potHeight, function () {
  15793. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15794. })) {
  15795. // Returning as texture needs extra async steps
  15796. return;
  15797. }
  15798. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15799. };
  15800. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  15801. // Create new RGBA data container.
  15802. var rgbaData;
  15803. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  15804. rgbaData = new Float32Array(width * height * 4);
  15805. }
  15806. else {
  15807. rgbaData = new Uint32Array(width * height * 4);
  15808. }
  15809. // Convert each pixel.
  15810. for (var x = 0; x < width; x++) {
  15811. for (var y = 0; y < height; y++) {
  15812. var index = (y * width + x) * 3;
  15813. var newIndex = (y * width + x) * 4;
  15814. // Map Old Value to new value.
  15815. rgbaData[newIndex + 0] = rgbData[index + 0];
  15816. rgbaData[newIndex + 1] = rgbData[index + 1];
  15817. rgbaData[newIndex + 2] = rgbData[index + 2];
  15818. // Add fully opaque alpha channel.
  15819. rgbaData[newIndex + 3] = 1;
  15820. }
  15821. }
  15822. return rgbaData;
  15823. };
  15824. /** @ignore */
  15825. Engine.prototype._releaseFramebufferObjects = function (texture) {
  15826. var gl = this._gl;
  15827. if (texture._framebuffer) {
  15828. gl.deleteFramebuffer(texture._framebuffer);
  15829. texture._framebuffer = null;
  15830. }
  15831. if (texture._depthStencilBuffer) {
  15832. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15833. texture._depthStencilBuffer = null;
  15834. }
  15835. if (texture._MSAAFramebuffer) {
  15836. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15837. texture._MSAAFramebuffer = null;
  15838. }
  15839. if (texture._MSAARenderBuffer) {
  15840. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15841. texture._MSAARenderBuffer = null;
  15842. }
  15843. };
  15844. /** @ignore */
  15845. Engine.prototype._releaseTexture = function (texture) {
  15846. var gl = this._gl;
  15847. this._releaseFramebufferObjects(texture);
  15848. gl.deleteTexture(texture._webGLTexture);
  15849. // Unbind channels
  15850. this.unbindAllTextures();
  15851. var index = this._internalTexturesCache.indexOf(texture);
  15852. if (index !== -1) {
  15853. this._internalTexturesCache.splice(index, 1);
  15854. }
  15855. // Integrated fixed lod samplers.
  15856. if (texture._lodTextureHigh) {
  15857. texture._lodTextureHigh.dispose();
  15858. }
  15859. if (texture._lodTextureMid) {
  15860. texture._lodTextureMid.dispose();
  15861. }
  15862. if (texture._lodTextureLow) {
  15863. texture._lodTextureLow.dispose();
  15864. }
  15865. // Set output texture of post process to null if the texture has been released/disposed
  15866. this.scenes.forEach(function (scene) {
  15867. scene.postProcesses.forEach(function (postProcess) {
  15868. if (postProcess._outputTexture == texture) {
  15869. postProcess._outputTexture = null;
  15870. }
  15871. });
  15872. scene.cameras.forEach(function (camera) {
  15873. camera._postProcesses.forEach(function (postProcess) {
  15874. if (postProcess) {
  15875. if (postProcess._outputTexture == texture) {
  15876. postProcess._outputTexture = null;
  15877. }
  15878. }
  15879. });
  15880. });
  15881. });
  15882. };
  15883. Engine.prototype.setProgram = function (program) {
  15884. if (this._currentProgram !== program) {
  15885. this._gl.useProgram(program);
  15886. this._currentProgram = program;
  15887. }
  15888. };
  15889. /**
  15890. * Binds an effect to the webGL context
  15891. * @param effect defines the effect to bind
  15892. */
  15893. Engine.prototype.bindSamplers = function (effect) {
  15894. this.setProgram(effect.getProgram());
  15895. var samplers = effect.getSamplers();
  15896. for (var index = 0; index < samplers.length; index++) {
  15897. var uniform = effect.getUniform(samplers[index]);
  15898. if (uniform) {
  15899. this._boundUniforms[index] = uniform;
  15900. }
  15901. }
  15902. this._currentEffect = null;
  15903. };
  15904. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  15905. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  15906. return;
  15907. }
  15908. // Remove
  15909. this._linkTrackers(internalTexture.previous, internalTexture.next);
  15910. // Bind last to it
  15911. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  15912. // Bind to dummy
  15913. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  15914. };
  15915. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  15916. if (!internalTexture) {
  15917. return -1;
  15918. }
  15919. internalTexture._initialSlot = channel;
  15920. if (this.disableTextureBindingOptimization) {
  15921. if (channel !== internalTexture._designatedSlot) {
  15922. this._textureCollisions.addCount(1, false);
  15923. }
  15924. }
  15925. else {
  15926. if (channel !== internalTexture._designatedSlot) {
  15927. if (internalTexture._designatedSlot > -1) {
  15928. return internalTexture._designatedSlot;
  15929. }
  15930. else {
  15931. // No slot for this texture, let's pick a new one (if we find a free slot)
  15932. if (this._nextFreeTextureSlots.length) {
  15933. return this._nextFreeTextureSlots[0];
  15934. }
  15935. // We need to recycle the oldest bound texture, sorry.
  15936. this._textureCollisions.addCount(1, false);
  15937. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  15938. }
  15939. }
  15940. }
  15941. return channel;
  15942. };
  15943. Engine.prototype._linkTrackers = function (previous, next) {
  15944. previous.next = next;
  15945. next.previous = previous;
  15946. };
  15947. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  15948. var currentSlot = internalTexture._designatedSlot;
  15949. if (currentSlot === -1) {
  15950. return -1;
  15951. }
  15952. internalTexture._designatedSlot = -1;
  15953. if (this.disableTextureBindingOptimization) {
  15954. return -1;
  15955. }
  15956. // Remove from bound list
  15957. this._linkTrackers(internalTexture.previous, internalTexture.next);
  15958. // Free the slot
  15959. this._boundTexturesCache[currentSlot] = null;
  15960. this._nextFreeTextureSlots.push(currentSlot);
  15961. return currentSlot;
  15962. };
  15963. Engine.prototype._activateCurrentTexture = function () {
  15964. if (this._currentTextureChannel !== this._activeChannel) {
  15965. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  15966. this._currentTextureChannel = this._activeChannel;
  15967. }
  15968. };
  15969. /** @ignore */
  15970. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  15971. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  15972. if (force === void 0) { force = false; }
  15973. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  15974. this._activeChannel = texture._designatedSlot;
  15975. }
  15976. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  15977. var isTextureForRendering = texture && texture._initialSlot > -1;
  15978. if (currentTextureBound !== texture || force) {
  15979. if (currentTextureBound) {
  15980. this._removeDesignatedSlot(currentTextureBound);
  15981. }
  15982. this._activateCurrentTexture();
  15983. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  15984. this._boundTexturesCache[this._activeChannel] = texture;
  15985. if (texture) {
  15986. if (!this.disableTextureBindingOptimization) {
  15987. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  15988. if (slotIndex > -1) {
  15989. this._nextFreeTextureSlots.splice(slotIndex, 1);
  15990. }
  15991. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  15992. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  15993. }
  15994. texture._designatedSlot = this._activeChannel;
  15995. }
  15996. }
  15997. else if (forTextureDataUpdate) {
  15998. this._activateCurrentTexture();
  15999. }
  16000. if (isTextureForRendering && !forTextureDataUpdate) {
  16001. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16002. }
  16003. };
  16004. /** @ignore */
  16005. Engine.prototype._bindTexture = function (channel, texture) {
  16006. if (channel < 0) {
  16007. return;
  16008. }
  16009. if (texture) {
  16010. channel = this._getCorrectTextureChannel(channel, texture);
  16011. }
  16012. this._activeChannel = channel;
  16013. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16014. };
  16015. /**
  16016. * Sets a texture to the webGL context from a postprocess
  16017. * @param channel defines the channel to use
  16018. * @param postProcess defines the source postprocess
  16019. */
  16020. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16021. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16022. };
  16023. /**
  16024. * Binds the output of the passed in post process to the texture channel specified
  16025. * @param channel The channel the texture should be bound to
  16026. * @param postProcess The post process which's output should be bound
  16027. */
  16028. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16029. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16030. };
  16031. /**
  16032. * Unbind all textures from the webGL context
  16033. */
  16034. Engine.prototype.unbindAllTextures = function () {
  16035. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16036. this._activeChannel = channel;
  16037. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16038. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16039. if (this.webGLVersion > 1) {
  16040. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16041. }
  16042. }
  16043. };
  16044. /**
  16045. * Sets a texture to the according uniform.
  16046. * @param channel The texture channel
  16047. * @param uniform The uniform to set
  16048. * @param texture The texture to apply
  16049. */
  16050. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16051. if (channel < 0) {
  16052. return;
  16053. }
  16054. if (uniform) {
  16055. this._boundUniforms[channel] = uniform;
  16056. }
  16057. this._setTexture(channel, texture);
  16058. };
  16059. /**
  16060. * Sets a depth stencil texture from a render target to the according uniform.
  16061. * @param channel The texture channel
  16062. * @param uniform The uniform to set
  16063. * @param texture The render target texture containing the depth stencil texture to apply
  16064. */
  16065. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16066. if (channel < 0) {
  16067. return;
  16068. }
  16069. if (uniform) {
  16070. this._boundUniforms[channel] = uniform;
  16071. }
  16072. if (!texture || !texture.depthStencilTexture) {
  16073. this._setTexture(channel, null);
  16074. }
  16075. else {
  16076. this._setTexture(channel, texture, false, true);
  16077. }
  16078. };
  16079. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16080. var uniform = this._boundUniforms[sourceSlot];
  16081. if (uniform._currentState === destination) {
  16082. return;
  16083. }
  16084. this._gl.uniform1i(uniform, destination);
  16085. uniform._currentState = destination;
  16086. };
  16087. Engine.prototype._getTextureWrapMode = function (mode) {
  16088. switch (mode) {
  16089. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16090. return this._gl.REPEAT;
  16091. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16092. return this._gl.CLAMP_TO_EDGE;
  16093. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16094. return this._gl.MIRRORED_REPEAT;
  16095. }
  16096. return this._gl.REPEAT;
  16097. };
  16098. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16099. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16100. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16101. // Not ready?
  16102. if (!texture) {
  16103. if (this._boundTexturesCache[channel] != null) {
  16104. this._activeChannel = channel;
  16105. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16106. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16107. if (this.webGLVersion > 1) {
  16108. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16109. }
  16110. }
  16111. return false;
  16112. }
  16113. // Video
  16114. if (texture.video) {
  16115. this._activeChannel = channel;
  16116. texture.update();
  16117. }
  16118. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  16119. texture.delayLoad();
  16120. return false;
  16121. }
  16122. var internalTexture;
  16123. if (depthStencilTexture) {
  16124. internalTexture = texture.depthStencilTexture;
  16125. }
  16126. else if (texture.isReady()) {
  16127. internalTexture = texture.getInternalTexture();
  16128. }
  16129. else if (texture.isCube) {
  16130. internalTexture = this.emptyCubeTexture;
  16131. }
  16132. else if (texture.is3D) {
  16133. internalTexture = this.emptyTexture3D;
  16134. }
  16135. else {
  16136. internalTexture = this.emptyTexture;
  16137. }
  16138. if (!isPartOfTextureArray) {
  16139. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16140. }
  16141. var needToBind = true;
  16142. if (this._boundTexturesCache[channel] === internalTexture) {
  16143. this._moveBoundTextureOnTop(internalTexture);
  16144. if (!isPartOfTextureArray) {
  16145. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16146. }
  16147. needToBind = false;
  16148. }
  16149. this._activeChannel = channel;
  16150. if (internalTexture && internalTexture.is3D) {
  16151. if (needToBind) {
  16152. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16153. }
  16154. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16155. internalTexture._cachedWrapU = texture.wrapU;
  16156. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16157. }
  16158. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16159. internalTexture._cachedWrapV = texture.wrapV;
  16160. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16161. }
  16162. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16163. internalTexture._cachedWrapR = texture.wrapR;
  16164. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16165. }
  16166. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16167. }
  16168. else if (internalTexture && internalTexture.isCube) {
  16169. if (needToBind) {
  16170. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16171. }
  16172. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16173. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16174. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16175. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16176. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16177. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16178. }
  16179. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16180. }
  16181. else {
  16182. if (needToBind) {
  16183. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16184. }
  16185. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16186. internalTexture._cachedWrapU = texture.wrapU;
  16187. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16188. }
  16189. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16190. internalTexture._cachedWrapV = texture.wrapV;
  16191. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16192. }
  16193. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16194. }
  16195. return true;
  16196. };
  16197. /**
  16198. * Sets an array of texture to the webGL context
  16199. * @param channel defines the channel where the texture array must be set
  16200. * @param uniform defines the associated uniform location
  16201. * @param textures defines the array of textures to bind
  16202. */
  16203. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16204. if (channel < 0 || !uniform) {
  16205. return;
  16206. }
  16207. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16208. this._textureUnits = new Int32Array(textures.length);
  16209. }
  16210. for (var i = 0; i < textures.length; i++) {
  16211. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16212. }
  16213. this._gl.uniform1iv(uniform, this._textureUnits);
  16214. for (var index = 0; index < textures.length; index++) {
  16215. this._setTexture(this._textureUnits[index], textures[index], true);
  16216. }
  16217. };
  16218. /** @ignore */
  16219. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16220. var internalTexture = texture.getInternalTexture();
  16221. if (!internalTexture) {
  16222. return;
  16223. }
  16224. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16225. var value = texture.anisotropicFilteringLevel;
  16226. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16227. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16228. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16229. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16230. }
  16231. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16232. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16233. internalTexture._cachedAnisotropicFilteringLevel = value;
  16234. }
  16235. };
  16236. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16237. this._bindTextureDirectly(target, texture, true, true);
  16238. this._gl.texParameterf(target, parameter, value);
  16239. };
  16240. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16241. if (texture) {
  16242. this._bindTextureDirectly(target, texture, true, true);
  16243. }
  16244. this._gl.texParameteri(target, parameter, value);
  16245. };
  16246. /**
  16247. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16248. * @param x defines the x coordinate of the rectangle where pixels must be read
  16249. * @param y defines the y coordinate of the rectangle where pixels must be read
  16250. * @param width defines the width of the rectangle where pixels must be read
  16251. * @param height defines the height of the rectangle where pixels must be read
  16252. * @returns a Uint8Array containing RGBA colors
  16253. */
  16254. Engine.prototype.readPixels = function (x, y, width, height) {
  16255. var data = new Uint8Array(height * width * 4);
  16256. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16257. return data;
  16258. };
  16259. /**
  16260. * Add an externaly attached data from its key.
  16261. * This method call will fail and return false, if such key already exists.
  16262. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16263. * @param key the unique key that identifies the data
  16264. * @param data the data object to associate to the key for this Engine instance
  16265. * @return true if no such key were already present and the data was added successfully, false otherwise
  16266. */
  16267. Engine.prototype.addExternalData = function (key, data) {
  16268. if (!this._externalData) {
  16269. this._externalData = new BABYLON.StringDictionary();
  16270. }
  16271. return this._externalData.add(key, data);
  16272. };
  16273. /**
  16274. * Get an externaly attached data from its key
  16275. * @param key the unique key that identifies the data
  16276. * @return the associated data, if present (can be null), or undefined if not present
  16277. */
  16278. Engine.prototype.getExternalData = function (key) {
  16279. if (!this._externalData) {
  16280. this._externalData = new BABYLON.StringDictionary();
  16281. }
  16282. return this._externalData.get(key);
  16283. };
  16284. /**
  16285. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16286. * @param key the unique key that identifies the data
  16287. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16288. * @return the associated data, can be null if the factory returned null.
  16289. */
  16290. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16291. if (!this._externalData) {
  16292. this._externalData = new BABYLON.StringDictionary();
  16293. }
  16294. return this._externalData.getOrAddWithFactory(key, factory);
  16295. };
  16296. /**
  16297. * Remove an externaly attached data from the Engine instance
  16298. * @param key the unique key that identifies the data
  16299. * @return true if the data was successfully removed, false if it doesn't exist
  16300. */
  16301. Engine.prototype.removeExternalData = function (key) {
  16302. if (!this._externalData) {
  16303. this._externalData = new BABYLON.StringDictionary();
  16304. }
  16305. return this._externalData.remove(key);
  16306. };
  16307. /**
  16308. * Unbind all vertex attributes from the webGL context
  16309. */
  16310. Engine.prototype.unbindAllAttributes = function () {
  16311. if (this._mustWipeVertexAttributes) {
  16312. this._mustWipeVertexAttributes = false;
  16313. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16314. this._gl.disableVertexAttribArray(i);
  16315. this._vertexAttribArraysEnabled[i] = false;
  16316. this._currentBufferPointers[i].active = false;
  16317. }
  16318. return;
  16319. }
  16320. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16321. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16322. continue;
  16323. }
  16324. this._gl.disableVertexAttribArray(i);
  16325. this._vertexAttribArraysEnabled[i] = false;
  16326. this._currentBufferPointers[i].active = false;
  16327. }
  16328. };
  16329. /**
  16330. * 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
  16331. */
  16332. Engine.prototype.releaseEffects = function () {
  16333. for (var name in this._compiledEffects) {
  16334. this._deleteProgram(this._compiledEffects[name]._program);
  16335. }
  16336. this._compiledEffects = {};
  16337. };
  16338. /**
  16339. * Dispose and release all associated resources
  16340. */
  16341. Engine.prototype.dispose = function () {
  16342. this.hideLoadingUI();
  16343. this.stopRenderLoop();
  16344. // Release postProcesses
  16345. while (this.postProcesses.length) {
  16346. this.postProcesses[0].dispose();
  16347. }
  16348. // Empty texture
  16349. if (this._emptyTexture) {
  16350. this._releaseTexture(this._emptyTexture);
  16351. this._emptyTexture = null;
  16352. }
  16353. if (this._emptyCubeTexture) {
  16354. this._releaseTexture(this._emptyCubeTexture);
  16355. this._emptyCubeTexture = null;
  16356. }
  16357. // Rescale PP
  16358. if (this._rescalePostProcess) {
  16359. this._rescalePostProcess.dispose();
  16360. }
  16361. // Release scenes
  16362. while (this.scenes.length) {
  16363. this.scenes[0].dispose();
  16364. }
  16365. // Release audio engine
  16366. if (Engine.audioEngine) {
  16367. Engine.audioEngine.dispose();
  16368. }
  16369. // Release effects
  16370. this.releaseEffects();
  16371. // Unbind
  16372. this.unbindAllAttributes();
  16373. this._boundUniforms = [];
  16374. if (this._dummyFramebuffer) {
  16375. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16376. }
  16377. //WebVR
  16378. this.disableVR();
  16379. // Events
  16380. if (BABYLON.Tools.IsWindowObjectExist()) {
  16381. window.removeEventListener("blur", this._onBlur);
  16382. window.removeEventListener("focus", this._onFocus);
  16383. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16384. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16385. if (this._renderingCanvas) {
  16386. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16387. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16388. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16389. if (!this._doNotHandleContextLost) {
  16390. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16391. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16392. }
  16393. }
  16394. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16395. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16396. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16397. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16398. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16399. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16400. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16401. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16402. if (this._onVrDisplayConnect) {
  16403. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16404. if (this._onVrDisplayDisconnect) {
  16405. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16406. }
  16407. if (this._onVrDisplayPresentChange) {
  16408. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16409. }
  16410. this._onVrDisplayConnect = null;
  16411. this._onVrDisplayDisconnect = null;
  16412. }
  16413. }
  16414. // Remove from Instances
  16415. var index = Engine.Instances.indexOf(this);
  16416. if (index >= 0) {
  16417. Engine.Instances.splice(index, 1);
  16418. }
  16419. this._workingCanvas = null;
  16420. this._workingContext = null;
  16421. this._currentBufferPointers = [];
  16422. this._renderingCanvas = null;
  16423. this._currentProgram = null;
  16424. this._bindedRenderFunction = null;
  16425. this.onResizeObservable.clear();
  16426. this.onCanvasBlurObservable.clear();
  16427. this.onCanvasFocusObservable.clear();
  16428. this.onCanvasPointerOutObservable.clear();
  16429. this.onBeginFrameObservable.clear();
  16430. this.onEndFrameObservable.clear();
  16431. BABYLON.Effect.ResetCache();
  16432. // Abort active requests
  16433. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16434. var request = _a[_i];
  16435. request.abort();
  16436. }
  16437. };
  16438. // Loading screen
  16439. /**
  16440. * Display the loading screen
  16441. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16442. */
  16443. Engine.prototype.displayLoadingUI = function () {
  16444. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16445. return;
  16446. }
  16447. var loadingScreen = this.loadingScreen;
  16448. if (loadingScreen) {
  16449. loadingScreen.displayLoadingUI();
  16450. }
  16451. };
  16452. /**
  16453. * Hide the loading screen
  16454. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16455. */
  16456. Engine.prototype.hideLoadingUI = function () {
  16457. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16458. return;
  16459. }
  16460. var loadingScreen = this.loadingScreen;
  16461. if (loadingScreen) {
  16462. loadingScreen.hideLoadingUI();
  16463. }
  16464. };
  16465. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16466. /**
  16467. * Gets the current loading screen object
  16468. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16469. */
  16470. get: function () {
  16471. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16472. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16473. return this._loadingScreen;
  16474. },
  16475. /**
  16476. * Sets the current loading screen object
  16477. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16478. */
  16479. set: function (loadingScreen) {
  16480. this._loadingScreen = loadingScreen;
  16481. },
  16482. enumerable: true,
  16483. configurable: true
  16484. });
  16485. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16486. /**
  16487. * Sets the current loading screen text
  16488. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16489. */
  16490. set: function (text) {
  16491. this.loadingScreen.loadingUIText = text;
  16492. },
  16493. enumerable: true,
  16494. configurable: true
  16495. });
  16496. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16497. /**
  16498. * Sets the current loading screen background color
  16499. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16500. */
  16501. set: function (color) {
  16502. this.loadingScreen.loadingUIBackgroundColor = color;
  16503. },
  16504. enumerable: true,
  16505. configurable: true
  16506. });
  16507. /**
  16508. * Attach a new callback raised when context lost event is fired
  16509. * @param callback defines the callback to call
  16510. */
  16511. Engine.prototype.attachContextLostEvent = function (callback) {
  16512. if (this._renderingCanvas) {
  16513. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16514. }
  16515. };
  16516. /**
  16517. * Attach a new callback raised when context restored event is fired
  16518. * @param callback defines the callback to call
  16519. */
  16520. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16521. if (this._renderingCanvas) {
  16522. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16523. }
  16524. };
  16525. /**
  16526. * Gets the source code of the vertex shader associated with a specific webGL program
  16527. * @param program defines the program to use
  16528. * @returns a string containing the source code of the vertex shader associated with the program
  16529. */
  16530. Engine.prototype.getVertexShaderSource = function (program) {
  16531. var shaders = this._gl.getAttachedShaders(program);
  16532. if (!shaders) {
  16533. return null;
  16534. }
  16535. return this._gl.getShaderSource(shaders[0]);
  16536. };
  16537. /**
  16538. * Gets the source code of the fragment shader associated with a specific webGL program
  16539. * @param program defines the program to use
  16540. * @returns a string containing the source code of the fragment shader associated with the program
  16541. */
  16542. Engine.prototype.getFragmentShaderSource = function (program) {
  16543. var shaders = this._gl.getAttachedShaders(program);
  16544. if (!shaders) {
  16545. return null;
  16546. }
  16547. return this._gl.getShaderSource(shaders[1]);
  16548. };
  16549. /**
  16550. * Get the current error code of the webGL context
  16551. * @returns the error code
  16552. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16553. */
  16554. Engine.prototype.getError = function () {
  16555. return this._gl.getError();
  16556. };
  16557. // FPS
  16558. /**
  16559. * Gets the current framerate
  16560. * @returns a number representing the framerate
  16561. */
  16562. Engine.prototype.getFps = function () {
  16563. return this._fps;
  16564. };
  16565. /**
  16566. * Gets the time spent between current and previous frame
  16567. * @returns a number representing the delta time in ms
  16568. */
  16569. Engine.prototype.getDeltaTime = function () {
  16570. return this._deltaTime;
  16571. };
  16572. Engine.prototype._measureFps = function () {
  16573. this._performanceMonitor.sampleFrame();
  16574. this._fps = this._performanceMonitor.averageFPS;
  16575. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16576. };
  16577. /** @ignore */
  16578. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16579. if (faceIndex === void 0) { faceIndex = -1; }
  16580. var gl = this._gl;
  16581. if (!this._dummyFramebuffer) {
  16582. var dummy = gl.createFramebuffer();
  16583. if (!dummy) {
  16584. throw new Error("Unable to create dummy framebuffer");
  16585. }
  16586. this._dummyFramebuffer = dummy;
  16587. }
  16588. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16589. if (faceIndex > -1) {
  16590. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16591. }
  16592. else {
  16593. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16594. }
  16595. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16596. var buffer;
  16597. switch (readType) {
  16598. case gl.UNSIGNED_BYTE:
  16599. buffer = new Uint8Array(4 * width * height);
  16600. readType = gl.UNSIGNED_BYTE;
  16601. break;
  16602. default:
  16603. buffer = new Float32Array(4 * width * height);
  16604. readType = gl.FLOAT;
  16605. break;
  16606. }
  16607. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16608. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16609. return buffer;
  16610. };
  16611. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16612. if (this._webGLVersion > 1) {
  16613. return this._caps.colorBufferFloat;
  16614. }
  16615. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16616. };
  16617. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16618. if (this._webGLVersion > 1) {
  16619. return this._caps.colorBufferFloat;
  16620. }
  16621. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16622. };
  16623. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16624. Engine.prototype._canRenderToFramebuffer = function (type) {
  16625. var gl = this._gl;
  16626. //clear existing errors
  16627. while (gl.getError() !== gl.NO_ERROR) { }
  16628. var successful = true;
  16629. var texture = gl.createTexture();
  16630. gl.bindTexture(gl.TEXTURE_2D, texture);
  16631. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16632. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16633. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16634. var fb = gl.createFramebuffer();
  16635. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16636. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16637. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16638. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16639. successful = successful && (gl.getError() === gl.NO_ERROR);
  16640. //try render by clearing frame buffer's color buffer
  16641. if (successful) {
  16642. gl.clear(gl.COLOR_BUFFER_BIT);
  16643. successful = successful && (gl.getError() === gl.NO_ERROR);
  16644. }
  16645. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16646. if (successful) {
  16647. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16648. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16649. var readFormat = gl.RGBA;
  16650. var readType = gl.UNSIGNED_BYTE;
  16651. var buffer = new Uint8Array(4);
  16652. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16653. successful = successful && (gl.getError() === gl.NO_ERROR);
  16654. }
  16655. //clean up
  16656. gl.deleteTexture(texture);
  16657. gl.deleteFramebuffer(fb);
  16658. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16659. //clear accumulated errors
  16660. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16661. return successful;
  16662. };
  16663. /** @ignore */
  16664. Engine.prototype._getWebGLTextureType = function (type) {
  16665. if (type === Engine.TEXTURETYPE_FLOAT) {
  16666. return this._gl.FLOAT;
  16667. }
  16668. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16669. // Add Half Float Constant.
  16670. return this._gl.HALF_FLOAT_OES;
  16671. }
  16672. return this._gl.UNSIGNED_BYTE;
  16673. };
  16674. ;
  16675. Engine.prototype._getInternalFormat = function (format) {
  16676. var internalFormat = this._gl.RGBA;
  16677. switch (format) {
  16678. case Engine.TEXTUREFORMAT_ALPHA:
  16679. internalFormat = this._gl.ALPHA;
  16680. break;
  16681. case Engine.TEXTUREFORMAT_LUMINANCE:
  16682. internalFormat = this._gl.LUMINANCE;
  16683. break;
  16684. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16685. internalFormat = this._gl.LUMINANCE_ALPHA;
  16686. break;
  16687. case Engine.TEXTUREFORMAT_RGB:
  16688. case Engine.TEXTUREFORMAT_RGB32F:
  16689. internalFormat = this._gl.RGB;
  16690. break;
  16691. case Engine.TEXTUREFORMAT_RGBA:
  16692. case Engine.TEXTUREFORMAT_RGBA32F:
  16693. internalFormat = this._gl.RGBA;
  16694. break;
  16695. case Engine.TEXTUREFORMAT_R32F:
  16696. internalFormat = this._gl.RED;
  16697. break;
  16698. case Engine.TEXTUREFORMAT_RG32F:
  16699. internalFormat = this._gl.RG;
  16700. break;
  16701. }
  16702. return internalFormat;
  16703. };
  16704. /** @ignore */
  16705. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16706. if (this._webGLVersion === 1) {
  16707. if (format) {
  16708. switch (format) {
  16709. case Engine.TEXTUREFORMAT_LUMINANCE:
  16710. return this._gl.LUMINANCE;
  16711. }
  16712. }
  16713. return this._gl.RGBA;
  16714. }
  16715. if (type === Engine.TEXTURETYPE_FLOAT) {
  16716. if (format) {
  16717. switch (format) {
  16718. case Engine.TEXTUREFORMAT_R32F:
  16719. return this._gl.R32F;
  16720. case Engine.TEXTUREFORMAT_RG32F:
  16721. return this._gl.RG32F;
  16722. case Engine.TEXTUREFORMAT_RGB32F:
  16723. return this._gl.RGB32F;
  16724. }
  16725. }
  16726. return this._gl.RGBA32F;
  16727. }
  16728. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16729. return this._gl.RGBA16F;
  16730. }
  16731. if (format) {
  16732. switch (format) {
  16733. case Engine.TEXTUREFORMAT_LUMINANCE:
  16734. return this._gl.LUMINANCE;
  16735. }
  16736. }
  16737. return this._gl.RGBA;
  16738. };
  16739. ;
  16740. /** @ignore */
  16741. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16742. if (type === Engine.TEXTURETYPE_FLOAT) {
  16743. return this._gl.RGBA32F;
  16744. }
  16745. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16746. return this._gl.RGBA16F;
  16747. }
  16748. return this._gl.RGBA8;
  16749. };
  16750. ;
  16751. /**
  16752. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16753. * @return the new query
  16754. */
  16755. Engine.prototype.createQuery = function () {
  16756. return this._gl.createQuery();
  16757. };
  16758. /**
  16759. * Delete and release a webGL query
  16760. * @param query defines the query to delete
  16761. * @return the current engine
  16762. */
  16763. Engine.prototype.deleteQuery = function (query) {
  16764. this._gl.deleteQuery(query);
  16765. return this;
  16766. };
  16767. /**
  16768. * Check if a given query has resolved and got its value
  16769. * @param query defines the query to check
  16770. * @returns true if the query got its value
  16771. */
  16772. Engine.prototype.isQueryResultAvailable = function (query) {
  16773. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  16774. };
  16775. /**
  16776. * Gets the value of a given query
  16777. * @param query defines the query to check
  16778. * @returns the value of the query
  16779. */
  16780. Engine.prototype.getQueryResult = function (query) {
  16781. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  16782. };
  16783. /**
  16784. * Initiates an occlusion query
  16785. * @param algorithmType defines the algorithm to use
  16786. * @param query defines the query to use
  16787. * @returns the current engine
  16788. * @see http://doc.babylonjs.com/features/occlusionquery
  16789. */
  16790. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  16791. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16792. this._gl.beginQuery(glAlgorithm, query);
  16793. return this;
  16794. };
  16795. /**
  16796. * Ends an occlusion query
  16797. * @see http://doc.babylonjs.com/features/occlusionquery
  16798. * @param algorithmType defines the algorithm to use
  16799. * @returns the current engine
  16800. */
  16801. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  16802. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16803. this._gl.endQuery(glAlgorithm);
  16804. return this;
  16805. };
  16806. /* Time queries */
  16807. Engine.prototype._createTimeQuery = function () {
  16808. var timerQuery = this._caps.timerQuery;
  16809. if (timerQuery.createQueryEXT) {
  16810. return timerQuery.createQueryEXT();
  16811. }
  16812. return this.createQuery();
  16813. };
  16814. Engine.prototype._deleteTimeQuery = function (query) {
  16815. var timerQuery = this._caps.timerQuery;
  16816. if (timerQuery.deleteQueryEXT) {
  16817. timerQuery.deleteQueryEXT(query);
  16818. return;
  16819. }
  16820. this.deleteQuery(query);
  16821. };
  16822. Engine.prototype._getTimeQueryResult = function (query) {
  16823. var timerQuery = this._caps.timerQuery;
  16824. if (timerQuery.getQueryObjectEXT) {
  16825. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  16826. }
  16827. return this.getQueryResult(query);
  16828. };
  16829. Engine.prototype._getTimeQueryAvailability = function (query) {
  16830. var timerQuery = this._caps.timerQuery;
  16831. if (timerQuery.getQueryObjectEXT) {
  16832. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  16833. }
  16834. return this.isQueryResultAvailable(query);
  16835. };
  16836. /**
  16837. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  16838. * Please note that only one query can be issued at a time
  16839. * @returns a time token used to track the time span
  16840. */
  16841. Engine.prototype.startTimeQuery = function () {
  16842. var timerQuery = this._caps.timerQuery;
  16843. if (!timerQuery) {
  16844. return null;
  16845. }
  16846. var token = new BABYLON._TimeToken();
  16847. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16848. if (this._caps.canUseTimestampForTimerQuery) {
  16849. token._startTimeQuery = this._createTimeQuery();
  16850. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  16851. }
  16852. else {
  16853. if (this._currentNonTimestampToken) {
  16854. return this._currentNonTimestampToken;
  16855. }
  16856. token._timeElapsedQuery = this._createTimeQuery();
  16857. if (timerQuery.beginQueryEXT) {
  16858. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16859. }
  16860. else {
  16861. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16862. }
  16863. this._currentNonTimestampToken = token;
  16864. }
  16865. return token;
  16866. };
  16867. /**
  16868. * Ends a time query
  16869. * @param token defines the token used to measure the time span
  16870. * @returns the time spent (in ns)
  16871. */
  16872. Engine.prototype.endTimeQuery = function (token) {
  16873. var timerQuery = this._caps.timerQuery;
  16874. if (!timerQuery || !token) {
  16875. return -1;
  16876. }
  16877. if (this._caps.canUseTimestampForTimerQuery) {
  16878. if (!token._startTimeQuery) {
  16879. return -1;
  16880. }
  16881. if (!token._endTimeQuery) {
  16882. token._endTimeQuery = this._createTimeQuery();
  16883. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  16884. }
  16885. }
  16886. else if (!token._timeElapsedQueryEnded) {
  16887. if (!token._timeElapsedQuery) {
  16888. return -1;
  16889. }
  16890. if (timerQuery.endQueryEXT) {
  16891. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  16892. }
  16893. else {
  16894. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  16895. }
  16896. token._timeElapsedQueryEnded = true;
  16897. }
  16898. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16899. var available = false;
  16900. if (token._endTimeQuery) {
  16901. available = this._getTimeQueryAvailability(token._endTimeQuery);
  16902. }
  16903. else if (token._timeElapsedQuery) {
  16904. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  16905. }
  16906. if (available && !disjoint) {
  16907. var result = 0;
  16908. if (this._caps.canUseTimestampForTimerQuery) {
  16909. if (!token._startTimeQuery || !token._endTimeQuery) {
  16910. return -1;
  16911. }
  16912. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  16913. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  16914. result = timeEnd - timeStart;
  16915. this._deleteTimeQuery(token._startTimeQuery);
  16916. this._deleteTimeQuery(token._endTimeQuery);
  16917. token._startTimeQuery = null;
  16918. token._endTimeQuery = null;
  16919. }
  16920. else {
  16921. if (!token._timeElapsedQuery) {
  16922. return -1;
  16923. }
  16924. result = this._getTimeQueryResult(token._timeElapsedQuery);
  16925. this._deleteTimeQuery(token._timeElapsedQuery);
  16926. token._timeElapsedQuery = null;
  16927. token._timeElapsedQueryEnded = false;
  16928. this._currentNonTimestampToken = null;
  16929. }
  16930. return result;
  16931. }
  16932. return -1;
  16933. };
  16934. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  16935. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  16936. };
  16937. // Transform feedback
  16938. /**
  16939. * Creates a webGL transform feedback object
  16940. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  16941. * @returns the webGL transform feedback object
  16942. */
  16943. Engine.prototype.createTransformFeedback = function () {
  16944. return this._gl.createTransformFeedback();
  16945. };
  16946. /**
  16947. * Delete a webGL transform feedback object
  16948. * @param value defines the webGL transform feedback object to delete
  16949. */
  16950. Engine.prototype.deleteTransformFeedback = function (value) {
  16951. this._gl.deleteTransformFeedback(value);
  16952. };
  16953. /**
  16954. * Bind a webGL transform feedback object to the webgl context
  16955. * @param value defines the webGL transform feedback object to bind
  16956. */
  16957. Engine.prototype.bindTransformFeedback = function (value) {
  16958. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  16959. };
  16960. /**
  16961. * Begins a transform feedback operation
  16962. * @param usePoints defines if points or triangles must be used
  16963. */
  16964. Engine.prototype.beginTransformFeedback = function (usePoints) {
  16965. if (usePoints === void 0) { usePoints = true; }
  16966. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  16967. };
  16968. /**
  16969. * Ends a transform feedback operation
  16970. */
  16971. Engine.prototype.endTransformFeedback = function () {
  16972. this._gl.endTransformFeedback();
  16973. };
  16974. /**
  16975. * Specify the varyings to use with transform feedback
  16976. * @param program defines the associated webGL program
  16977. * @param value defines the list of strings representing the varying names
  16978. */
  16979. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  16980. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  16981. };
  16982. /**
  16983. * Bind a webGL buffer for a transform feedback operation
  16984. * @param value defines the webGL buffer to bind
  16985. */
  16986. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  16987. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  16988. };
  16989. /** @ignore */
  16990. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  16991. var _this = this;
  16992. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  16993. this._activeRequests.push(request);
  16994. request.onCompleteObservable.add(function (request) {
  16995. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  16996. });
  16997. return request;
  16998. };
  16999. /** @ignore */
  17000. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17001. var _this = this;
  17002. return new Promise(function (resolve, reject) {
  17003. _this._loadFile(url, function (data) {
  17004. resolve(data);
  17005. }, undefined, database, useArrayBuffer, function (request, exception) {
  17006. reject(exception);
  17007. });
  17008. });
  17009. };
  17010. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17011. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17012. var onload = function (data) {
  17013. loadedFiles[index] = data;
  17014. loadedFiles._internalCount++;
  17015. if (loadedFiles._internalCount === 6) {
  17016. onfinish(loadedFiles);
  17017. }
  17018. };
  17019. var onerror = function (request, exception) {
  17020. if (onErrorCallBack && request) {
  17021. onErrorCallBack(request.status + " " + request.statusText, exception);
  17022. }
  17023. };
  17024. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17025. };
  17026. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17027. if (onError === void 0) { onError = null; }
  17028. var loadedFiles = [];
  17029. loadedFiles._internalCount = 0;
  17030. for (var index = 0; index < 6; index++) {
  17031. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17032. }
  17033. };
  17034. // Statics
  17035. /**
  17036. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17037. * @returns true if the engine can be created
  17038. * @ignoreNaming
  17039. */
  17040. Engine.isSupported = function () {
  17041. try {
  17042. var tempcanvas = document.createElement("canvas");
  17043. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17044. return gl != null && !!window.WebGLRenderingContext;
  17045. }
  17046. catch (e) {
  17047. return false;
  17048. }
  17049. };
  17050. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17051. Engine.ExceptionList = [
  17052. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17053. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17054. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17055. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17056. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17057. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17058. ];
  17059. /** Gets the list of created engines */
  17060. Engine.Instances = new Array();
  17061. // Const statics
  17062. Engine._ALPHA_DISABLE = 0;
  17063. Engine._ALPHA_ADD = 1;
  17064. Engine._ALPHA_COMBINE = 2;
  17065. Engine._ALPHA_SUBTRACT = 3;
  17066. Engine._ALPHA_MULTIPLY = 4;
  17067. Engine._ALPHA_MAXIMIZED = 5;
  17068. Engine._ALPHA_ONEONE = 6;
  17069. Engine._ALPHA_PREMULTIPLIED = 7;
  17070. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17071. Engine._ALPHA_INTERPOLATE = 9;
  17072. Engine._ALPHA_SCREENMODE = 10;
  17073. Engine._DELAYLOADSTATE_NONE = 0;
  17074. Engine._DELAYLOADSTATE_LOADED = 1;
  17075. Engine._DELAYLOADSTATE_LOADING = 2;
  17076. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17077. Engine._TEXTUREFORMAT_ALPHA = 0;
  17078. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17079. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17080. Engine._TEXTUREFORMAT_RGB = 4;
  17081. Engine._TEXTUREFORMAT_RGBA = 5;
  17082. Engine._TEXTUREFORMAT_R32F = 6;
  17083. Engine._TEXTUREFORMAT_RG32F = 7;
  17084. Engine._TEXTUREFORMAT_RGB32F = 8;
  17085. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17086. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17087. Engine._TEXTURETYPE_FLOAT = 1;
  17088. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17089. // Depht or Stencil test Constants.
  17090. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17091. 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.
  17092. 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.
  17093. 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.
  17094. 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.
  17095. 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.
  17096. 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.
  17097. 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.
  17098. // Stencil Actions Constants.
  17099. Engine._KEEP = 0x1E00;
  17100. Engine._REPLACE = 0x1E01;
  17101. Engine._INCR = 0x1E02;
  17102. Engine._DECR = 0x1E03;
  17103. Engine._INVERT = 0x150A;
  17104. Engine._INCR_WRAP = 0x8507;
  17105. Engine._DECR_WRAP = 0x8508;
  17106. // Texture rescaling mode
  17107. Engine._SCALEMODE_FLOOR = 1;
  17108. Engine._SCALEMODE_NEAREST = 2;
  17109. Engine._SCALEMODE_CEILING = 3;
  17110. // Updatable statics so stick with vars here
  17111. /**
  17112. * Gets or sets the epsilon value used by collision engine
  17113. */
  17114. Engine.CollisionsEpsilon = 0.001;
  17115. /**
  17116. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17117. */
  17118. Engine.CodeRepository = "src/";
  17119. /**
  17120. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17121. */
  17122. Engine.ShadersRepository = "src/Shaders/";
  17123. return Engine;
  17124. }());
  17125. BABYLON.Engine = Engine;
  17126. })(BABYLON || (BABYLON = {}));
  17127. //# sourceMappingURL=babylon.engine.js.map
  17128. "use strict";
  17129. var BABYLON;
  17130. (function (BABYLON) {
  17131. /**
  17132. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17133. */
  17134. var Node = /** @class */ (function () {
  17135. /**
  17136. * Creates a new Node
  17137. * @param {string} name - the name and id to be given to this node
  17138. * @param {BABYLON.Scene} the scene this node will be added to
  17139. */
  17140. function Node(name, scene) {
  17141. if (scene === void 0) { scene = null; }
  17142. /**
  17143. * Gets or sets a string used to store user defined state for the node
  17144. */
  17145. this.state = "";
  17146. /**
  17147. * Gets or sets an object used to store user defined information for the node
  17148. */
  17149. this.metadata = null;
  17150. /**
  17151. * Gets or sets a boolean used to define if the node must be serialized
  17152. */
  17153. this.doNotSerialize = false;
  17154. /** @ignore */
  17155. this._isDisposed = false;
  17156. /**
  17157. * Gets a list of Animations associated with the node
  17158. */
  17159. this.animations = new Array();
  17160. this._ranges = {};
  17161. this._isEnabled = true;
  17162. this._isReady = true;
  17163. /** @ignore */
  17164. this._currentRenderId = -1;
  17165. this._parentRenderId = -1;
  17166. this._childRenderId = -1;
  17167. this._animationPropertiesOverride = null;
  17168. /**
  17169. * An event triggered when the mesh is disposed
  17170. */
  17171. this.onDisposeObservable = new BABYLON.Observable();
  17172. // Behaviors
  17173. this._behaviors = new Array();
  17174. this.name = name;
  17175. this.id = name;
  17176. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17177. this.uniqueId = this._scene.getUniqueId();
  17178. this._initCache();
  17179. }
  17180. /**
  17181. * Gets a boolean indicating if the node has been disposed
  17182. * @returns true if the node was disposed
  17183. */
  17184. Node.prototype.isDisposed = function () {
  17185. return this._isDisposed;
  17186. };
  17187. Object.defineProperty(Node.prototype, "parent", {
  17188. get: function () {
  17189. return this._parentNode;
  17190. },
  17191. /**
  17192. * Gets or sets the parent of the node
  17193. */
  17194. set: function (parent) {
  17195. if (this._parentNode === parent) {
  17196. return;
  17197. }
  17198. // Remove self from list of children of parent
  17199. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17200. var index = this._parentNode._children.indexOf(this);
  17201. if (index !== -1) {
  17202. this._parentNode._children.splice(index, 1);
  17203. }
  17204. }
  17205. // Store new parent
  17206. this._parentNode = parent;
  17207. // Add as child to new parent
  17208. if (this._parentNode) {
  17209. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17210. this._parentNode._children = new Array();
  17211. }
  17212. this._parentNode._children.push(this);
  17213. }
  17214. },
  17215. enumerable: true,
  17216. configurable: true
  17217. });
  17218. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17219. /**
  17220. * Gets or sets the animation properties override
  17221. */
  17222. get: function () {
  17223. return this._animationPropertiesOverride;
  17224. },
  17225. set: function (value) {
  17226. this._animationPropertiesOverride = value;
  17227. },
  17228. enumerable: true,
  17229. configurable: true
  17230. });
  17231. /**
  17232. * Gets a string idenfifying the name of the class
  17233. * @returns "Node" string
  17234. */
  17235. Node.prototype.getClassName = function () {
  17236. return "Node";
  17237. };
  17238. Object.defineProperty(Node.prototype, "onDispose", {
  17239. /**
  17240. * Sets a callback that will be raised when the node will be disposed
  17241. */
  17242. set: function (callback) {
  17243. if (this._onDisposeObserver) {
  17244. this.onDisposeObservable.remove(this._onDisposeObserver);
  17245. }
  17246. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17247. },
  17248. enumerable: true,
  17249. configurable: true
  17250. });
  17251. /**
  17252. * Gets the scene of the node
  17253. * @returns a {BABYLON.Scene}
  17254. */
  17255. Node.prototype.getScene = function () {
  17256. return this._scene;
  17257. };
  17258. /**
  17259. * Gets the engine of the node
  17260. * @returns a {BABYLON.Engine}
  17261. */
  17262. Node.prototype.getEngine = function () {
  17263. return this._scene.getEngine();
  17264. };
  17265. /**
  17266. * Attach a behavior to the node
  17267. * @see http://doc.babylonjs.com/features/behaviour
  17268. * @param behavior defines the behavior to attach
  17269. * @returns the current Node
  17270. */
  17271. Node.prototype.addBehavior = function (behavior) {
  17272. var _this = this;
  17273. var index = this._behaviors.indexOf(behavior);
  17274. if (index !== -1) {
  17275. return this;
  17276. }
  17277. behavior.init();
  17278. if (this._scene.isLoading) {
  17279. // We defer the attach when the scene will be loaded
  17280. var observer = this._scene.onDataLoadedObservable.add(function () {
  17281. behavior.attach(_this);
  17282. setTimeout(function () {
  17283. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17284. _this._scene.onDataLoadedObservable.remove(observer);
  17285. }, 0);
  17286. });
  17287. }
  17288. else {
  17289. behavior.attach(this);
  17290. }
  17291. this._behaviors.push(behavior);
  17292. return this;
  17293. };
  17294. /**
  17295. * Remove an attached behavior
  17296. * @see http://doc.babylonjs.com/features/behaviour
  17297. * @param behavior defines the behavior to attach
  17298. * @returns the current Node
  17299. */
  17300. Node.prototype.removeBehavior = function (behavior) {
  17301. var index = this._behaviors.indexOf(behavior);
  17302. if (index === -1) {
  17303. return this;
  17304. }
  17305. this._behaviors[index].detach();
  17306. this._behaviors.splice(index, 1);
  17307. return this;
  17308. };
  17309. Object.defineProperty(Node.prototype, "behaviors", {
  17310. /**
  17311. * Gets the list of attached behaviors
  17312. * @see http://doc.babylonjs.com/features/behaviour
  17313. */
  17314. get: function () {
  17315. return this._behaviors;
  17316. },
  17317. enumerable: true,
  17318. configurable: true
  17319. });
  17320. /**
  17321. * Gets an attached behavior by name
  17322. * @param name defines the name of the behavior to look for
  17323. * @see http://doc.babylonjs.com/features/behaviour
  17324. * @returns null if behavior was not found else the requested behavior
  17325. */
  17326. Node.prototype.getBehaviorByName = function (name) {
  17327. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17328. var behavior = _a[_i];
  17329. if (behavior.name === name) {
  17330. return behavior;
  17331. }
  17332. }
  17333. return null;
  17334. };
  17335. /**
  17336. * Returns the world matrix of the node
  17337. * @returns a matrix containing the node's world matrix
  17338. */
  17339. Node.prototype.getWorldMatrix = function () {
  17340. return BABYLON.Matrix.Identity();
  17341. };
  17342. // override it in derived class if you add new variables to the cache
  17343. // and call the parent class method
  17344. /** @ignore */
  17345. Node.prototype._initCache = function () {
  17346. this._cache = {};
  17347. this._cache.parent = undefined;
  17348. };
  17349. /** @ignore */
  17350. Node.prototype.updateCache = function (force) {
  17351. if (!force && this.isSynchronized())
  17352. return;
  17353. this._cache.parent = this.parent;
  17354. this._updateCache();
  17355. };
  17356. // override it in derived class if you add new variables to the cache
  17357. // and call the parent class method if !ignoreParentClass
  17358. /** @ignore */
  17359. Node.prototype._updateCache = function (ignoreParentClass) {
  17360. };
  17361. // override it in derived class if you add new variables to the cache
  17362. /** @ignore */
  17363. Node.prototype._isSynchronized = function () {
  17364. return true;
  17365. };
  17366. /** @ignore */
  17367. Node.prototype._markSyncedWithParent = function () {
  17368. if (this.parent) {
  17369. this._parentRenderId = this.parent._childRenderId;
  17370. }
  17371. };
  17372. /** @ignore */
  17373. Node.prototype.isSynchronizedWithParent = function () {
  17374. if (!this.parent) {
  17375. return true;
  17376. }
  17377. if (this._parentRenderId !== this.parent._childRenderId) {
  17378. return false;
  17379. }
  17380. return this.parent.isSynchronized();
  17381. };
  17382. /** @ignore */
  17383. Node.prototype.isSynchronized = function (updateCache) {
  17384. var check = this.hasNewParent();
  17385. check = check || !this.isSynchronizedWithParent();
  17386. check = check || !this._isSynchronized();
  17387. if (updateCache)
  17388. this.updateCache(true);
  17389. return !check;
  17390. };
  17391. /** @ignore */
  17392. Node.prototype.hasNewParent = function (update) {
  17393. if (this._cache.parent === this.parent)
  17394. return false;
  17395. if (update)
  17396. this._cache.parent = this.parent;
  17397. return true;
  17398. };
  17399. /**
  17400. * Is this node ready to be used/rendered
  17401. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17402. * @return true if the node is ready
  17403. */
  17404. Node.prototype.isReady = function (completeCheck) {
  17405. if (completeCheck === void 0) { completeCheck = false; }
  17406. return this._isReady;
  17407. };
  17408. /**
  17409. * Is this node enabled?
  17410. * 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
  17411. * @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
  17412. * @return whether this node (and its parent) is enabled
  17413. */
  17414. Node.prototype.isEnabled = function (checkAncestors) {
  17415. if (checkAncestors === void 0) { checkAncestors = true; }
  17416. if (checkAncestors === false) {
  17417. return this._isEnabled;
  17418. }
  17419. if (this._isEnabled === false) {
  17420. return false;
  17421. }
  17422. if (this.parent !== undefined && this.parent !== null) {
  17423. return this.parent.isEnabled(checkAncestors);
  17424. }
  17425. return true;
  17426. };
  17427. /**
  17428. * Set the enabled state of this node
  17429. * @param value defines the new enabled state
  17430. */
  17431. Node.prototype.setEnabled = function (value) {
  17432. this._isEnabled = value;
  17433. };
  17434. /**
  17435. * Is this node a descendant of the given node?
  17436. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17437. * @param ancestor defines the parent node to inspect
  17438. * @returns a boolean indicating if this node is a descendant of the given node
  17439. */
  17440. Node.prototype.isDescendantOf = function (ancestor) {
  17441. if (this.parent) {
  17442. if (this.parent === ancestor) {
  17443. return true;
  17444. }
  17445. return this.parent.isDescendantOf(ancestor);
  17446. }
  17447. return false;
  17448. };
  17449. /** @ignore */
  17450. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17451. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17452. if (!this._children) {
  17453. return;
  17454. }
  17455. for (var index = 0; index < this._children.length; index++) {
  17456. var item = this._children[index];
  17457. if (!predicate || predicate(item)) {
  17458. results.push(item);
  17459. }
  17460. if (!directDescendantsOnly) {
  17461. item._getDescendants(results, false, predicate);
  17462. }
  17463. }
  17464. };
  17465. /**
  17466. * Will return all nodes that have this node as ascendant
  17467. * @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
  17468. * @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
  17469. * @return all children nodes of all types
  17470. */
  17471. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17472. var results = new Array();
  17473. this._getDescendants(results, directDescendantsOnly, predicate);
  17474. return results;
  17475. };
  17476. /**
  17477. * Get all child-meshes of this node
  17478. * @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
  17479. * @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
  17480. * @returns an array of {BABYLON.AbstractMesh}
  17481. */
  17482. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17483. var results = [];
  17484. this._getDescendants(results, directDescendantsOnly, function (node) {
  17485. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17486. });
  17487. return results;
  17488. };
  17489. /**
  17490. * Get all child-transformNodes of this node
  17491. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  17492. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17493. * @returns an array of {BABYLON.TransformNode}
  17494. */
  17495. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17496. var results = [];
  17497. this._getDescendants(results, directDescendantsOnly, function (node) {
  17498. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17499. });
  17500. return results;
  17501. };
  17502. /**
  17503. * Get all direct children of this node
  17504. * @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
  17505. * @returns an array of {BABYLON.Node}
  17506. */
  17507. Node.prototype.getChildren = function (predicate) {
  17508. return this.getDescendants(true, predicate);
  17509. };
  17510. /** @ignore */
  17511. Node.prototype._setReady = function (state) {
  17512. if (state === this._isReady) {
  17513. return;
  17514. }
  17515. if (!state) {
  17516. this._isReady = false;
  17517. return;
  17518. }
  17519. if (this.onReady) {
  17520. this.onReady(this);
  17521. }
  17522. this._isReady = true;
  17523. };
  17524. /**
  17525. * Get an animation by name
  17526. * @param name defines the name of the animation to look for
  17527. * @returns null if not found else the requested animation
  17528. */
  17529. Node.prototype.getAnimationByName = function (name) {
  17530. for (var i = 0; i < this.animations.length; i++) {
  17531. var animation = this.animations[i];
  17532. if (animation.name === name) {
  17533. return animation;
  17534. }
  17535. }
  17536. return null;
  17537. };
  17538. /**
  17539. * Creates an animation range for this node
  17540. * @param name defines the name of the range
  17541. * @param from defines the starting key
  17542. * @param to defines the end key
  17543. */
  17544. Node.prototype.createAnimationRange = function (name, from, to) {
  17545. // check name not already in use
  17546. if (!this._ranges[name]) {
  17547. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17548. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17549. if (this.animations[i]) {
  17550. this.animations[i].createRange(name, from, to);
  17551. }
  17552. }
  17553. }
  17554. };
  17555. /**
  17556. * Delete a specific animation range
  17557. * @param name defines the name of the range to delete
  17558. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17559. */
  17560. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17561. if (deleteFrames === void 0) { deleteFrames = true; }
  17562. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17563. if (this.animations[i]) {
  17564. this.animations[i].deleteRange(name, deleteFrames);
  17565. }
  17566. }
  17567. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17568. };
  17569. /**
  17570. * Get an animation range by name
  17571. * @param name defines the name of the animation range to look for
  17572. * @returns null if not found else the requested animation range
  17573. */
  17574. Node.prototype.getAnimationRange = function (name) {
  17575. return this._ranges[name];
  17576. };
  17577. /**
  17578. * Will start the animation sequence
  17579. * @param name defines the range frames for animation sequence
  17580. * @param loop defines if the animation should loop (false by default)
  17581. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17582. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17583. * @returns the object created for this animation. If range does not exist, it will return null
  17584. */
  17585. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17586. var range = this.getAnimationRange(name);
  17587. if (!range) {
  17588. return null;
  17589. }
  17590. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17591. };
  17592. /**
  17593. * Serialize animation ranges into a JSON compatible object
  17594. * @returns serialization object
  17595. */
  17596. Node.prototype.serializeAnimationRanges = function () {
  17597. var serializationRanges = [];
  17598. for (var name in this._ranges) {
  17599. var localRange = this._ranges[name];
  17600. if (!localRange) {
  17601. continue;
  17602. }
  17603. var range = {};
  17604. range.name = name;
  17605. range.from = localRange.from;
  17606. range.to = localRange.to;
  17607. serializationRanges.push(range);
  17608. }
  17609. return serializationRanges;
  17610. };
  17611. /**
  17612. * Computes the world matrix of the node
  17613. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17614. * @returns the world matrix
  17615. */
  17616. Node.prototype.computeWorldMatrix = function (force) {
  17617. return BABYLON.Matrix.Identity();
  17618. };
  17619. /**
  17620. * Releases resources associated with this node.
  17621. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17622. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17623. */
  17624. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17625. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17626. if (!doNotRecurse) {
  17627. var nodes = this.getDescendants(true);
  17628. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17629. var node = nodes_1[_i];
  17630. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17631. }
  17632. }
  17633. else {
  17634. var transformNodes = this.getChildTransformNodes(true);
  17635. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17636. var transformNode = transformNodes_1[_a];
  17637. transformNode.parent = null;
  17638. transformNode.computeWorldMatrix(true);
  17639. }
  17640. }
  17641. this.parent = null;
  17642. // Callback
  17643. this.onDisposeObservable.notifyObservers(this);
  17644. this.onDisposeObservable.clear();
  17645. // Behaviors
  17646. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17647. var behavior = _c[_b];
  17648. behavior.detach();
  17649. }
  17650. this._behaviors = [];
  17651. this._isDisposed = true;
  17652. };
  17653. /**
  17654. * Parse animation range data from a serialization object and store them into a given node
  17655. * @param node defines where to store the animation ranges
  17656. * @param parsedNode defines the serialization object to read data from
  17657. * @param scene defines the hosting scene
  17658. */
  17659. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17660. if (parsedNode.ranges) {
  17661. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17662. var data = parsedNode.ranges[index];
  17663. node.createAnimationRange(data.name, data.from, data.to);
  17664. }
  17665. }
  17666. };
  17667. __decorate([
  17668. BABYLON.serialize()
  17669. ], Node.prototype, "name", void 0);
  17670. __decorate([
  17671. BABYLON.serialize()
  17672. ], Node.prototype, "id", void 0);
  17673. __decorate([
  17674. BABYLON.serialize()
  17675. ], Node.prototype, "uniqueId", void 0);
  17676. __decorate([
  17677. BABYLON.serialize()
  17678. ], Node.prototype, "state", void 0);
  17679. __decorate([
  17680. BABYLON.serialize()
  17681. ], Node.prototype, "metadata", void 0);
  17682. return Node;
  17683. }());
  17684. BABYLON.Node = Node;
  17685. })(BABYLON || (BABYLON = {}));
  17686. //# sourceMappingURL=babylon.node.js.map
  17687. "use strict";
  17688. var BABYLON;
  17689. (function (BABYLON) {
  17690. var BoundingSphere = /** @class */ (function () {
  17691. function BoundingSphere(minimum, maximum) {
  17692. this.minimum = minimum;
  17693. this.maximum = maximum;
  17694. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17695. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  17696. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  17697. this.radius = distance * 0.5;
  17698. this.centerWorld = BABYLON.Vector3.Zero();
  17699. this._update(BABYLON.Matrix.Identity());
  17700. }
  17701. // Methods
  17702. BoundingSphere.prototype._update = function (world) {
  17703. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17704. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17705. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17706. };
  17707. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17708. for (var i = 0; i < 6; i++) {
  17709. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17710. return false;
  17711. }
  17712. return true;
  17713. };
  17714. BoundingSphere.prototype.intersectsPoint = function (point) {
  17715. var x = this.centerWorld.x - point.x;
  17716. var y = this.centerWorld.y - point.y;
  17717. var z = this.centerWorld.z - point.z;
  17718. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17719. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17720. return false;
  17721. return true;
  17722. };
  17723. // Statics
  17724. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17725. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17726. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17727. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17728. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17729. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17730. return false;
  17731. return true;
  17732. };
  17733. return BoundingSphere;
  17734. }());
  17735. BABYLON.BoundingSphere = BoundingSphere;
  17736. })(BABYLON || (BABYLON = {}));
  17737. //# sourceMappingURL=babylon.boundingSphere.js.map
  17738. "use strict";
  17739. var BABYLON;
  17740. (function (BABYLON) {
  17741. var BoundingBox = /** @class */ (function () {
  17742. function BoundingBox(minimum, maximum) {
  17743. this.minimum = minimum;
  17744. this.maximum = maximum;
  17745. this.vectors = new Array();
  17746. this.vectorsWorld = new Array();
  17747. // Bounding vectors
  17748. this.vectors.push(this.minimum.clone());
  17749. this.vectors.push(this.maximum.clone());
  17750. this.vectors.push(this.minimum.clone());
  17751. this.vectors[2].x = this.maximum.x;
  17752. this.vectors.push(this.minimum.clone());
  17753. this.vectors[3].y = this.maximum.y;
  17754. this.vectors.push(this.minimum.clone());
  17755. this.vectors[4].z = this.maximum.z;
  17756. this.vectors.push(this.maximum.clone());
  17757. this.vectors[5].z = this.minimum.z;
  17758. this.vectors.push(this.maximum.clone());
  17759. this.vectors[6].x = this.minimum.x;
  17760. this.vectors.push(this.maximum.clone());
  17761. this.vectors[7].y = this.minimum.y;
  17762. // OBB
  17763. this.center = this.maximum.add(this.minimum).scale(0.5);
  17764. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17765. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17766. // World
  17767. for (var index = 0; index < this.vectors.length; index++) {
  17768. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17769. }
  17770. this.minimumWorld = BABYLON.Vector3.Zero();
  17771. this.maximumWorld = BABYLON.Vector3.Zero();
  17772. this.centerWorld = BABYLON.Vector3.Zero();
  17773. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17774. this._update(BABYLON.Matrix.Identity());
  17775. }
  17776. // Methods
  17777. BoundingBox.prototype.getWorldMatrix = function () {
  17778. return this._worldMatrix;
  17779. };
  17780. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17781. this._worldMatrix.copyFrom(matrix);
  17782. return this;
  17783. };
  17784. BoundingBox.prototype._update = function (world) {
  17785. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  17786. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  17787. for (var index = 0; index < this.vectors.length; index++) {
  17788. var v = this.vectorsWorld[index];
  17789. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  17790. if (v.x < this.minimumWorld.x)
  17791. this.minimumWorld.x = v.x;
  17792. if (v.y < this.minimumWorld.y)
  17793. this.minimumWorld.y = v.y;
  17794. if (v.z < this.minimumWorld.z)
  17795. this.minimumWorld.z = v.z;
  17796. if (v.x > this.maximumWorld.x)
  17797. this.maximumWorld.x = v.x;
  17798. if (v.y > this.maximumWorld.y)
  17799. this.maximumWorld.y = v.y;
  17800. if (v.z > this.maximumWorld.z)
  17801. this.maximumWorld.z = v.z;
  17802. }
  17803. // Extend
  17804. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  17805. this.extendSizeWorld.scaleInPlace(0.5);
  17806. // OBB
  17807. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  17808. this.centerWorld.scaleInPlace(0.5);
  17809. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  17810. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  17811. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  17812. this._worldMatrix = world;
  17813. };
  17814. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  17815. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  17816. };
  17817. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17818. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  17819. };
  17820. BoundingBox.prototype.intersectsPoint = function (point) {
  17821. var delta = -BABYLON.Epsilon;
  17822. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  17823. return false;
  17824. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  17825. return false;
  17826. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  17827. return false;
  17828. return true;
  17829. };
  17830. BoundingBox.prototype.intersectsSphere = function (sphere) {
  17831. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  17832. };
  17833. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  17834. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  17835. return false;
  17836. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  17837. return false;
  17838. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  17839. return false;
  17840. return true;
  17841. };
  17842. // Statics
  17843. BoundingBox.Intersects = function (box0, box1) {
  17844. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  17845. return false;
  17846. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  17847. return false;
  17848. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  17849. return false;
  17850. return true;
  17851. };
  17852. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  17853. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  17854. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  17855. return (num <= (sphereRadius * sphereRadius));
  17856. };
  17857. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  17858. for (var p = 0; p < 6; p++) {
  17859. for (var i = 0; i < 8; i++) {
  17860. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17861. return false;
  17862. }
  17863. }
  17864. }
  17865. return true;
  17866. };
  17867. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  17868. for (var p = 0; p < 6; p++) {
  17869. var inCount = 8;
  17870. for (var i = 0; i < 8; i++) {
  17871. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17872. --inCount;
  17873. }
  17874. else {
  17875. break;
  17876. }
  17877. }
  17878. if (inCount === 0)
  17879. return false;
  17880. }
  17881. return true;
  17882. };
  17883. return BoundingBox;
  17884. }());
  17885. BABYLON.BoundingBox = BoundingBox;
  17886. })(BABYLON || (BABYLON = {}));
  17887. //# sourceMappingURL=babylon.boundingBox.js.map
  17888. "use strict";
  17889. var BABYLON;
  17890. (function (BABYLON) {
  17891. var computeBoxExtents = function (axis, box) {
  17892. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  17893. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  17894. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  17895. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  17896. var r = r0 + r1 + r2;
  17897. return {
  17898. min: p - r,
  17899. max: p + r
  17900. };
  17901. };
  17902. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  17903. var axisOverlap = function (axis, box0, box1) {
  17904. var result0 = computeBoxExtents(axis, box0);
  17905. var result1 = computeBoxExtents(axis, box1);
  17906. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  17907. };
  17908. var BoundingInfo = /** @class */ (function () {
  17909. function BoundingInfo(minimum, maximum) {
  17910. this.minimum = minimum;
  17911. this.maximum = maximum;
  17912. this._isLocked = false;
  17913. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  17914. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  17915. }
  17916. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  17917. get: function () {
  17918. return this._isLocked;
  17919. },
  17920. set: function (value) {
  17921. this._isLocked = value;
  17922. },
  17923. enumerable: true,
  17924. configurable: true
  17925. });
  17926. // Methods
  17927. BoundingInfo.prototype.update = function (world) {
  17928. if (this._isLocked) {
  17929. return;
  17930. }
  17931. this.boundingBox._update(world);
  17932. this.boundingSphere._update(world);
  17933. };
  17934. /**
  17935. * Recreate the bounding info to be centered around a specific point given a specific extend.
  17936. * @param center New center of the bounding info
  17937. * @param extend New extend of the bounding info
  17938. */
  17939. BoundingInfo.prototype.centerOn = function (center, extend) {
  17940. this.minimum = center.subtract(extend);
  17941. this.maximum = center.add(extend);
  17942. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  17943. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  17944. return this;
  17945. };
  17946. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  17947. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  17948. return false;
  17949. return this.boundingBox.isInFrustum(frustumPlanes);
  17950. };
  17951. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  17952. /**
  17953. * Gets the world distance between the min and max points of the bounding box
  17954. */
  17955. get: function () {
  17956. var boundingBox = this.boundingBox;
  17957. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  17958. return size.length();
  17959. },
  17960. enumerable: true,
  17961. configurable: true
  17962. });
  17963. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17964. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  17965. };
  17966. BoundingInfo.prototype._checkCollision = function (collider) {
  17967. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  17968. };
  17969. BoundingInfo.prototype.intersectsPoint = function (point) {
  17970. if (!this.boundingSphere.centerWorld) {
  17971. return false;
  17972. }
  17973. if (!this.boundingSphere.intersectsPoint(point)) {
  17974. return false;
  17975. }
  17976. if (!this.boundingBox.intersectsPoint(point)) {
  17977. return false;
  17978. }
  17979. return true;
  17980. };
  17981. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  17982. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  17983. return false;
  17984. }
  17985. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  17986. return false;
  17987. }
  17988. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  17989. return false;
  17990. }
  17991. if (!precise) {
  17992. return true;
  17993. }
  17994. var box0 = this.boundingBox;
  17995. var box1 = boundingInfo.boundingBox;
  17996. if (!axisOverlap(box0.directions[0], box0, box1))
  17997. return false;
  17998. if (!axisOverlap(box0.directions[1], box0, box1))
  17999. return false;
  18000. if (!axisOverlap(box0.directions[2], box0, box1))
  18001. return false;
  18002. if (!axisOverlap(box1.directions[0], box0, box1))
  18003. return false;
  18004. if (!axisOverlap(box1.directions[1], box0, box1))
  18005. return false;
  18006. if (!axisOverlap(box1.directions[2], box0, box1))
  18007. return false;
  18008. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18009. return false;
  18010. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18011. return false;
  18012. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18013. return false;
  18014. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18015. return false;
  18016. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18017. return false;
  18018. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18019. return false;
  18020. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18021. return false;
  18022. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18023. return false;
  18024. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18025. return false;
  18026. return true;
  18027. };
  18028. return BoundingInfo;
  18029. }());
  18030. BABYLON.BoundingInfo = BoundingInfo;
  18031. })(BABYLON || (BABYLON = {}));
  18032. //# sourceMappingURL=babylon.boundingInfo.js.map
  18033. "use strict";
  18034. var BABYLON;
  18035. (function (BABYLON) {
  18036. var TransformNode = /** @class */ (function (_super) {
  18037. __extends(TransformNode, _super);
  18038. function TransformNode(name, scene, isPure) {
  18039. if (scene === void 0) { scene = null; }
  18040. if (isPure === void 0) { isPure = true; }
  18041. var _this = _super.call(this, name, scene) || this;
  18042. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18043. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18044. _this._up = new BABYLON.Vector3(0, 1, 0);
  18045. _this._right = new BABYLON.Vector3(1, 0, 0);
  18046. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18047. // Properties
  18048. _this._rotation = BABYLON.Vector3.Zero();
  18049. _this._scaling = BABYLON.Vector3.One();
  18050. _this._isDirty = false;
  18051. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18052. _this.scalingDeterminant = 1;
  18053. _this.infiniteDistance = false;
  18054. _this.position = BABYLON.Vector3.Zero();
  18055. _this._localWorld = BABYLON.Matrix.Zero();
  18056. _this._worldMatrix = BABYLON.Matrix.Zero();
  18057. _this._worldMatrixDeterminant = 0;
  18058. _this._absolutePosition = BABYLON.Vector3.Zero();
  18059. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18060. _this._postMultiplyPivotMatrix = false;
  18061. _this._isWorldMatrixFrozen = false;
  18062. /**
  18063. * An event triggered after the world matrix is updated
  18064. */
  18065. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18066. _this._nonUniformScaling = false;
  18067. if (isPure) {
  18068. _this.getScene().addTransformNode(_this);
  18069. }
  18070. return _this;
  18071. }
  18072. /**
  18073. * Gets a string idenfifying the name of the class
  18074. * @returns "TransformNode" string
  18075. */
  18076. TransformNode.prototype.getClassName = function () {
  18077. return "TransformNode";
  18078. };
  18079. Object.defineProperty(TransformNode.prototype, "rotation", {
  18080. /**
  18081. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18082. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18083. * Default : (0.0, 0.0, 0.0)
  18084. */
  18085. get: function () {
  18086. return this._rotation;
  18087. },
  18088. set: function (newRotation) {
  18089. this._rotation = newRotation;
  18090. },
  18091. enumerable: true,
  18092. configurable: true
  18093. });
  18094. Object.defineProperty(TransformNode.prototype, "scaling", {
  18095. /**
  18096. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18097. * Default : (1.0, 1.0, 1.0)
  18098. */
  18099. get: function () {
  18100. return this._scaling;
  18101. },
  18102. /**
  18103. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18104. * Default : (1.0, 1.0, 1.0)
  18105. */
  18106. set: function (newScaling) {
  18107. this._scaling = newScaling;
  18108. },
  18109. enumerable: true,
  18110. configurable: true
  18111. });
  18112. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18113. /**
  18114. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18115. * It's null by default.
  18116. * 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)
  18117. */
  18118. get: function () {
  18119. return this._rotationQuaternion;
  18120. },
  18121. set: function (quaternion) {
  18122. this._rotationQuaternion = quaternion;
  18123. //reset the rotation vector.
  18124. if (quaternion && this.rotation.length()) {
  18125. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18126. }
  18127. },
  18128. enumerable: true,
  18129. configurable: true
  18130. });
  18131. Object.defineProperty(TransformNode.prototype, "forward", {
  18132. /**
  18133. * The forward direction of that transform in world space.
  18134. */
  18135. get: function () {
  18136. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18137. },
  18138. enumerable: true,
  18139. configurable: true
  18140. });
  18141. Object.defineProperty(TransformNode.prototype, "up", {
  18142. /**
  18143. * The up direction of that transform in world space.
  18144. */
  18145. get: function () {
  18146. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18147. },
  18148. enumerable: true,
  18149. configurable: true
  18150. });
  18151. Object.defineProperty(TransformNode.prototype, "right", {
  18152. /**
  18153. * The right direction of that transform in world space.
  18154. */
  18155. get: function () {
  18156. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18157. },
  18158. enumerable: true,
  18159. configurable: true
  18160. });
  18161. /**
  18162. * Returns the latest update of the World matrix
  18163. * Returns a Matrix.
  18164. */
  18165. TransformNode.prototype.getWorldMatrix = function () {
  18166. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18167. this.computeWorldMatrix();
  18168. }
  18169. return this._worldMatrix;
  18170. };
  18171. /**
  18172. * Returns the latest update of the World matrix determinant.
  18173. */
  18174. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18175. return this._worldMatrixDeterminant;
  18176. };
  18177. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18178. /**
  18179. * Returns directly the latest state of the mesh World matrix.
  18180. * A Matrix is returned.
  18181. */
  18182. get: function () {
  18183. return this._worldMatrix;
  18184. },
  18185. enumerable: true,
  18186. configurable: true
  18187. });
  18188. /**
  18189. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18190. * Returns the TransformNode.
  18191. */
  18192. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18193. this._poseMatrix.copyFrom(matrix);
  18194. return this;
  18195. };
  18196. /**
  18197. * Returns the mesh Pose matrix.
  18198. * Returned object : Matrix
  18199. */
  18200. TransformNode.prototype.getPoseMatrix = function () {
  18201. return this._poseMatrix;
  18202. };
  18203. TransformNode.prototype._isSynchronized = function () {
  18204. if (this._isDirty) {
  18205. return false;
  18206. }
  18207. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18208. return false;
  18209. if (this._cache.pivotMatrixUpdated) {
  18210. return false;
  18211. }
  18212. if (this.infiniteDistance) {
  18213. return false;
  18214. }
  18215. if (!this._cache.position.equals(this.position))
  18216. return false;
  18217. if (this.rotationQuaternion) {
  18218. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18219. return false;
  18220. }
  18221. if (!this._cache.rotation.equals(this.rotation))
  18222. return false;
  18223. if (!this._cache.scaling.equals(this.scaling))
  18224. return false;
  18225. return true;
  18226. };
  18227. TransformNode.prototype._initCache = function () {
  18228. _super.prototype._initCache.call(this);
  18229. this._cache.localMatrixUpdated = false;
  18230. this._cache.position = BABYLON.Vector3.Zero();
  18231. this._cache.scaling = BABYLON.Vector3.Zero();
  18232. this._cache.rotation = BABYLON.Vector3.Zero();
  18233. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18234. this._cache.billboardMode = -1;
  18235. };
  18236. TransformNode.prototype.markAsDirty = function (property) {
  18237. if (property === "rotation") {
  18238. this.rotationQuaternion = null;
  18239. }
  18240. this._currentRenderId = Number.MAX_VALUE;
  18241. this._isDirty = true;
  18242. return this;
  18243. };
  18244. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18245. /**
  18246. * Returns the current mesh absolute position.
  18247. * Retuns a Vector3.
  18248. */
  18249. get: function () {
  18250. return this._absolutePosition;
  18251. },
  18252. enumerable: true,
  18253. configurable: true
  18254. });
  18255. /**
  18256. * Sets a new matrix to apply before all other transformation
  18257. * @param matrix defines the transform matrix
  18258. * @returns the current TransformNode
  18259. */
  18260. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18261. return this.setPivotMatrix(matrix, false);
  18262. };
  18263. /**
  18264. * Sets a new pivot matrix to the current node
  18265. * @param matrix defines the new pivot matrix to use
  18266. * @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
  18267. * @returns the current TransformNode
  18268. */
  18269. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18270. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18271. this._pivotMatrix = matrix.clone();
  18272. this._cache.pivotMatrixUpdated = true;
  18273. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18274. if (this._postMultiplyPivotMatrix) {
  18275. if (!this._pivotMatrixInverse) {
  18276. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18277. }
  18278. else {
  18279. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18280. }
  18281. }
  18282. return this;
  18283. };
  18284. /**
  18285. * Returns the mesh pivot matrix.
  18286. * Default : Identity.
  18287. * A Matrix is returned.
  18288. */
  18289. TransformNode.prototype.getPivotMatrix = function () {
  18290. return this._pivotMatrix;
  18291. };
  18292. /**
  18293. * Prevents the World matrix to be computed any longer.
  18294. * Returns the TransformNode.
  18295. */
  18296. TransformNode.prototype.freezeWorldMatrix = function () {
  18297. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18298. this.computeWorldMatrix(true);
  18299. this._isWorldMatrixFrozen = true;
  18300. return this;
  18301. };
  18302. /**
  18303. * Allows back the World matrix computation.
  18304. * Returns the TransformNode.
  18305. */
  18306. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18307. this._isWorldMatrixFrozen = false;
  18308. this.computeWorldMatrix(true);
  18309. return this;
  18310. };
  18311. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18312. /**
  18313. * True if the World matrix has been frozen.
  18314. * Returns a boolean.
  18315. */
  18316. get: function () {
  18317. return this._isWorldMatrixFrozen;
  18318. },
  18319. enumerable: true,
  18320. configurable: true
  18321. });
  18322. /**
  18323. * Retuns the mesh absolute position in the World.
  18324. * Returns a Vector3.
  18325. */
  18326. TransformNode.prototype.getAbsolutePosition = function () {
  18327. this.computeWorldMatrix();
  18328. return this._absolutePosition;
  18329. };
  18330. /**
  18331. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18332. * Returns the TransformNode.
  18333. */
  18334. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18335. if (!absolutePosition) {
  18336. return this;
  18337. }
  18338. var absolutePositionX;
  18339. var absolutePositionY;
  18340. var absolutePositionZ;
  18341. if (absolutePosition.x === undefined) {
  18342. if (arguments.length < 3) {
  18343. return this;
  18344. }
  18345. absolutePositionX = arguments[0];
  18346. absolutePositionY = arguments[1];
  18347. absolutePositionZ = arguments[2];
  18348. }
  18349. else {
  18350. absolutePositionX = absolutePosition.x;
  18351. absolutePositionY = absolutePosition.y;
  18352. absolutePositionZ = absolutePosition.z;
  18353. }
  18354. if (this.parent) {
  18355. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18356. invertParentWorldMatrix.invert();
  18357. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18358. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18359. }
  18360. else {
  18361. this.position.x = absolutePositionX;
  18362. this.position.y = absolutePositionY;
  18363. this.position.z = absolutePositionZ;
  18364. }
  18365. return this;
  18366. };
  18367. /**
  18368. * Sets the mesh position in its local space.
  18369. * Returns the TransformNode.
  18370. */
  18371. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18372. this.computeWorldMatrix();
  18373. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18374. return this;
  18375. };
  18376. /**
  18377. * Returns the mesh position in the local space from the current World matrix values.
  18378. * Returns a new Vector3.
  18379. */
  18380. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18381. this.computeWorldMatrix();
  18382. var invLocalWorldMatrix = this._localWorld.clone();
  18383. invLocalWorldMatrix.invert();
  18384. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18385. };
  18386. /**
  18387. * Translates the mesh along the passed Vector3 in its local space.
  18388. * Returns the TransformNode.
  18389. */
  18390. TransformNode.prototype.locallyTranslate = function (vector3) {
  18391. this.computeWorldMatrix(true);
  18392. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18393. return this;
  18394. };
  18395. /**
  18396. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18397. * @param targetPoint the position (must be in same space as current mesh) to look at
  18398. * @param yawCor optional yaw (y-axis) correction in radians
  18399. * @param pitchCor optional pitch (x-axis) correction in radians
  18400. * @param rollCor optional roll (z-axis) correction in radians
  18401. * @param space the choosen space of the target
  18402. * @returns the TransformNode.
  18403. */
  18404. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18405. if (yawCor === void 0) { yawCor = 0; }
  18406. if (pitchCor === void 0) { pitchCor = 0; }
  18407. if (rollCor === void 0) { rollCor = 0; }
  18408. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18409. var dv = TransformNode._lookAtVectorCache;
  18410. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18411. targetPoint.subtractToRef(pos, dv);
  18412. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18413. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18414. var pitch = Math.atan2(dv.y, len);
  18415. if (this.rotationQuaternion) {
  18416. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18417. }
  18418. else {
  18419. this.rotation.x = pitch + pitchCor;
  18420. this.rotation.y = yaw + yawCor;
  18421. this.rotation.z = rollCor;
  18422. }
  18423. return this;
  18424. };
  18425. /**
  18426. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18427. * This Vector3 is expressed in the World space.
  18428. */
  18429. TransformNode.prototype.getDirection = function (localAxis) {
  18430. var result = BABYLON.Vector3.Zero();
  18431. this.getDirectionToRef(localAxis, result);
  18432. return result;
  18433. };
  18434. /**
  18435. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18436. * localAxis is expressed in the mesh local space.
  18437. * result is computed in the Wordl space from the mesh World matrix.
  18438. * Returns the TransformNode.
  18439. */
  18440. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18441. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18442. return this;
  18443. };
  18444. /**
  18445. * Sets a new pivot point to the current node
  18446. * @param point defines the new pivot point to use
  18447. * @param space defines if the point is in world or local space (local by default)
  18448. * @returns the current TransformNode
  18449. */
  18450. TransformNode.prototype.setPivotPoint = function (point, space) {
  18451. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18452. if (this.getScene().getRenderId() == 0) {
  18453. this.computeWorldMatrix(true);
  18454. }
  18455. var wm = this.getWorldMatrix();
  18456. if (space == BABYLON.Space.WORLD) {
  18457. var tmat = BABYLON.Tmp.Matrix[0];
  18458. wm.invertToRef(tmat);
  18459. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18460. }
  18461. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18462. };
  18463. /**
  18464. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18465. */
  18466. TransformNode.prototype.getPivotPoint = function () {
  18467. var point = BABYLON.Vector3.Zero();
  18468. this.getPivotPointToRef(point);
  18469. return point;
  18470. };
  18471. /**
  18472. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18473. * Returns the TransformNode.
  18474. */
  18475. TransformNode.prototype.getPivotPointToRef = function (result) {
  18476. result.x = -this._pivotMatrix.m[12];
  18477. result.y = -this._pivotMatrix.m[13];
  18478. result.z = -this._pivotMatrix.m[14];
  18479. return this;
  18480. };
  18481. /**
  18482. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18483. */
  18484. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18485. var point = BABYLON.Vector3.Zero();
  18486. this.getAbsolutePivotPointToRef(point);
  18487. return point;
  18488. };
  18489. /**
  18490. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18491. * Returns the TransformNode.
  18492. */
  18493. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18494. result.x = this._pivotMatrix.m[12];
  18495. result.y = this._pivotMatrix.m[13];
  18496. result.z = this._pivotMatrix.m[14];
  18497. this.getPivotPointToRef(result);
  18498. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18499. return this;
  18500. };
  18501. /**
  18502. * Defines the passed node as the parent of the current node.
  18503. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18504. * Returns the TransformNode.
  18505. */
  18506. TransformNode.prototype.setParent = function (node) {
  18507. if (node === null) {
  18508. var rotation = BABYLON.Tmp.Quaternion[0];
  18509. var position = BABYLON.Tmp.Vector3[0];
  18510. var scale = BABYLON.Tmp.Vector3[1];
  18511. if (this.parent && this.parent.computeWorldMatrix) {
  18512. this.parent.computeWorldMatrix(true);
  18513. }
  18514. this.computeWorldMatrix(true);
  18515. this.getWorldMatrix().decompose(scale, rotation, position);
  18516. if (this.rotationQuaternion) {
  18517. this.rotationQuaternion.copyFrom(rotation);
  18518. }
  18519. else {
  18520. rotation.toEulerAnglesToRef(this.rotation);
  18521. }
  18522. this.scaling.x = scale.x;
  18523. this.scaling.y = scale.y;
  18524. this.scaling.z = scale.z;
  18525. this.position.x = position.x;
  18526. this.position.y = position.y;
  18527. this.position.z = position.z;
  18528. }
  18529. else {
  18530. var rotation = BABYLON.Tmp.Quaternion[0];
  18531. var position = BABYLON.Tmp.Vector3[0];
  18532. var scale = BABYLON.Tmp.Vector3[1];
  18533. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18534. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18535. this.computeWorldMatrix(true);
  18536. node.computeWorldMatrix(true);
  18537. node.getWorldMatrix().invertToRef(invParentMatrix);
  18538. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18539. diffMatrix.decompose(scale, rotation, position);
  18540. if (this.rotationQuaternion) {
  18541. this.rotationQuaternion.copyFrom(rotation);
  18542. }
  18543. else {
  18544. rotation.toEulerAnglesToRef(this.rotation);
  18545. }
  18546. this.position.x = position.x;
  18547. this.position.y = position.y;
  18548. this.position.z = position.z;
  18549. this.scaling.x = scale.x;
  18550. this.scaling.y = scale.y;
  18551. this.scaling.z = scale.z;
  18552. }
  18553. this.parent = node;
  18554. return this;
  18555. };
  18556. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18557. get: function () {
  18558. return this._nonUniformScaling;
  18559. },
  18560. enumerable: true,
  18561. configurable: true
  18562. });
  18563. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18564. if (this._nonUniformScaling === value) {
  18565. return false;
  18566. }
  18567. this._nonUniformScaling = true;
  18568. return true;
  18569. };
  18570. /**
  18571. * Attach the current TransformNode to another TransformNode associated with a bone
  18572. * @param bone Bone affecting the TransformNode
  18573. * @param affectedTransformNode TransformNode associated with the bone
  18574. */
  18575. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18576. this._transformToBoneReferal = affectedTransformNode;
  18577. this.parent = bone;
  18578. if (bone.getWorldMatrix().determinant() < 0) {
  18579. this.scalingDeterminant *= -1;
  18580. }
  18581. return this;
  18582. };
  18583. TransformNode.prototype.detachFromBone = function () {
  18584. if (!this.parent) {
  18585. return this;
  18586. }
  18587. if (this.parent.getWorldMatrix().determinant() < 0) {
  18588. this.scalingDeterminant *= -1;
  18589. }
  18590. this._transformToBoneReferal = null;
  18591. this.parent = null;
  18592. return this;
  18593. };
  18594. /**
  18595. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18596. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18597. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18598. * The passed axis is also normalized.
  18599. * Returns the TransformNode.
  18600. */
  18601. TransformNode.prototype.rotate = function (axis, amount, space) {
  18602. axis.normalize();
  18603. if (!this.rotationQuaternion) {
  18604. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18605. this.rotation = BABYLON.Vector3.Zero();
  18606. }
  18607. var rotationQuaternion;
  18608. if (!space || space === BABYLON.Space.LOCAL) {
  18609. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18610. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18611. }
  18612. else {
  18613. if (this.parent) {
  18614. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18615. invertParentWorldMatrix.invert();
  18616. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18617. }
  18618. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18619. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18620. }
  18621. return this;
  18622. };
  18623. /**
  18624. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18625. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18626. * The passed axis is also normalized.
  18627. * Returns the TransformNode.
  18628. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18629. */
  18630. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18631. axis.normalize();
  18632. if (!this.rotationQuaternion) {
  18633. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18634. this.rotation.copyFromFloats(0, 0, 0);
  18635. }
  18636. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18637. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18638. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18639. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18640. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18641. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18642. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18643. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18644. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18645. return this;
  18646. };
  18647. /**
  18648. * Translates the mesh along the axis vector for the passed distance in the given space.
  18649. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18650. * Returns the TransformNode.
  18651. */
  18652. TransformNode.prototype.translate = function (axis, distance, space) {
  18653. var displacementVector = axis.scale(distance);
  18654. if (!space || space === BABYLON.Space.LOCAL) {
  18655. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18656. this.setPositionWithLocalVector(tempV3);
  18657. }
  18658. else {
  18659. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18660. }
  18661. return this;
  18662. };
  18663. /**
  18664. * Adds a rotation step to the mesh current rotation.
  18665. * x, y, z are Euler angles expressed in radians.
  18666. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18667. * This means this rotation is made in the mesh local space only.
  18668. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18669. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18670. * ```javascript
  18671. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18672. * ```
  18673. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18674. * 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.
  18675. * Returns the TransformNode.
  18676. */
  18677. TransformNode.prototype.addRotation = function (x, y, z) {
  18678. var rotationQuaternion;
  18679. if (this.rotationQuaternion) {
  18680. rotationQuaternion = this.rotationQuaternion;
  18681. }
  18682. else {
  18683. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18684. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18685. }
  18686. var accumulation = BABYLON.Tmp.Quaternion[0];
  18687. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18688. rotationQuaternion.multiplyInPlace(accumulation);
  18689. if (!this.rotationQuaternion) {
  18690. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18691. }
  18692. return this;
  18693. };
  18694. /**
  18695. * Computes the mesh World matrix and returns it.
  18696. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18697. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18698. * If the parameter `force`is set to `true`, the actual computation is done.
  18699. * Returns the mesh World Matrix.
  18700. */
  18701. TransformNode.prototype.computeWorldMatrix = function (force) {
  18702. if (this._isWorldMatrixFrozen) {
  18703. return this._worldMatrix;
  18704. }
  18705. if (!force && this.isSynchronized(true)) {
  18706. this._currentRenderId = this.getScene().getRenderId();
  18707. return this._worldMatrix;
  18708. }
  18709. this._cache.position.copyFrom(this.position);
  18710. this._cache.scaling.copyFrom(this.scaling);
  18711. this._cache.pivotMatrixUpdated = false;
  18712. this._cache.billboardMode = this.billboardMode;
  18713. this._currentRenderId = this.getScene().getRenderId();
  18714. this._childRenderId = this.getScene().getRenderId();
  18715. this._isDirty = false;
  18716. // Scaling
  18717. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18718. // Rotation
  18719. //rotate, if quaternion is set and rotation was used
  18720. if (this.rotationQuaternion) {
  18721. var len = this.rotation.length();
  18722. if (len) {
  18723. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18724. this.rotation.copyFromFloats(0, 0, 0);
  18725. }
  18726. }
  18727. if (this.rotationQuaternion) {
  18728. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18729. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18730. }
  18731. else {
  18732. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18733. this._cache.rotation.copyFrom(this.rotation);
  18734. }
  18735. // Translation
  18736. var camera = this.getScene().activeCamera;
  18737. if (this.infiniteDistance && !this.parent && camera) {
  18738. var cameraWorldMatrix = camera.getWorldMatrix();
  18739. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18740. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18741. }
  18742. else {
  18743. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18744. }
  18745. // Composing transformations
  18746. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18747. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18748. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18749. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18750. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18751. // Need to decompose each rotation here
  18752. var currentPosition = BABYLON.Tmp.Vector3[3];
  18753. if (this.parent && this.parent.getWorldMatrix) {
  18754. if (this._transformToBoneReferal) {
  18755. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18756. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18757. }
  18758. else {
  18759. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18760. }
  18761. }
  18762. else {
  18763. currentPosition.copyFrom(this.position);
  18764. }
  18765. currentPosition.subtractInPlace(camera.globalPosition);
  18766. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18767. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18768. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18769. }
  18770. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18771. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  18772. }
  18773. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  18774. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  18775. }
  18776. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  18777. }
  18778. else {
  18779. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  18780. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  18781. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  18782. }
  18783. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  18784. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18785. }
  18786. // Local world
  18787. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  18788. // Parent
  18789. if (this.parent && this.parent.getWorldMatrix) {
  18790. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  18791. if (this._transformToBoneReferal) {
  18792. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18793. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  18794. }
  18795. else {
  18796. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  18797. }
  18798. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  18799. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  18800. this._worldMatrix.copyFrom(this._localWorld);
  18801. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  18802. }
  18803. else {
  18804. if (this._transformToBoneReferal) {
  18805. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18806. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  18807. }
  18808. else {
  18809. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  18810. }
  18811. }
  18812. this._markSyncedWithParent();
  18813. }
  18814. else {
  18815. this._worldMatrix.copyFrom(this._localWorld);
  18816. }
  18817. // Post multiply inverse of pivotMatrix
  18818. if (this._postMultiplyPivotMatrix) {
  18819. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  18820. }
  18821. // Normal matrix
  18822. if (this.scaling.isNonUniform) {
  18823. this._updateNonUniformScalingState(true);
  18824. }
  18825. else if (this.parent && this.parent._nonUniformScaling) {
  18826. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  18827. }
  18828. else {
  18829. this._updateNonUniformScalingState(false);
  18830. }
  18831. this._afterComputeWorldMatrix();
  18832. // Absolute position
  18833. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  18834. // Callbacks
  18835. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  18836. if (!this._poseMatrix) {
  18837. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  18838. }
  18839. // Cache the determinant
  18840. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  18841. return this._worldMatrix;
  18842. };
  18843. TransformNode.prototype._afterComputeWorldMatrix = function () {
  18844. };
  18845. /**
  18846. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  18847. * @param func: callback function to add
  18848. *
  18849. * Returns the TransformNode.
  18850. */
  18851. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  18852. this.onAfterWorldMatrixUpdateObservable.add(func);
  18853. return this;
  18854. };
  18855. /**
  18856. * Removes a registered callback function.
  18857. * Returns the TransformNode.
  18858. */
  18859. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  18860. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  18861. return this;
  18862. };
  18863. /**
  18864. * Clone the current transform node
  18865. * Returns the new transform node
  18866. * @param name Name of the new clone
  18867. * @param newParent New parent for the clone
  18868. * @param doNotCloneChildren Do not clone children hierarchy
  18869. */
  18870. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18871. var _this = this;
  18872. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  18873. result.name = name;
  18874. result.id = name;
  18875. if (newParent) {
  18876. result.parent = newParent;
  18877. }
  18878. if (!doNotCloneChildren) {
  18879. // Children
  18880. var directDescendants = this.getDescendants(true);
  18881. for (var index = 0; index < directDescendants.length; index++) {
  18882. var child = directDescendants[index];
  18883. if (child.clone) {
  18884. child.clone(name + "." + child.name, result);
  18885. }
  18886. }
  18887. }
  18888. return result;
  18889. };
  18890. TransformNode.prototype.serialize = function (currentSerializationObject) {
  18891. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  18892. serializationObject.type = this.getClassName();
  18893. // Parent
  18894. if (this.parent) {
  18895. serializationObject.parentId = this.parent.id;
  18896. }
  18897. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  18898. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18899. }
  18900. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  18901. serializationObject.isEnabled = this.isEnabled();
  18902. // Parent
  18903. if (this.parent) {
  18904. serializationObject.parentId = this.parent.id;
  18905. }
  18906. return serializationObject;
  18907. };
  18908. // Statics
  18909. /**
  18910. * Returns a new TransformNode object parsed from the source provided.
  18911. * The parameter `parsedMesh` is the source.
  18912. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  18913. */
  18914. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  18915. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  18916. if (BABYLON.Tags) {
  18917. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  18918. }
  18919. if (parsedTransformNode.localMatrix) {
  18920. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  18921. }
  18922. else if (parsedTransformNode.pivotMatrix) {
  18923. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  18924. }
  18925. transformNode.setEnabled(parsedTransformNode.isEnabled);
  18926. // Parent
  18927. if (parsedTransformNode.parentId) {
  18928. transformNode._waitingParentId = parsedTransformNode.parentId;
  18929. }
  18930. return transformNode;
  18931. };
  18932. /**
  18933. * Releases resources associated with this transform node.
  18934. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18935. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18936. */
  18937. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18938. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18939. // Animations
  18940. this.getScene().stopAnimation(this);
  18941. // Remove from scene
  18942. this.getScene().removeTransformNode(this);
  18943. this.onAfterWorldMatrixUpdateObservable.clear();
  18944. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18945. };
  18946. // Statics
  18947. TransformNode.BILLBOARDMODE_NONE = 0;
  18948. TransformNode.BILLBOARDMODE_X = 1;
  18949. TransformNode.BILLBOARDMODE_Y = 2;
  18950. TransformNode.BILLBOARDMODE_Z = 4;
  18951. TransformNode.BILLBOARDMODE_ALL = 7;
  18952. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  18953. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  18954. __decorate([
  18955. BABYLON.serializeAsVector3()
  18956. ], TransformNode.prototype, "_rotation", void 0);
  18957. __decorate([
  18958. BABYLON.serializeAsQuaternion()
  18959. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  18960. __decorate([
  18961. BABYLON.serializeAsVector3()
  18962. ], TransformNode.prototype, "_scaling", void 0);
  18963. __decorate([
  18964. BABYLON.serialize()
  18965. ], TransformNode.prototype, "billboardMode", void 0);
  18966. __decorate([
  18967. BABYLON.serialize()
  18968. ], TransformNode.prototype, "scalingDeterminant", void 0);
  18969. __decorate([
  18970. BABYLON.serialize()
  18971. ], TransformNode.prototype, "infiniteDistance", void 0);
  18972. __decorate([
  18973. BABYLON.serializeAsVector3()
  18974. ], TransformNode.prototype, "position", void 0);
  18975. return TransformNode;
  18976. }(BABYLON.Node));
  18977. BABYLON.TransformNode = TransformNode;
  18978. })(BABYLON || (BABYLON = {}));
  18979. //# sourceMappingURL=babylon.transformNode.js.map
  18980. "use strict";
  18981. var BABYLON;
  18982. (function (BABYLON) {
  18983. var AbstractMesh = /** @class */ (function (_super) {
  18984. __extends(AbstractMesh, _super);
  18985. // Constructor
  18986. function AbstractMesh(name, scene) {
  18987. if (scene === void 0) { scene = null; }
  18988. var _this = _super.call(this, name, scene, false) || this;
  18989. _this._facetNb = 0; // facet number
  18990. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  18991. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  18992. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  18993. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  18994. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  18995. _this._subDiv = {
  18996. max: 1,
  18997. X: 1,
  18998. Y: 1,
  18999. Z: 1
  19000. };
  19001. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19002. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19003. // Events
  19004. /**
  19005. * An event triggered when this mesh collides with another one
  19006. */
  19007. _this.onCollideObservable = new BABYLON.Observable();
  19008. /**
  19009. * An event triggered when the collision's position changes
  19010. */
  19011. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19012. /**
  19013. * An event triggered when material is changed
  19014. */
  19015. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19016. // Properties
  19017. _this.definedFacingForward = true; // orientation for POV movement & rotation
  19018. /**
  19019. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19020. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19021. * or
  19022. * 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.
  19023. * for more info check WebGl documentations
  19024. */
  19025. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19026. /**
  19027. * 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:
  19028. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19029. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19030. * 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.
  19031. */
  19032. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19033. /**
  19034. * 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.
  19035. * The default value is -1 which means don't break the query and wait till the result.
  19036. */
  19037. _this.occlusionRetryCount = -1;
  19038. _this._occlusionInternalRetryCounter = 0;
  19039. _this._isOccluded = false;
  19040. _this._isOcclusionQueryInProgress = false;
  19041. _this._visibility = 1.0;
  19042. _this.alphaIndex = Number.MAX_VALUE;
  19043. _this.isVisible = true;
  19044. _this.isPickable = true;
  19045. _this.showBoundingBox = false;
  19046. _this.showSubMeshesBoundingBox = false;
  19047. _this.isBlocker = false;
  19048. _this.enablePointerMoveEvents = false;
  19049. _this.renderingGroupId = 0;
  19050. _this._receiveShadows = false;
  19051. _this.renderOutline = false;
  19052. _this.outlineColor = BABYLON.Color3.Red();
  19053. _this.outlineWidth = 0.02;
  19054. _this.renderOverlay = false;
  19055. _this.overlayColor = BABYLON.Color3.Red();
  19056. _this.overlayAlpha = 0.5;
  19057. _this._hasVertexAlpha = false;
  19058. _this._useVertexColors = true;
  19059. _this._computeBonesUsingShaders = true;
  19060. _this._numBoneInfluencers = 4;
  19061. _this._applyFog = true;
  19062. _this.useOctreeForRenderingSelection = true;
  19063. _this.useOctreeForPicking = true;
  19064. _this.useOctreeForCollisions = true;
  19065. _this._layerMask = 0x0FFFFFFF;
  19066. /**
  19067. * True if the mesh must be rendered in any case.
  19068. */
  19069. _this.alwaysSelectAsActiveMesh = false;
  19070. /**
  19071. * This scene's action manager
  19072. */
  19073. _this.actionManager = null;
  19074. // Physics
  19075. _this.physicsImpostor = null;
  19076. // Collisions
  19077. _this._checkCollisions = false;
  19078. _this._collisionMask = -1;
  19079. _this._collisionGroup = -1;
  19080. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19081. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19082. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19083. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19084. // Edges
  19085. _this.edgesWidth = 1;
  19086. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19087. // Cache
  19088. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19089. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19090. _this._renderId = 0;
  19091. _this._intersectionsInProgress = new Array();
  19092. _this._unIndexed = false;
  19093. _this._lightSources = new Array();
  19094. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19095. if (collidedMesh === void 0) { collidedMesh = null; }
  19096. //TODO move this to the collision coordinator!
  19097. if (_this.getScene().workerCollisions)
  19098. newPosition.multiplyInPlace(_this._collider._radius);
  19099. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19100. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19101. _this.position.addInPlace(_this._diffPositionForCollisions);
  19102. }
  19103. if (collidedMesh) {
  19104. _this.onCollideObservable.notifyObservers(collidedMesh);
  19105. }
  19106. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19107. };
  19108. _this.getScene().addMesh(_this);
  19109. _this._resyncLightSources();
  19110. return _this;
  19111. }
  19112. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19113. get: function () {
  19114. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19115. },
  19116. enumerable: true,
  19117. configurable: true
  19118. });
  19119. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19120. get: function () {
  19121. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19122. },
  19123. enumerable: true,
  19124. configurable: true
  19125. });
  19126. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19127. get: function () {
  19128. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19129. },
  19130. enumerable: true,
  19131. configurable: true
  19132. });
  19133. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19134. get: function () {
  19135. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19136. },
  19137. enumerable: true,
  19138. configurable: true
  19139. });
  19140. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19141. get: function () {
  19142. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19143. },
  19144. enumerable: true,
  19145. configurable: true
  19146. });
  19147. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19148. /**
  19149. * Read-only : the number of facets in the mesh
  19150. */
  19151. get: function () {
  19152. return this._facetNb;
  19153. },
  19154. enumerable: true,
  19155. configurable: true
  19156. });
  19157. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19158. /**
  19159. * The number (integer) of subdivisions per axis in the partioning space
  19160. */
  19161. get: function () {
  19162. return this._partitioningSubdivisions;
  19163. },
  19164. set: function (nb) {
  19165. this._partitioningSubdivisions = nb;
  19166. },
  19167. enumerable: true,
  19168. configurable: true
  19169. });
  19170. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19171. /**
  19172. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19173. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  19174. */
  19175. get: function () {
  19176. return this._partitioningBBoxRatio;
  19177. },
  19178. set: function (ratio) {
  19179. this._partitioningBBoxRatio = ratio;
  19180. },
  19181. enumerable: true,
  19182. configurable: true
  19183. });
  19184. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19185. /**
  19186. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  19187. * Works only for updatable meshes.
  19188. * Doesn't work with multi-materials.
  19189. */
  19190. get: function () {
  19191. return this._facetDepthSort;
  19192. },
  19193. set: function (sort) {
  19194. this._facetDepthSort = sort;
  19195. },
  19196. enumerable: true,
  19197. configurable: true
  19198. });
  19199. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19200. /**
  19201. * The location (Vector3) where the facet depth sort must be computed from.
  19202. * By default, the active camera position.
  19203. * Used only when facet depth sort is enabled.
  19204. */
  19205. get: function () {
  19206. return this._facetDepthSortFrom;
  19207. },
  19208. set: function (location) {
  19209. this._facetDepthSortFrom = location;
  19210. },
  19211. enumerable: true,
  19212. configurable: true
  19213. });
  19214. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19215. /**
  19216. * Read-only boolean : is the feature facetData enabled ?
  19217. */
  19218. get: function () {
  19219. return this._facetDataEnabled;
  19220. },
  19221. enumerable: true,
  19222. configurable: true
  19223. });
  19224. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19225. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19226. return false;
  19227. }
  19228. this._markSubMeshesAsMiscDirty();
  19229. return true;
  19230. };
  19231. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19232. set: function (callback) {
  19233. if (this._onCollideObserver) {
  19234. this.onCollideObservable.remove(this._onCollideObserver);
  19235. }
  19236. this._onCollideObserver = this.onCollideObservable.add(callback);
  19237. },
  19238. enumerable: true,
  19239. configurable: true
  19240. });
  19241. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19242. set: function (callback) {
  19243. if (this._onCollisionPositionChangeObserver) {
  19244. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19245. }
  19246. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19247. },
  19248. enumerable: true,
  19249. configurable: true
  19250. });
  19251. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19252. /**
  19253. * 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.
  19254. */
  19255. get: function () {
  19256. return this._isOccluded;
  19257. },
  19258. set: function (value) {
  19259. this._isOccluded = value;
  19260. },
  19261. enumerable: true,
  19262. configurable: true
  19263. });
  19264. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19265. /**
  19266. * Flag to check the progress status of the query
  19267. */
  19268. get: function () {
  19269. return this._isOcclusionQueryInProgress;
  19270. },
  19271. enumerable: true,
  19272. configurable: true
  19273. });
  19274. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19275. /**
  19276. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  19277. */
  19278. get: function () {
  19279. return this._visibility;
  19280. },
  19281. /**
  19282. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  19283. */
  19284. set: function (value) {
  19285. if (this._visibility === value) {
  19286. return;
  19287. }
  19288. this._visibility = value;
  19289. this._markSubMeshesAsMiscDirty();
  19290. },
  19291. enumerable: true,
  19292. configurable: true
  19293. });
  19294. Object.defineProperty(AbstractMesh.prototype, "material", {
  19295. get: function () {
  19296. return this._material;
  19297. },
  19298. set: function (value) {
  19299. if (this._material === value) {
  19300. return;
  19301. }
  19302. this._material = value;
  19303. if (this.onMaterialChangedObservable.hasObservers) {
  19304. this.onMaterialChangedObservable.notifyObservers(this);
  19305. }
  19306. if (!this.subMeshes) {
  19307. return;
  19308. }
  19309. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19310. var subMesh = _a[_i];
  19311. subMesh.setEffect(null);
  19312. }
  19313. },
  19314. enumerable: true,
  19315. configurable: true
  19316. });
  19317. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19318. get: function () {
  19319. return this._receiveShadows;
  19320. },
  19321. set: function (value) {
  19322. if (this._receiveShadows === value) {
  19323. return;
  19324. }
  19325. this._receiveShadows = value;
  19326. this._markSubMeshesAsLightDirty();
  19327. },
  19328. enumerable: true,
  19329. configurable: true
  19330. });
  19331. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19332. get: function () {
  19333. return this._hasVertexAlpha;
  19334. },
  19335. set: function (value) {
  19336. if (this._hasVertexAlpha === value) {
  19337. return;
  19338. }
  19339. this._hasVertexAlpha = value;
  19340. this._markSubMeshesAsAttributesDirty();
  19341. this._markSubMeshesAsMiscDirty();
  19342. },
  19343. enumerable: true,
  19344. configurable: true
  19345. });
  19346. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19347. get: function () {
  19348. return this._useVertexColors;
  19349. },
  19350. set: function (value) {
  19351. if (this._useVertexColors === value) {
  19352. return;
  19353. }
  19354. this._useVertexColors = value;
  19355. this._markSubMeshesAsAttributesDirty();
  19356. },
  19357. enumerable: true,
  19358. configurable: true
  19359. });
  19360. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19361. get: function () {
  19362. return this._computeBonesUsingShaders;
  19363. },
  19364. set: function (value) {
  19365. if (this._computeBonesUsingShaders === value) {
  19366. return;
  19367. }
  19368. this._computeBonesUsingShaders = value;
  19369. this._markSubMeshesAsAttributesDirty();
  19370. },
  19371. enumerable: true,
  19372. configurable: true
  19373. });
  19374. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19375. get: function () {
  19376. return this._numBoneInfluencers;
  19377. },
  19378. set: function (value) {
  19379. if (this._numBoneInfluencers === value) {
  19380. return;
  19381. }
  19382. this._numBoneInfluencers = value;
  19383. this._markSubMeshesAsAttributesDirty();
  19384. },
  19385. enumerable: true,
  19386. configurable: true
  19387. });
  19388. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19389. get: function () {
  19390. return this._applyFog;
  19391. },
  19392. set: function (value) {
  19393. if (this._applyFog === value) {
  19394. return;
  19395. }
  19396. this._applyFog = value;
  19397. this._markSubMeshesAsMiscDirty();
  19398. },
  19399. enumerable: true,
  19400. configurable: true
  19401. });
  19402. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19403. get: function () {
  19404. return this._layerMask;
  19405. },
  19406. set: function (value) {
  19407. if (value === this._layerMask) {
  19408. return;
  19409. }
  19410. this._layerMask = value;
  19411. this._resyncLightSources();
  19412. },
  19413. enumerable: true,
  19414. configurable: true
  19415. });
  19416. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19417. get: function () {
  19418. return this._collisionMask;
  19419. },
  19420. set: function (mask) {
  19421. this._collisionMask = !isNaN(mask) ? mask : -1;
  19422. },
  19423. enumerable: true,
  19424. configurable: true
  19425. });
  19426. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19427. get: function () {
  19428. return this._collisionGroup;
  19429. },
  19430. set: function (mask) {
  19431. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19432. },
  19433. enumerable: true,
  19434. configurable: true
  19435. });
  19436. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19437. get: function () {
  19438. return null;
  19439. },
  19440. enumerable: true,
  19441. configurable: true
  19442. });
  19443. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19444. get: function () {
  19445. return this._skeleton;
  19446. },
  19447. set: function (value) {
  19448. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19449. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19450. }
  19451. if (value && value.needInitialSkinMatrix) {
  19452. value._registerMeshWithPoseMatrix(this);
  19453. }
  19454. this._skeleton = value;
  19455. if (!this._skeleton) {
  19456. this._bonesTransformMatrices = null;
  19457. }
  19458. this._markSubMeshesAsAttributesDirty();
  19459. },
  19460. enumerable: true,
  19461. configurable: true
  19462. });
  19463. /**
  19464. * Returns the string "AbstractMesh"
  19465. */
  19466. AbstractMesh.prototype.getClassName = function () {
  19467. return "AbstractMesh";
  19468. };
  19469. /**
  19470. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19471. */
  19472. AbstractMesh.prototype.toString = function (fullDetails) {
  19473. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19474. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19475. if (this._skeleton) {
  19476. ret += ", skeleton: " + this._skeleton.name;
  19477. }
  19478. if (fullDetails) {
  19479. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19480. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19481. }
  19482. return ret;
  19483. };
  19484. AbstractMesh.prototype._rebuild = function () {
  19485. if (this._occlusionQuery) {
  19486. this._occlusionQuery = null;
  19487. }
  19488. if (this._edgesRenderer) {
  19489. this._edgesRenderer._rebuild();
  19490. }
  19491. if (!this.subMeshes) {
  19492. return;
  19493. }
  19494. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19495. var subMesh = _a[_i];
  19496. subMesh._rebuild();
  19497. }
  19498. };
  19499. AbstractMesh.prototype._resyncLightSources = function () {
  19500. this._lightSources.length = 0;
  19501. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19502. var light = _a[_i];
  19503. if (!light.isEnabled()) {
  19504. continue;
  19505. }
  19506. if (light.canAffectMesh(this)) {
  19507. this._lightSources.push(light);
  19508. }
  19509. }
  19510. this._markSubMeshesAsLightDirty();
  19511. };
  19512. AbstractMesh.prototype._resyncLighSource = function (light) {
  19513. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19514. var index = this._lightSources.indexOf(light);
  19515. if (index === -1) {
  19516. if (!isIn) {
  19517. return;
  19518. }
  19519. this._lightSources.push(light);
  19520. }
  19521. else {
  19522. if (isIn) {
  19523. return;
  19524. }
  19525. this._lightSources.splice(index, 1);
  19526. }
  19527. this._markSubMeshesAsLightDirty();
  19528. };
  19529. AbstractMesh.prototype._removeLightSource = function (light) {
  19530. var index = this._lightSources.indexOf(light);
  19531. if (index === -1) {
  19532. return;
  19533. }
  19534. this._lightSources.splice(index, 1);
  19535. this._markSubMeshesAsLightDirty();
  19536. };
  19537. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19538. if (!this.subMeshes) {
  19539. return;
  19540. }
  19541. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19542. var subMesh = _a[_i];
  19543. if (subMesh._materialDefines) {
  19544. func(subMesh._materialDefines);
  19545. }
  19546. }
  19547. };
  19548. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19549. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19550. };
  19551. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19552. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19553. };
  19554. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19555. if (!this.subMeshes) {
  19556. return;
  19557. }
  19558. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19559. var subMesh = _a[_i];
  19560. var material = subMesh.getMaterial();
  19561. if (material) {
  19562. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19563. }
  19564. }
  19565. };
  19566. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19567. /**
  19568. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19569. * Default : (1.0, 1.0, 1.0)
  19570. */
  19571. get: function () {
  19572. return this._scaling;
  19573. },
  19574. /**
  19575. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19576. * Default : (1.0, 1.0, 1.0)
  19577. */
  19578. set: function (newScaling) {
  19579. this._scaling = newScaling;
  19580. if (this.physicsImpostor) {
  19581. this.physicsImpostor.forceUpdate();
  19582. }
  19583. },
  19584. enumerable: true,
  19585. configurable: true
  19586. });
  19587. // Methods
  19588. /**
  19589. * Disables the mesh edger rendering mode.
  19590. * Returns the AbstractMesh.
  19591. */
  19592. AbstractMesh.prototype.disableEdgesRendering = function () {
  19593. if (this._edgesRenderer) {
  19594. this._edgesRenderer.dispose();
  19595. this._edgesRenderer = null;
  19596. }
  19597. return this;
  19598. };
  19599. /**
  19600. * Enables the edge rendering mode on the mesh.
  19601. * This mode makes the mesh edges visible.
  19602. * Returns the AbstractMesh.
  19603. */
  19604. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19605. if (epsilon === void 0) { epsilon = 0.95; }
  19606. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19607. this.disableEdgesRendering();
  19608. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19609. return this;
  19610. };
  19611. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19612. /**
  19613. * Returns true if the mesh is blocked. Used by the class Mesh.
  19614. * Returns the boolean `false` by default.
  19615. */
  19616. get: function () {
  19617. return false;
  19618. },
  19619. enumerable: true,
  19620. configurable: true
  19621. });
  19622. /**
  19623. * Returns the mesh itself by default, used by the class Mesh.
  19624. * Returned type : AbstractMesh
  19625. */
  19626. AbstractMesh.prototype.getLOD = function (camera) {
  19627. return this;
  19628. };
  19629. /**
  19630. * Returns 0 by default, used by the class Mesh.
  19631. * Returns an integer.
  19632. */
  19633. AbstractMesh.prototype.getTotalVertices = function () {
  19634. return 0;
  19635. };
  19636. /**
  19637. * Returns null by default, used by the class Mesh.
  19638. * Returned type : integer array
  19639. */
  19640. AbstractMesh.prototype.getIndices = function () {
  19641. return null;
  19642. };
  19643. /**
  19644. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  19645. * Returned type : float array or Float32Array
  19646. */
  19647. AbstractMesh.prototype.getVerticesData = function (kind) {
  19648. return null;
  19649. };
  19650. /**
  19651. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19652. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19653. * The `data` are either a numeric array either a Float32Array.
  19654. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19655. * 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).
  19656. * Note that a new underlying VertexBuffer object is created each call.
  19657. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19658. *
  19659. * Possible `kind` values :
  19660. * - BABYLON.VertexBuffer.PositionKind
  19661. * - BABYLON.VertexBuffer.UVKind
  19662. * - BABYLON.VertexBuffer.UV2Kind
  19663. * - BABYLON.VertexBuffer.UV3Kind
  19664. * - BABYLON.VertexBuffer.UV4Kind
  19665. * - BABYLON.VertexBuffer.UV5Kind
  19666. * - BABYLON.VertexBuffer.UV6Kind
  19667. * - BABYLON.VertexBuffer.ColorKind
  19668. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19669. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19670. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19671. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19672. *
  19673. * Returns the Mesh.
  19674. */
  19675. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19676. return this;
  19677. };
  19678. /**
  19679. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19680. * If the mesh has no geometry, it is simply returned as it is.
  19681. * The `data` are either a numeric array either a Float32Array.
  19682. * No new underlying VertexBuffer object is created.
  19683. * 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.
  19684. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19685. *
  19686. * Possible `kind` values :
  19687. * - BABYLON.VertexBuffer.PositionKind
  19688. * - BABYLON.VertexBuffer.UVKind
  19689. * - BABYLON.VertexBuffer.UV2Kind
  19690. * - BABYLON.VertexBuffer.UV3Kind
  19691. * - BABYLON.VertexBuffer.UV4Kind
  19692. * - BABYLON.VertexBuffer.UV5Kind
  19693. * - BABYLON.VertexBuffer.UV6Kind
  19694. * - BABYLON.VertexBuffer.ColorKind
  19695. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19696. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19697. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19698. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19699. *
  19700. * Returns the Mesh.
  19701. */
  19702. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19703. return this;
  19704. };
  19705. /**
  19706. * Sets the mesh indices.
  19707. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  19708. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19709. * This method creates a new index buffer each call.
  19710. * Returns the Mesh.
  19711. */
  19712. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  19713. return this;
  19714. };
  19715. /** Returns false by default, used by the class Mesh.
  19716. * Returns a boolean
  19717. */
  19718. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  19719. return false;
  19720. };
  19721. /**
  19722. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  19723. * Returns a BoundingInfo
  19724. */
  19725. AbstractMesh.prototype.getBoundingInfo = function () {
  19726. if (this._masterMesh) {
  19727. return this._masterMesh.getBoundingInfo();
  19728. }
  19729. if (!this._boundingInfo) {
  19730. // this._boundingInfo is being created here
  19731. this._updateBoundingInfo();
  19732. }
  19733. // cannot be null.
  19734. return this._boundingInfo;
  19735. };
  19736. /**
  19737. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  19738. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  19739. */
  19740. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  19741. if (includeDescendants === void 0) { includeDescendants = true; }
  19742. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  19743. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  19744. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  19745. if (maxDimension === 0) {
  19746. return this;
  19747. }
  19748. var scale = 1 / maxDimension;
  19749. this.scaling.scaleInPlace(scale);
  19750. return this;
  19751. };
  19752. /**
  19753. * Sets a mesh new object BoundingInfo.
  19754. * Returns the AbstractMesh.
  19755. */
  19756. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  19757. this._boundingInfo = boundingInfo;
  19758. return this;
  19759. };
  19760. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  19761. get: function () {
  19762. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  19763. },
  19764. enumerable: true,
  19765. configurable: true
  19766. });
  19767. AbstractMesh.prototype._preActivate = function () {
  19768. };
  19769. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19770. };
  19771. AbstractMesh.prototype._activate = function (renderId) {
  19772. this._renderId = renderId;
  19773. };
  19774. /**
  19775. * Returns the latest update of the World matrix
  19776. * Returns a Matrix.
  19777. */
  19778. AbstractMesh.prototype.getWorldMatrix = function () {
  19779. if (this._masterMesh) {
  19780. return this._masterMesh.getWorldMatrix();
  19781. }
  19782. return _super.prototype.getWorldMatrix.call(this);
  19783. };
  19784. /**
  19785. * Returns the latest update of the World matrix determinant.
  19786. */
  19787. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  19788. if (this._masterMesh) {
  19789. return this._masterMesh._getWorldMatrixDeterminant();
  19790. }
  19791. return _super.prototype._getWorldMatrixDeterminant.call(this);
  19792. };
  19793. // ================================== Point of View Movement =================================
  19794. /**
  19795. * Perform relative position change from the point of view of behind the front of the mesh.
  19796. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19797. * Supports definition of mesh facing forward or backward.
  19798. * @param {number} amountRight
  19799. * @param {number} amountUp
  19800. * @param {number} amountForward
  19801. *
  19802. * Returns the AbstractMesh.
  19803. */
  19804. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  19805. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  19806. return this;
  19807. };
  19808. /**
  19809. * Calculate relative position change from the point of view of behind the front of the mesh.
  19810. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19811. * Supports definition of mesh facing forward or backward.
  19812. * @param {number} amountRight
  19813. * @param {number} amountUp
  19814. * @param {number} amountForward
  19815. *
  19816. * Returns a new Vector3.
  19817. */
  19818. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  19819. var rotMatrix = new BABYLON.Matrix();
  19820. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19821. rotQuaternion.toRotationMatrix(rotMatrix);
  19822. var translationDelta = BABYLON.Vector3.Zero();
  19823. var defForwardMult = this.definedFacingForward ? -1 : 1;
  19824. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  19825. return translationDelta;
  19826. };
  19827. // ================================== Point of View Rotation =================================
  19828. /**
  19829. * Perform relative rotation change from the point of view of behind the front of the mesh.
  19830. * Supports definition of mesh facing forward or backward.
  19831. * @param {number} flipBack
  19832. * @param {number} twirlClockwise
  19833. * @param {number} tiltRight
  19834. *
  19835. * Returns the AbstractMesh.
  19836. */
  19837. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19838. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  19839. return this;
  19840. };
  19841. /**
  19842. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  19843. * Supports definition of mesh facing forward or backward.
  19844. * @param {number} flipBack
  19845. * @param {number} twirlClockwise
  19846. * @param {number} tiltRight
  19847. *
  19848. * Returns a new Vector3.
  19849. */
  19850. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19851. var defForwardMult = this.definedFacingForward ? 1 : -1;
  19852. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  19853. };
  19854. /**
  19855. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  19856. * @param includeDescendants Include bounding info from descendants as well (true by default).
  19857. */
  19858. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  19859. if (includeDescendants === void 0) { includeDescendants = true; }
  19860. this.computeWorldMatrix(true);
  19861. var min;
  19862. var max;
  19863. var boundingInfo = this.getBoundingInfo();
  19864. if (!this.subMeshes) {
  19865. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19866. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19867. }
  19868. else {
  19869. min = boundingInfo.boundingBox.minimumWorld;
  19870. max = boundingInfo.boundingBox.maximumWorld;
  19871. }
  19872. if (includeDescendants) {
  19873. var descendants = this.getDescendants(false);
  19874. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  19875. var descendant = descendants_1[_i];
  19876. var childMesh = descendant;
  19877. childMesh.computeWorldMatrix(true);
  19878. //make sure we have the needed params to get mix and max
  19879. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  19880. continue;
  19881. }
  19882. var childBoundingInfo = childMesh.getBoundingInfo();
  19883. var boundingBox = childBoundingInfo.boundingBox;
  19884. var minBox = boundingBox.minimumWorld;
  19885. var maxBox = boundingBox.maximumWorld;
  19886. BABYLON.Tools.CheckExtends(minBox, min, max);
  19887. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19888. }
  19889. }
  19890. return {
  19891. min: min,
  19892. max: max
  19893. };
  19894. };
  19895. /**
  19896. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  19897. * Returns the AbstractMesh.
  19898. */
  19899. AbstractMesh.prototype._updateBoundingInfo = function () {
  19900. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  19901. this._boundingInfo.update(this.worldMatrixFromCache);
  19902. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19903. return this;
  19904. };
  19905. /**
  19906. * Update a mesh's children BoundingInfo objects only.
  19907. * Returns the AbstractMesh.
  19908. */
  19909. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  19910. if (!this.subMeshes) {
  19911. return this;
  19912. }
  19913. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  19914. var subMesh = this.subMeshes[subIndex];
  19915. if (!subMesh.IsGlobal) {
  19916. subMesh.updateBoundingInfo(matrix);
  19917. }
  19918. }
  19919. return this;
  19920. };
  19921. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  19922. // Bounding info
  19923. this._updateBoundingInfo();
  19924. };
  19925. /**
  19926. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  19927. * A mesh is in the frustum if its bounding box intersects the frustum.
  19928. * Boolean returned.
  19929. */
  19930. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  19931. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  19932. };
  19933. /**
  19934. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  19935. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  19936. * Boolean returned.
  19937. */
  19938. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19939. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  19940. ;
  19941. };
  19942. /**
  19943. * True if the mesh intersects another mesh or a SolidParticle object.
  19944. * 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)
  19945. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  19946. * Returns a boolean.
  19947. */
  19948. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  19949. if (precise === void 0) { precise = false; }
  19950. if (!this._boundingInfo || !mesh._boundingInfo) {
  19951. return false;
  19952. }
  19953. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  19954. return true;
  19955. }
  19956. if (includeDescendants) {
  19957. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  19958. var child = _a[_i];
  19959. if (child.intersectsMesh(mesh, precise, true)) {
  19960. return true;
  19961. }
  19962. }
  19963. }
  19964. return false;
  19965. };
  19966. /**
  19967. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  19968. * Returns a boolean.
  19969. */
  19970. AbstractMesh.prototype.intersectsPoint = function (point) {
  19971. if (!this._boundingInfo) {
  19972. return false;
  19973. }
  19974. return this._boundingInfo.intersectsPoint(point);
  19975. };
  19976. AbstractMesh.prototype.getPhysicsImpostor = function () {
  19977. return this.physicsImpostor;
  19978. };
  19979. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  19980. if (camera === void 0) { camera = null; }
  19981. if (!camera) {
  19982. camera = this.getScene().activeCamera;
  19983. }
  19984. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  19985. };
  19986. /**
  19987. * Returns the distance from the mesh to the active camera.
  19988. * Returns a float.
  19989. */
  19990. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  19991. if (camera === void 0) { camera = null; }
  19992. if (!camera) {
  19993. camera = this.getScene().activeCamera;
  19994. }
  19995. return this.absolutePosition.subtract(camera.position).length();
  19996. };
  19997. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  19998. if (!this.physicsImpostor) {
  19999. return this;
  20000. }
  20001. this.physicsImpostor.applyImpulse(force, contactPoint);
  20002. return this;
  20003. };
  20004. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20005. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20006. return this;
  20007. }
  20008. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20009. mainPivot: pivot1,
  20010. connectedPivot: pivot2,
  20011. nativeParams: options
  20012. });
  20013. return this;
  20014. };
  20015. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20016. // Collisions
  20017. /**
  20018. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  20019. * Default `false`.
  20020. */
  20021. get: function () {
  20022. return this._checkCollisions;
  20023. },
  20024. set: function (collisionEnabled) {
  20025. this._checkCollisions = collisionEnabled;
  20026. if (this.getScene().workerCollisions) {
  20027. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20028. }
  20029. },
  20030. enumerable: true,
  20031. configurable: true
  20032. });
  20033. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20034. /**
  20035. * Gets Collider object used to compute collisions (not physics)
  20036. */
  20037. get: function () {
  20038. return this._collider;
  20039. },
  20040. enumerable: true,
  20041. configurable: true
  20042. });
  20043. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20044. var globalPosition = this.getAbsolutePosition();
  20045. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20046. if (!this._collider) {
  20047. this._collider = new BABYLON.Collider();
  20048. }
  20049. this._collider._radius = this.ellipsoid;
  20050. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20051. return this;
  20052. };
  20053. // Submeshes octree
  20054. /**
  20055. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20056. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  20057. * Returns an Octree of submeshes.
  20058. */
  20059. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20060. if (maxCapacity === void 0) { maxCapacity = 64; }
  20061. if (maxDepth === void 0) { maxDepth = 2; }
  20062. if (!this._submeshesOctree) {
  20063. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20064. }
  20065. this.computeWorldMatrix(true);
  20066. var boundingInfo = this.getBoundingInfo();
  20067. // Update octree
  20068. var bbox = boundingInfo.boundingBox;
  20069. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20070. return this._submeshesOctree;
  20071. };
  20072. // Collisions
  20073. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20074. this._generatePointsArray();
  20075. if (!this._positions) {
  20076. return this;
  20077. }
  20078. // Transformation
  20079. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20080. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20081. subMesh._lastColliderWorldVertices = [];
  20082. subMesh._trianglePlanes = [];
  20083. var start = subMesh.verticesStart;
  20084. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20085. for (var i = start; i < end; i++) {
  20086. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20087. }
  20088. }
  20089. // Collide
  20090. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20091. if (collider.collisionFound) {
  20092. collider.collidedMesh = this;
  20093. }
  20094. return this;
  20095. };
  20096. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20097. var subMeshes;
  20098. var len;
  20099. // Octrees
  20100. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20101. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20102. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20103. len = intersections.length;
  20104. subMeshes = intersections.data;
  20105. }
  20106. else {
  20107. subMeshes = this.subMeshes;
  20108. len = subMeshes.length;
  20109. }
  20110. for (var index = 0; index < len; index++) {
  20111. var subMesh = subMeshes[index];
  20112. // Bounding test
  20113. if (len > 1 && !subMesh._checkCollision(collider))
  20114. continue;
  20115. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20116. }
  20117. return this;
  20118. };
  20119. AbstractMesh.prototype._checkCollision = function (collider) {
  20120. // Bounding box test
  20121. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20122. return this;
  20123. // Transformation matrix
  20124. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20125. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20126. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20127. return this;
  20128. };
  20129. // Picking
  20130. AbstractMesh.prototype._generatePointsArray = function () {
  20131. return false;
  20132. };
  20133. /**
  20134. * Checks if the passed Ray intersects with the mesh.
  20135. * Returns an object PickingInfo.
  20136. */
  20137. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20138. var pickingInfo = new BABYLON.PickingInfo();
  20139. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20140. return pickingInfo;
  20141. }
  20142. if (!this._generatePointsArray()) {
  20143. return pickingInfo;
  20144. }
  20145. var intersectInfo = null;
  20146. // Octrees
  20147. var subMeshes;
  20148. var len;
  20149. if (this._submeshesOctree && this.useOctreeForPicking) {
  20150. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20151. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20152. len = intersections.length;
  20153. subMeshes = intersections.data;
  20154. }
  20155. else {
  20156. subMeshes = this.subMeshes;
  20157. len = subMeshes.length;
  20158. }
  20159. for (var index = 0; index < len; index++) {
  20160. var subMesh = subMeshes[index];
  20161. // Bounding test
  20162. if (len > 1 && !subMesh.canIntersects(ray))
  20163. continue;
  20164. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20165. if (currentIntersectInfo) {
  20166. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20167. intersectInfo = currentIntersectInfo;
  20168. intersectInfo.subMeshId = index;
  20169. if (fastCheck) {
  20170. break;
  20171. }
  20172. }
  20173. }
  20174. }
  20175. if (intersectInfo) {
  20176. // Get picked point
  20177. var world = this.getWorldMatrix();
  20178. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20179. var direction = ray.direction.clone();
  20180. direction = direction.scale(intersectInfo.distance);
  20181. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20182. var pickedPoint = worldOrigin.add(worldDirection);
  20183. // Return result
  20184. pickingInfo.hit = true;
  20185. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20186. pickingInfo.pickedPoint = pickedPoint;
  20187. pickingInfo.pickedMesh = this;
  20188. pickingInfo.bu = intersectInfo.bu || 0;
  20189. pickingInfo.bv = intersectInfo.bv || 0;
  20190. pickingInfo.faceId = intersectInfo.faceId;
  20191. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20192. return pickingInfo;
  20193. }
  20194. return pickingInfo;
  20195. };
  20196. /**
  20197. * Clones the mesh, used by the class Mesh.
  20198. * Just returns `null` for an AbstractMesh.
  20199. */
  20200. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20201. return null;
  20202. };
  20203. /**
  20204. * Disposes all the mesh submeshes.
  20205. * Returns the AbstractMesh.
  20206. */
  20207. AbstractMesh.prototype.releaseSubMeshes = function () {
  20208. if (this.subMeshes) {
  20209. while (this.subMeshes.length) {
  20210. this.subMeshes[0].dispose();
  20211. }
  20212. }
  20213. else {
  20214. this.subMeshes = new Array();
  20215. }
  20216. return this;
  20217. };
  20218. /**
  20219. * Releases resources associated with this abstract mesh.
  20220. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20221. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20222. */
  20223. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20224. var _this = this;
  20225. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20226. var index;
  20227. // Smart Array Retainers.
  20228. this.getScene().freeActiveMeshes();
  20229. this.getScene().freeRenderingGroups();
  20230. // Action manager
  20231. if (this.actionManager !== undefined && this.actionManager !== null) {
  20232. this.actionManager.dispose();
  20233. this.actionManager = null;
  20234. }
  20235. // Skeleton
  20236. this._skeleton = null;
  20237. // Physics
  20238. if (this.physicsImpostor) {
  20239. this.physicsImpostor.dispose();
  20240. }
  20241. // Intersections in progress
  20242. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20243. var other = this._intersectionsInProgress[index];
  20244. var pos = other._intersectionsInProgress.indexOf(this);
  20245. other._intersectionsInProgress.splice(pos, 1);
  20246. }
  20247. this._intersectionsInProgress = [];
  20248. // Lights
  20249. var lights = this.getScene().lights;
  20250. lights.forEach(function (light) {
  20251. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20252. if (meshIndex !== -1) {
  20253. light.includedOnlyMeshes.splice(meshIndex, 1);
  20254. }
  20255. meshIndex = light.excludedMeshes.indexOf(_this);
  20256. if (meshIndex !== -1) {
  20257. light.excludedMeshes.splice(meshIndex, 1);
  20258. }
  20259. // Shadow generators
  20260. var generator = light.getShadowGenerator();
  20261. if (generator) {
  20262. var shadowMap = generator.getShadowMap();
  20263. if (shadowMap && shadowMap.renderList) {
  20264. meshIndex = shadowMap.renderList.indexOf(_this);
  20265. if (meshIndex !== -1) {
  20266. shadowMap.renderList.splice(meshIndex, 1);
  20267. }
  20268. }
  20269. }
  20270. });
  20271. // Edges
  20272. if (this._edgesRenderer) {
  20273. this._edgesRenderer.dispose();
  20274. this._edgesRenderer = null;
  20275. }
  20276. // SubMeshes
  20277. if (this.getClassName() !== "InstancedMesh") {
  20278. this.releaseSubMeshes();
  20279. }
  20280. // Octree
  20281. var sceneOctree = this.getScene().selectionOctree;
  20282. if (sceneOctree !== undefined && sceneOctree !== null) {
  20283. var index = sceneOctree.dynamicContent.indexOf(this);
  20284. if (index !== -1) {
  20285. sceneOctree.dynamicContent.splice(index, 1);
  20286. }
  20287. }
  20288. // Query
  20289. var engine = this.getScene().getEngine();
  20290. if (this._occlusionQuery) {
  20291. this._isOcclusionQueryInProgress = false;
  20292. engine.deleteQuery(this._occlusionQuery);
  20293. this._occlusionQuery = null;
  20294. }
  20295. // Engine
  20296. engine.wipeCaches();
  20297. // Remove from scene
  20298. this.getScene().removeMesh(this);
  20299. if (disposeMaterialAndTextures) {
  20300. if (this.material) {
  20301. this.material.dispose(false, true);
  20302. }
  20303. }
  20304. if (!doNotRecurse) {
  20305. // Particles
  20306. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20307. if (this.getScene().particleSystems[index].emitter === this) {
  20308. this.getScene().particleSystems[index].dispose();
  20309. index--;
  20310. }
  20311. }
  20312. }
  20313. // facet data
  20314. if (this._facetDataEnabled) {
  20315. this.disableFacetData();
  20316. }
  20317. this.onAfterWorldMatrixUpdateObservable.clear();
  20318. this.onCollideObservable.clear();
  20319. this.onCollisionPositionChangeObservable.clear();
  20320. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20321. };
  20322. /**
  20323. * Adds the passed mesh as a child to the current mesh.
  20324. * Returns the AbstractMesh.
  20325. */
  20326. AbstractMesh.prototype.addChild = function (mesh) {
  20327. mesh.setParent(this);
  20328. return this;
  20329. };
  20330. /**
  20331. * Removes the passed mesh from the current mesh children list.
  20332. * Returns the AbstractMesh.
  20333. */
  20334. AbstractMesh.prototype.removeChild = function (mesh) {
  20335. mesh.setParent(null);
  20336. return this;
  20337. };
  20338. // Facet data
  20339. /**
  20340. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  20341. * Returns the AbstractMesh.
  20342. */
  20343. AbstractMesh.prototype._initFacetData = function () {
  20344. if (!this._facetNormals) {
  20345. this._facetNormals = new Array();
  20346. }
  20347. if (!this._facetPositions) {
  20348. this._facetPositions = new Array();
  20349. }
  20350. if (!this._facetPartitioning) {
  20351. this._facetPartitioning = new Array();
  20352. }
  20353. this._facetNb = (this.getIndices().length / 3) | 0;
  20354. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20355. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20356. for (var f = 0; f < this._facetNb; f++) {
  20357. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20358. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20359. }
  20360. this._facetDataEnabled = true;
  20361. return this;
  20362. };
  20363. /**
  20364. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20365. * This method can be called within the render loop.
  20366. * 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.
  20367. * Returns the AbstractMesh.
  20368. */
  20369. AbstractMesh.prototype.updateFacetData = function () {
  20370. if (!this._facetDataEnabled) {
  20371. this._initFacetData();
  20372. }
  20373. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20374. var indices = this.getIndices();
  20375. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20376. var bInfo = this.getBoundingInfo();
  20377. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20378. // init arrays, matrix and sort function on first call
  20379. this._facetDepthSortEnabled = true;
  20380. if (indices instanceof Uint16Array) {
  20381. this._depthSortedIndices = new Uint16Array(indices);
  20382. }
  20383. else if (indices instanceof Uint32Array) {
  20384. this._depthSortedIndices = new Uint32Array(indices);
  20385. }
  20386. else {
  20387. var needs32bits = false;
  20388. for (var i = 0; i < indices.length; i++) {
  20389. if (indices[i] > 65535) {
  20390. needs32bits = true;
  20391. break;
  20392. }
  20393. }
  20394. if (needs32bits) {
  20395. this._depthSortedIndices = new Uint32Array(indices);
  20396. }
  20397. else {
  20398. this._depthSortedIndices = new Uint16Array(indices);
  20399. }
  20400. }
  20401. this._facetDepthSortFunction = function (f1, f2) {
  20402. return (f2.sqDistance - f1.sqDistance);
  20403. };
  20404. if (!this._facetDepthSortFrom) {
  20405. var camera = this.getScene().activeCamera;
  20406. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20407. }
  20408. this._depthSortedFacets = [];
  20409. for (var f = 0; f < this._facetNb; f++) {
  20410. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20411. this._depthSortedFacets.push(depthSortedFacet);
  20412. }
  20413. this._invertedMatrix = BABYLON.Matrix.Identity();
  20414. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20415. }
  20416. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20417. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20418. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20419. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20420. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20421. this._subDiv.max = this._partitioningSubdivisions;
  20422. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20423. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20424. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20425. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20426. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20427. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20428. // set the parameters for ComputeNormals()
  20429. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20430. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20431. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20432. this._facetParameters.bInfo = bInfo;
  20433. this._facetParameters.bbSize = this._bbSize;
  20434. this._facetParameters.subDiv = this._subDiv;
  20435. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20436. this._facetParameters.depthSort = this._facetDepthSort;
  20437. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20438. this.computeWorldMatrix(true);
  20439. this._worldMatrix.invertToRef(this._invertedMatrix);
  20440. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20441. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20442. }
  20443. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20444. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20445. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20446. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20447. var l = (this._depthSortedIndices.length / 3) | 0;
  20448. for (var f = 0; f < l; f++) {
  20449. var sind = this._depthSortedFacets[f].ind;
  20450. this._depthSortedIndices[f * 3] = indices[sind];
  20451. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20452. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20453. }
  20454. this.updateIndices(this._depthSortedIndices);
  20455. }
  20456. return this;
  20457. };
  20458. /**
  20459. * Returns the facetLocalNormals array.
  20460. * The normals are expressed in the mesh local space.
  20461. */
  20462. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20463. if (!this._facetNormals) {
  20464. this.updateFacetData();
  20465. }
  20466. return this._facetNormals;
  20467. };
  20468. /**
  20469. * Returns the facetLocalPositions array.
  20470. * The facet positions are expressed in the mesh local space.
  20471. */
  20472. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20473. if (!this._facetPositions) {
  20474. this.updateFacetData();
  20475. }
  20476. return this._facetPositions;
  20477. };
  20478. /**
  20479. * Returns the facetLocalPartioning array.
  20480. */
  20481. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20482. if (!this._facetPartitioning) {
  20483. this.updateFacetData();
  20484. }
  20485. return this._facetPartitioning;
  20486. };
  20487. /**
  20488. * Returns the i-th facet position in the world system.
  20489. * This method allocates a new Vector3 per call.
  20490. */
  20491. AbstractMesh.prototype.getFacetPosition = function (i) {
  20492. var pos = BABYLON.Vector3.Zero();
  20493. this.getFacetPositionToRef(i, pos);
  20494. return pos;
  20495. };
  20496. /**
  20497. * Sets the reference Vector3 with the i-th facet position in the world system.
  20498. * Returns the AbstractMesh.
  20499. */
  20500. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20501. var localPos = (this.getFacetLocalPositions())[i];
  20502. var world = this.getWorldMatrix();
  20503. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20504. return this;
  20505. };
  20506. /**
  20507. * Returns the i-th facet normal in the world system.
  20508. * This method allocates a new Vector3 per call.
  20509. */
  20510. AbstractMesh.prototype.getFacetNormal = function (i) {
  20511. var norm = BABYLON.Vector3.Zero();
  20512. this.getFacetNormalToRef(i, norm);
  20513. return norm;
  20514. };
  20515. /**
  20516. * Sets the reference Vector3 with the i-th facet normal in the world system.
  20517. * Returns the AbstractMesh.
  20518. */
  20519. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20520. var localNorm = (this.getFacetLocalNormals())[i];
  20521. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20522. return this;
  20523. };
  20524. /**
  20525. * 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).
  20526. */
  20527. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20528. var bInfo = this.getBoundingInfo();
  20529. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20530. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20531. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20532. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20533. return null;
  20534. }
  20535. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20536. };
  20537. /**
  20538. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  20539. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  20540. * 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.
  20541. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20542. * 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.
  20543. */
  20544. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20545. if (checkFace === void 0) { checkFace = false; }
  20546. if (facing === void 0) { facing = true; }
  20547. var world = this.getWorldMatrix();
  20548. var invMat = BABYLON.Tmp.Matrix[5];
  20549. world.invertToRef(invMat);
  20550. var invVect = BABYLON.Tmp.Vector3[8];
  20551. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20552. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20553. if (projected) {
  20554. // tranform the local computed projected vector to world coordinates
  20555. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20556. }
  20557. return closest;
  20558. };
  20559. /**
  20560. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  20561. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  20562. * 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.
  20563. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20564. * 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.
  20565. */
  20566. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  20567. if (checkFace === void 0) { checkFace = false; }
  20568. if (facing === void 0) { facing = true; }
  20569. var closest = null;
  20570. var tmpx = 0.0;
  20571. var tmpy = 0.0;
  20572. var tmpz = 0.0;
  20573. var d = 0.0; // tmp dot facet normal * facet position
  20574. var t0 = 0.0;
  20575. var projx = 0.0;
  20576. var projy = 0.0;
  20577. var projz = 0.0;
  20578. // Get all the facets in the same partitioning block than (x, y, z)
  20579. var facetPositions = this.getFacetLocalPositions();
  20580. var facetNormals = this.getFacetLocalNormals();
  20581. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  20582. if (!facetsInBlock) {
  20583. return null;
  20584. }
  20585. // Get the closest facet to (x, y, z)
  20586. var shortest = Number.MAX_VALUE; // init distance vars
  20587. var tmpDistance = shortest;
  20588. var fib; // current facet in the block
  20589. var norm; // current facet normal
  20590. var p0; // current facet barycenter position
  20591. // loop on all the facets in the current partitioning block
  20592. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  20593. fib = facetsInBlock[idx];
  20594. norm = facetNormals[fib];
  20595. p0 = facetPositions[fib];
  20596. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  20597. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  20598. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  20599. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  20600. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  20601. projx = x + norm.x * t0;
  20602. projy = y + norm.y * t0;
  20603. projz = z + norm.z * t0;
  20604. tmpx = projx - x;
  20605. tmpy = projy - y;
  20606. tmpz = projz - z;
  20607. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  20608. if (tmpDistance < shortest) {
  20609. shortest = tmpDistance;
  20610. closest = fib;
  20611. if (projected) {
  20612. projected.x = projx;
  20613. projected.y = projy;
  20614. projected.z = projz;
  20615. }
  20616. }
  20617. }
  20618. }
  20619. return closest;
  20620. };
  20621. /**
  20622. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  20623. */
  20624. AbstractMesh.prototype.getFacetDataParameters = function () {
  20625. return this._facetParameters;
  20626. };
  20627. /**
  20628. * Disables the feature FacetData and frees the related memory.
  20629. * Returns the AbstractMesh.
  20630. */
  20631. AbstractMesh.prototype.disableFacetData = function () {
  20632. if (this._facetDataEnabled) {
  20633. this._facetDataEnabled = false;
  20634. this._facetPositions = new Array();
  20635. this._facetNormals = new Array();
  20636. this._facetPartitioning = new Array();
  20637. this._facetParameters = null;
  20638. this._depthSortedIndices = new Uint32Array(0);
  20639. }
  20640. return this;
  20641. };
  20642. /**
  20643. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  20644. * Returns the mesh.
  20645. */
  20646. AbstractMesh.prototype.updateIndices = function (indices) {
  20647. return this;
  20648. };
  20649. /**
  20650. * The mesh Geometry. Actually used by the Mesh object.
  20651. * Returns a blank geometry object.
  20652. */
  20653. /**
  20654. * Creates new normals data for the mesh.
  20655. * @param updatable.
  20656. */
  20657. AbstractMesh.prototype.createNormals = function (updatable) {
  20658. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20659. var indices = this.getIndices();
  20660. var normals;
  20661. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20662. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20663. }
  20664. else {
  20665. normals = [];
  20666. }
  20667. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  20668. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  20669. };
  20670. /**
  20671. * Align the mesh with a normal.
  20672. * Returns the mesh.
  20673. */
  20674. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  20675. if (!upDirection) {
  20676. upDirection = BABYLON.Axis.Y;
  20677. }
  20678. var axisX = BABYLON.Tmp.Vector3[0];
  20679. var axisZ = BABYLON.Tmp.Vector3[1];
  20680. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  20681. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  20682. if (this.rotationQuaternion) {
  20683. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  20684. }
  20685. else {
  20686. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  20687. }
  20688. return this;
  20689. };
  20690. AbstractMesh.prototype.checkOcclusionQuery = function () {
  20691. var engine = this.getEngine();
  20692. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  20693. this._isOccluded = false;
  20694. return;
  20695. }
  20696. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  20697. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  20698. if (isOcclusionQueryAvailable) {
  20699. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  20700. this._isOcclusionQueryInProgress = false;
  20701. this._occlusionInternalRetryCounter = 0;
  20702. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  20703. }
  20704. else {
  20705. this._occlusionInternalRetryCounter++;
  20706. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  20707. this._isOcclusionQueryInProgress = false;
  20708. this._occlusionInternalRetryCounter = 0;
  20709. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  20710. // if strict continue the last state of the object.
  20711. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  20712. }
  20713. else {
  20714. return;
  20715. }
  20716. }
  20717. }
  20718. var scene = this.getScene();
  20719. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  20720. if (!this._occlusionQuery) {
  20721. this._occlusionQuery = engine.createQuery();
  20722. }
  20723. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  20724. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  20725. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  20726. this._isOcclusionQueryInProgress = true;
  20727. };
  20728. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  20729. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  20730. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  20731. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  20732. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  20733. return AbstractMesh;
  20734. }(BABYLON.TransformNode));
  20735. BABYLON.AbstractMesh = AbstractMesh;
  20736. })(BABYLON || (BABYLON = {}));
  20737. //# sourceMappingURL=babylon.abstractMesh.js.map
  20738. "use strict";
  20739. var BABYLON;
  20740. (function (BABYLON) {
  20741. /**
  20742. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  20743. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  20744. * 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.
  20745. */
  20746. var Light = /** @class */ (function (_super) {
  20747. __extends(Light, _super);
  20748. /**
  20749. * Creates a Light object in the scene.
  20750. * Documentation : http://doc.babylonjs.com/tutorials/lights
  20751. * @param name The firendly name of the light
  20752. * @param scene The scene the light belongs too
  20753. */
  20754. function Light(name, scene) {
  20755. var _this = _super.call(this, name, scene) || this;
  20756. /**
  20757. * Diffuse gives the basic color to an object.
  20758. */
  20759. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  20760. /**
  20761. * Specular produces a highlight color on an object.
  20762. * Note: This is note affecting PBR materials.
  20763. */
  20764. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  20765. /**
  20766. * Strength of the light.
  20767. * Note: By default it is define in the framework own unit.
  20768. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  20769. */
  20770. _this.intensity = 1.0;
  20771. /**
  20772. * Defines how far from the source the light is impacting in scene units.
  20773. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  20774. */
  20775. _this.range = Number.MAX_VALUE;
  20776. /**
  20777. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  20778. * of light.
  20779. */
  20780. _this._photometricScale = 1.0;
  20781. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  20782. _this._radius = 0.00001;
  20783. /**
  20784. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  20785. * exceeding the number allowed of the materials.
  20786. */
  20787. _this.renderPriority = 0;
  20788. /**
  20789. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  20790. * the current shadow generator.
  20791. */
  20792. _this.shadowEnabled = true;
  20793. _this._excludeWithLayerMask = 0;
  20794. _this._includeOnlyWithLayerMask = 0;
  20795. _this._lightmapMode = 0;
  20796. /**
  20797. * @ignore Internal use only.
  20798. */
  20799. _this._excludedMeshesIds = new Array();
  20800. /**
  20801. * @ignore Internal use only.
  20802. */
  20803. _this._includedOnlyMeshesIds = new Array();
  20804. _this.getScene().addLight(_this);
  20805. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  20806. _this._buildUniformLayout();
  20807. _this.includedOnlyMeshes = new Array();
  20808. _this.excludedMeshes = new Array();
  20809. _this._resyncMeshes();
  20810. return _this;
  20811. }
  20812. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  20813. /**
  20814. * If every light affecting the material is in this lightmapMode,
  20815. * material.lightmapTexture adds or multiplies
  20816. * (depends on material.useLightmapAsShadowmap)
  20817. * after every other light calculations.
  20818. */
  20819. get: function () {
  20820. return Light._LIGHTMAP_DEFAULT;
  20821. },
  20822. enumerable: true,
  20823. configurable: true
  20824. });
  20825. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  20826. /**
  20827. * material.lightmapTexture as only diffuse lighting from this light
  20828. * adds only specular lighting from this light
  20829. * adds dynamic shadows
  20830. */
  20831. get: function () {
  20832. return Light._LIGHTMAP_SPECULAR;
  20833. },
  20834. enumerable: true,
  20835. configurable: true
  20836. });
  20837. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  20838. /**
  20839. * material.lightmapTexture as only lighting
  20840. * no light calculation from this light
  20841. * only adds dynamic shadows from this light
  20842. */
  20843. get: function () {
  20844. return Light._LIGHTMAP_SHADOWSONLY;
  20845. },
  20846. enumerable: true,
  20847. configurable: true
  20848. });
  20849. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  20850. /**
  20851. * Each light type uses the default quantity according to its type:
  20852. * point/spot lights use luminous intensity
  20853. * directional lights use illuminance
  20854. */
  20855. get: function () {
  20856. return Light._INTENSITYMODE_AUTOMATIC;
  20857. },
  20858. enumerable: true,
  20859. configurable: true
  20860. });
  20861. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  20862. /**
  20863. * lumen (lm)
  20864. */
  20865. get: function () {
  20866. return Light._INTENSITYMODE_LUMINOUSPOWER;
  20867. },
  20868. enumerable: true,
  20869. configurable: true
  20870. });
  20871. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  20872. /**
  20873. * candela (lm/sr)
  20874. */
  20875. get: function () {
  20876. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  20877. },
  20878. enumerable: true,
  20879. configurable: true
  20880. });
  20881. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  20882. /**
  20883. * lux (lm/m^2)
  20884. */
  20885. get: function () {
  20886. return Light._INTENSITYMODE_ILLUMINANCE;
  20887. },
  20888. enumerable: true,
  20889. configurable: true
  20890. });
  20891. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  20892. /**
  20893. * nit (cd/m^2)
  20894. */
  20895. get: function () {
  20896. return Light._INTENSITYMODE_LUMINANCE;
  20897. },
  20898. enumerable: true,
  20899. configurable: true
  20900. });
  20901. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  20902. /**
  20903. * Light type const id of the point light.
  20904. */
  20905. get: function () {
  20906. return Light._LIGHTTYPEID_POINTLIGHT;
  20907. },
  20908. enumerable: true,
  20909. configurable: true
  20910. });
  20911. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  20912. /**
  20913. * Light type const id of the directional light.
  20914. */
  20915. get: function () {
  20916. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  20917. },
  20918. enumerable: true,
  20919. configurable: true
  20920. });
  20921. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  20922. /**
  20923. * Light type const id of the spot light.
  20924. */
  20925. get: function () {
  20926. return Light._LIGHTTYPEID_SPOTLIGHT;
  20927. },
  20928. enumerable: true,
  20929. configurable: true
  20930. });
  20931. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  20932. /**
  20933. * Light type const id of the hemispheric light.
  20934. */
  20935. get: function () {
  20936. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  20937. },
  20938. enumerable: true,
  20939. configurable: true
  20940. });
  20941. Object.defineProperty(Light.prototype, "intensityMode", {
  20942. /**
  20943. * Gets the photometric scale used to interpret the intensity.
  20944. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  20945. */
  20946. get: function () {
  20947. return this._intensityMode;
  20948. },
  20949. /**
  20950. * Sets the photometric scale used to interpret the intensity.
  20951. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  20952. */
  20953. set: function (value) {
  20954. this._intensityMode = value;
  20955. this._computePhotometricScale();
  20956. },
  20957. enumerable: true,
  20958. configurable: true
  20959. });
  20960. ;
  20961. ;
  20962. Object.defineProperty(Light.prototype, "radius", {
  20963. /**
  20964. * Gets the light radius used by PBR Materials to simulate soft area lights.
  20965. */
  20966. get: function () {
  20967. return this._radius;
  20968. },
  20969. /**
  20970. * sets the light radius used by PBR Materials to simulate soft area lights.
  20971. */
  20972. set: function (value) {
  20973. this._radius = value;
  20974. this._computePhotometricScale();
  20975. },
  20976. enumerable: true,
  20977. configurable: true
  20978. });
  20979. ;
  20980. ;
  20981. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  20982. /**
  20983. * Gets the only meshes impacted by this light.
  20984. */
  20985. get: function () {
  20986. return this._includedOnlyMeshes;
  20987. },
  20988. /**
  20989. * Sets the only meshes impacted by this light.
  20990. */
  20991. set: function (value) {
  20992. this._includedOnlyMeshes = value;
  20993. this._hookArrayForIncludedOnly(value);
  20994. },
  20995. enumerable: true,
  20996. configurable: true
  20997. });
  20998. Object.defineProperty(Light.prototype, "excludedMeshes", {
  20999. /**
  21000. * Gets the meshes not impacted by this light.
  21001. */
  21002. get: function () {
  21003. return this._excludedMeshes;
  21004. },
  21005. /**
  21006. * Sets the meshes not impacted by this light.
  21007. */
  21008. set: function (value) {
  21009. this._excludedMeshes = value;
  21010. this._hookArrayForExcluded(value);
  21011. },
  21012. enumerable: true,
  21013. configurable: true
  21014. });
  21015. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21016. /**
  21017. * Gets the layer id use to find what meshes are not impacted by the light.
  21018. * Inactive if 0
  21019. */
  21020. get: function () {
  21021. return this._excludeWithLayerMask;
  21022. },
  21023. /**
  21024. * Sets the layer id use to find what meshes are not impacted by the light.
  21025. * Inactive if 0
  21026. */
  21027. set: function (value) {
  21028. this._excludeWithLayerMask = value;
  21029. this._resyncMeshes();
  21030. },
  21031. enumerable: true,
  21032. configurable: true
  21033. });
  21034. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21035. /**
  21036. * Gets the layer id use to find what meshes are impacted by the light.
  21037. * Inactive if 0
  21038. */
  21039. get: function () {
  21040. return this._includeOnlyWithLayerMask;
  21041. },
  21042. /**
  21043. * Sets the layer id use to find what meshes are impacted by the light.
  21044. * Inactive if 0
  21045. */
  21046. set: function (value) {
  21047. this._includeOnlyWithLayerMask = value;
  21048. this._resyncMeshes();
  21049. },
  21050. enumerable: true,
  21051. configurable: true
  21052. });
  21053. Object.defineProperty(Light.prototype, "lightmapMode", {
  21054. /**
  21055. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21056. */
  21057. get: function () {
  21058. return this._lightmapMode;
  21059. },
  21060. /**
  21061. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21062. */
  21063. set: function (value) {
  21064. if (this._lightmapMode === value) {
  21065. return;
  21066. }
  21067. this._lightmapMode = value;
  21068. this._markMeshesAsLightDirty();
  21069. },
  21070. enumerable: true,
  21071. configurable: true
  21072. });
  21073. /**
  21074. * Returns the string "Light".
  21075. * @returns the class name
  21076. */
  21077. Light.prototype.getClassName = function () {
  21078. return "Light";
  21079. };
  21080. /**
  21081. * Converts the light information to a readable string for debug purpose.
  21082. * @param fullDetails Supports for multiple levels of logging within scene loading
  21083. * @returns the human readable light info
  21084. */
  21085. Light.prototype.toString = function (fullDetails) {
  21086. var ret = "Name: " + this.name;
  21087. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21088. if (this.animations) {
  21089. for (var i = 0; i < this.animations.length; i++) {
  21090. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21091. }
  21092. }
  21093. if (fullDetails) {
  21094. }
  21095. return ret;
  21096. };
  21097. /**
  21098. * Set the enabled state of this node.
  21099. * @param value - the new enabled state
  21100. */
  21101. Light.prototype.setEnabled = function (value) {
  21102. _super.prototype.setEnabled.call(this, value);
  21103. this._resyncMeshes();
  21104. };
  21105. /**
  21106. * Returns the Light associated shadow generator if any.
  21107. * @return the associated shadow generator.
  21108. */
  21109. Light.prototype.getShadowGenerator = function () {
  21110. return this._shadowGenerator;
  21111. };
  21112. /**
  21113. * Returns a Vector3, the absolute light position in the World.
  21114. * @returns the world space position of the light
  21115. */
  21116. Light.prototype.getAbsolutePosition = function () {
  21117. return BABYLON.Vector3.Zero();
  21118. };
  21119. /**
  21120. * Specifies if the light will affect the passed mesh.
  21121. * @param mesh The mesh to test against the light
  21122. * @return true the mesh is affected otherwise, false.
  21123. */
  21124. Light.prototype.canAffectMesh = function (mesh) {
  21125. if (!mesh) {
  21126. return true;
  21127. }
  21128. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21129. return false;
  21130. }
  21131. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21132. return false;
  21133. }
  21134. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21135. return false;
  21136. }
  21137. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21138. return false;
  21139. }
  21140. return true;
  21141. };
  21142. /**
  21143. * Computes and Returns the light World matrix.
  21144. * @returns the world matrix
  21145. */
  21146. Light.prototype.getWorldMatrix = function () {
  21147. this._currentRenderId = this.getScene().getRenderId();
  21148. this._childRenderId = this._currentRenderId;
  21149. var worldMatrix = this._getWorldMatrix();
  21150. if (this.parent && this.parent.getWorldMatrix) {
  21151. if (!this._parentedWorldMatrix) {
  21152. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21153. }
  21154. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21155. this._markSyncedWithParent();
  21156. return this._parentedWorldMatrix;
  21157. }
  21158. return worldMatrix;
  21159. };
  21160. /**
  21161. * Sort function to order lights for rendering.
  21162. * @param a First Light object to compare to second.
  21163. * @param b Second Light object to compare first.
  21164. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21165. */
  21166. Light.CompareLightsPriority = function (a, b) {
  21167. //shadow-casting lights have priority over non-shadow-casting lights
  21168. //the renderPrioirty is a secondary sort criterion
  21169. if (a.shadowEnabled !== b.shadowEnabled) {
  21170. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21171. }
  21172. return b.renderPriority - a.renderPriority;
  21173. };
  21174. /**
  21175. * Releases resources associated with this node.
  21176. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21177. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21178. */
  21179. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21180. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21181. if (this._shadowGenerator) {
  21182. this._shadowGenerator.dispose();
  21183. this._shadowGenerator = null;
  21184. }
  21185. // Animations
  21186. this.getScene().stopAnimation(this);
  21187. // Remove from meshes
  21188. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21189. var mesh = _a[_i];
  21190. mesh._removeLightSource(this);
  21191. }
  21192. this._uniformBuffer.dispose();
  21193. // Remove from scene
  21194. this.getScene().removeLight(this);
  21195. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21196. };
  21197. /**
  21198. * Returns the light type ID (integer).
  21199. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21200. */
  21201. Light.prototype.getTypeID = function () {
  21202. return 0;
  21203. };
  21204. /**
  21205. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21206. * @returns the scaled intensity in intensity mode unit
  21207. */
  21208. Light.prototype.getScaledIntensity = function () {
  21209. return this._photometricScale * this.intensity;
  21210. };
  21211. /**
  21212. * Returns a new Light object, named "name", from the current one.
  21213. * @param name The name of the cloned light
  21214. * @returns the new created light
  21215. */
  21216. Light.prototype.clone = function (name) {
  21217. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21218. if (!constructor) {
  21219. return null;
  21220. }
  21221. return BABYLON.SerializationHelper.Clone(constructor, this);
  21222. };
  21223. /**
  21224. * Serializes the current light into a Serialization object.
  21225. * @returns the serialized object.
  21226. */
  21227. Light.prototype.serialize = function () {
  21228. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21229. // Type
  21230. serializationObject.type = this.getTypeID();
  21231. // Parent
  21232. if (this.parent) {
  21233. serializationObject.parentId = this.parent.id;
  21234. }
  21235. // Inclusion / exclusions
  21236. if (this.excludedMeshes.length > 0) {
  21237. serializationObject.excludedMeshesIds = [];
  21238. this.excludedMeshes.forEach(function (mesh) {
  21239. serializationObject.excludedMeshesIds.push(mesh.id);
  21240. });
  21241. }
  21242. if (this.includedOnlyMeshes.length > 0) {
  21243. serializationObject.includedOnlyMeshesIds = [];
  21244. this.includedOnlyMeshes.forEach(function (mesh) {
  21245. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21246. });
  21247. }
  21248. // Animations
  21249. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21250. serializationObject.ranges = this.serializeAnimationRanges();
  21251. return serializationObject;
  21252. };
  21253. /**
  21254. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21255. * This new light is named "name" and added to the passed scene.
  21256. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21257. * @param name The friendly name of the light
  21258. * @param scene The scene the new light will belong to
  21259. * @returns the constructor function
  21260. */
  21261. Light.GetConstructorFromName = function (type, name, scene) {
  21262. switch (type) {
  21263. case 0:
  21264. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21265. case 1:
  21266. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21267. case 2:
  21268. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21269. case 3:
  21270. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21271. }
  21272. return null;
  21273. };
  21274. /**
  21275. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21276. * @param parsedLight The JSON representation of the light
  21277. * @param scene The scene to create the parsed light in
  21278. * @returns the created light after parsing
  21279. */
  21280. Light.Parse = function (parsedLight, scene) {
  21281. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21282. if (!constructor) {
  21283. return null;
  21284. }
  21285. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21286. // Inclusion / exclusions
  21287. if (parsedLight.excludedMeshesIds) {
  21288. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21289. }
  21290. if (parsedLight.includedOnlyMeshesIds) {
  21291. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21292. }
  21293. // Parent
  21294. if (parsedLight.parentId) {
  21295. light._waitingParentId = parsedLight.parentId;
  21296. }
  21297. // Animations
  21298. if (parsedLight.animations) {
  21299. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21300. var parsedAnimation = parsedLight.animations[animationIndex];
  21301. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21302. }
  21303. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21304. }
  21305. if (parsedLight.autoAnimate) {
  21306. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21307. }
  21308. return light;
  21309. };
  21310. Light.prototype._hookArrayForExcluded = function (array) {
  21311. var _this = this;
  21312. var oldPush = array.push;
  21313. array.push = function () {
  21314. var items = [];
  21315. for (var _i = 0; _i < arguments.length; _i++) {
  21316. items[_i] = arguments[_i];
  21317. }
  21318. var result = oldPush.apply(array, items);
  21319. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21320. var item = items_1[_a];
  21321. item._resyncLighSource(_this);
  21322. }
  21323. return result;
  21324. };
  21325. var oldSplice = array.splice;
  21326. array.splice = function (index, deleteCount) {
  21327. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21328. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21329. var item = deleted_1[_i];
  21330. item._resyncLighSource(_this);
  21331. }
  21332. return deleted;
  21333. };
  21334. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21335. var item = array_1[_i];
  21336. item._resyncLighSource(this);
  21337. }
  21338. };
  21339. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21340. var _this = this;
  21341. var oldPush = array.push;
  21342. array.push = function () {
  21343. var items = [];
  21344. for (var _i = 0; _i < arguments.length; _i++) {
  21345. items[_i] = arguments[_i];
  21346. }
  21347. var result = oldPush.apply(array, items);
  21348. _this._resyncMeshes();
  21349. return result;
  21350. };
  21351. var oldSplice = array.splice;
  21352. array.splice = function (index, deleteCount) {
  21353. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21354. _this._resyncMeshes();
  21355. return deleted;
  21356. };
  21357. this._resyncMeshes();
  21358. };
  21359. Light.prototype._resyncMeshes = function () {
  21360. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21361. var mesh = _a[_i];
  21362. mesh._resyncLighSource(this);
  21363. }
  21364. };
  21365. /**
  21366. * Forces the meshes to update their light related information in their rendering used effects
  21367. * @ignore Internal Use Only
  21368. */
  21369. Light.prototype._markMeshesAsLightDirty = function () {
  21370. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21371. var mesh = _a[_i];
  21372. if (mesh._lightSources.indexOf(this) !== -1) {
  21373. mesh._markSubMeshesAsLightDirty();
  21374. }
  21375. }
  21376. };
  21377. /**
  21378. * Recomputes the cached photometric scale if needed.
  21379. */
  21380. Light.prototype._computePhotometricScale = function () {
  21381. this._photometricScale = this._getPhotometricScale();
  21382. this.getScene().resetCachedMaterial();
  21383. };
  21384. /**
  21385. * Returns the Photometric Scale according to the light type and intensity mode.
  21386. */
  21387. Light.prototype._getPhotometricScale = function () {
  21388. var photometricScale = 0.0;
  21389. var lightTypeID = this.getTypeID();
  21390. //get photometric mode
  21391. var photometricMode = this.intensityMode;
  21392. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21393. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21394. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21395. }
  21396. else {
  21397. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21398. }
  21399. }
  21400. //compute photometric scale
  21401. switch (lightTypeID) {
  21402. case Light.LIGHTTYPEID_POINTLIGHT:
  21403. case Light.LIGHTTYPEID_SPOTLIGHT:
  21404. switch (photometricMode) {
  21405. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21406. photometricScale = 1.0 / (4.0 * Math.PI);
  21407. break;
  21408. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21409. photometricScale = 1.0;
  21410. break;
  21411. case Light.INTENSITYMODE_LUMINANCE:
  21412. photometricScale = this.radius * this.radius;
  21413. break;
  21414. }
  21415. break;
  21416. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21417. switch (photometricMode) {
  21418. case Light.INTENSITYMODE_ILLUMINANCE:
  21419. photometricScale = 1.0;
  21420. break;
  21421. case Light.INTENSITYMODE_LUMINANCE:
  21422. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21423. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21424. var apexAngleRadians = this.radius;
  21425. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21426. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21427. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21428. photometricScale = solidAngle;
  21429. break;
  21430. }
  21431. break;
  21432. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21433. // No fall off in hemisperic light.
  21434. photometricScale = 1.0;
  21435. break;
  21436. }
  21437. return photometricScale;
  21438. };
  21439. /**
  21440. * Reorder the light in the scene according to their defined priority.
  21441. * @ignore Internal Use Only
  21442. */
  21443. Light.prototype._reorderLightsInScene = function () {
  21444. var scene = this.getScene();
  21445. if (this._renderPriority != 0) {
  21446. scene.requireLightSorting = true;
  21447. }
  21448. this.getScene().sortLightsByPriority();
  21449. };
  21450. //lightmapMode Consts
  21451. Light._LIGHTMAP_DEFAULT = 0;
  21452. Light._LIGHTMAP_SPECULAR = 1;
  21453. Light._LIGHTMAP_SHADOWSONLY = 2;
  21454. // Intensity Mode Consts
  21455. Light._INTENSITYMODE_AUTOMATIC = 0;
  21456. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21457. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21458. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21459. Light._INTENSITYMODE_LUMINANCE = 4;
  21460. // Light types ids const.
  21461. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21462. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21463. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21464. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21465. __decorate([
  21466. BABYLON.serializeAsColor3()
  21467. ], Light.prototype, "diffuse", void 0);
  21468. __decorate([
  21469. BABYLON.serializeAsColor3()
  21470. ], Light.prototype, "specular", void 0);
  21471. __decorate([
  21472. BABYLON.serialize()
  21473. ], Light.prototype, "intensity", void 0);
  21474. __decorate([
  21475. BABYLON.serialize()
  21476. ], Light.prototype, "range", void 0);
  21477. __decorate([
  21478. BABYLON.serialize()
  21479. ], Light.prototype, "intensityMode", null);
  21480. __decorate([
  21481. BABYLON.serialize()
  21482. ], Light.prototype, "radius", null);
  21483. __decorate([
  21484. BABYLON.serialize()
  21485. ], Light.prototype, "_renderPriority", void 0);
  21486. __decorate([
  21487. BABYLON.expandToProperty("_reorderLightsInScene")
  21488. ], Light.prototype, "renderPriority", void 0);
  21489. __decorate([
  21490. BABYLON.serialize()
  21491. ], Light.prototype, "shadowEnabled", void 0);
  21492. __decorate([
  21493. BABYLON.serialize("excludeWithLayerMask")
  21494. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21495. __decorate([
  21496. BABYLON.serialize("includeOnlyWithLayerMask")
  21497. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21498. __decorate([
  21499. BABYLON.serialize("lightmapMode")
  21500. ], Light.prototype, "_lightmapMode", void 0);
  21501. return Light;
  21502. }(BABYLON.Node));
  21503. BABYLON.Light = Light;
  21504. })(BABYLON || (BABYLON = {}));
  21505. //# sourceMappingURL=babylon.light.js.map
  21506. "use strict";
  21507. var BABYLON;
  21508. (function (BABYLON) {
  21509. var Camera = /** @class */ (function (_super) {
  21510. __extends(Camera, _super);
  21511. function Camera(name, position, scene) {
  21512. var _this = _super.call(this, name, scene) || this;
  21513. /**
  21514. * The vector the camera should consider as up.
  21515. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21516. */
  21517. _this.upVector = BABYLON.Vector3.Up();
  21518. _this.orthoLeft = null;
  21519. _this.orthoRight = null;
  21520. _this.orthoBottom = null;
  21521. _this.orthoTop = null;
  21522. /**
  21523. * FOV is set in Radians. (default is 0.8)
  21524. */
  21525. _this.fov = 0.8;
  21526. _this.minZ = 1;
  21527. _this.maxZ = 10000.0;
  21528. _this.inertia = 0.9;
  21529. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21530. _this.isIntermediate = false;
  21531. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21532. /**
  21533. * Restricts the camera to viewing objects with the same layerMask.
  21534. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21535. */
  21536. _this.layerMask = 0x0FFFFFFF;
  21537. /**
  21538. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21539. */
  21540. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21541. // Camera rig members
  21542. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21543. _this._rigCameras = new Array();
  21544. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21545. _this._skipRendering = false;
  21546. _this.customRenderTargets = new Array();
  21547. // Observables
  21548. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21549. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21550. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21551. _this.onRestoreStateObservable = new BABYLON.Observable();
  21552. // Cache
  21553. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21554. _this._projectionMatrix = new BABYLON.Matrix();
  21555. _this._doNotComputeProjectionMatrix = false;
  21556. _this._postProcesses = new Array();
  21557. _this._transformMatrix = BABYLON.Matrix.Zero();
  21558. _this._activeMeshes = new BABYLON.SmartArray(256);
  21559. _this._globalPosition = BABYLON.Vector3.Zero();
  21560. _this._refreshFrustumPlanes = true;
  21561. _this.getScene().addCamera(_this);
  21562. if (!_this.getScene().activeCamera) {
  21563. _this.getScene().activeCamera = _this;
  21564. }
  21565. _this.position = position;
  21566. return _this;
  21567. }
  21568. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21569. get: function () {
  21570. return Camera._PERSPECTIVE_CAMERA;
  21571. },
  21572. enumerable: true,
  21573. configurable: true
  21574. });
  21575. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21576. get: function () {
  21577. return Camera._ORTHOGRAPHIC_CAMERA;
  21578. },
  21579. enumerable: true,
  21580. configurable: true
  21581. });
  21582. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21583. /**
  21584. * This is the default FOV mode for perspective cameras.
  21585. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21586. *
  21587. */
  21588. get: function () {
  21589. return Camera._FOVMODE_VERTICAL_FIXED;
  21590. },
  21591. enumerable: true,
  21592. configurable: true
  21593. });
  21594. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21595. /**
  21596. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21597. *
  21598. */
  21599. get: function () {
  21600. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21601. },
  21602. enumerable: true,
  21603. configurable: true
  21604. });
  21605. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21606. get: function () {
  21607. return Camera._RIG_MODE_NONE;
  21608. },
  21609. enumerable: true,
  21610. configurable: true
  21611. });
  21612. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  21613. get: function () {
  21614. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  21615. },
  21616. enumerable: true,
  21617. configurable: true
  21618. });
  21619. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  21620. get: function () {
  21621. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  21622. },
  21623. enumerable: true,
  21624. configurable: true
  21625. });
  21626. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  21627. get: function () {
  21628. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21629. },
  21630. enumerable: true,
  21631. configurable: true
  21632. });
  21633. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  21634. get: function () {
  21635. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  21636. },
  21637. enumerable: true,
  21638. configurable: true
  21639. });
  21640. Object.defineProperty(Camera, "RIG_MODE_VR", {
  21641. get: function () {
  21642. return Camera._RIG_MODE_VR;
  21643. },
  21644. enumerable: true,
  21645. configurable: true
  21646. });
  21647. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  21648. get: function () {
  21649. return Camera._RIG_MODE_WEBVR;
  21650. },
  21651. enumerable: true,
  21652. configurable: true
  21653. });
  21654. /**
  21655. * Store current camera state (fov, position, etc..)
  21656. */
  21657. Camera.prototype.storeState = function () {
  21658. this._stateStored = true;
  21659. this._storedFov = this.fov;
  21660. return this;
  21661. };
  21662. /**
  21663. * Restores the camera state values if it has been stored. You must call storeState() first
  21664. */
  21665. Camera.prototype._restoreStateValues = function () {
  21666. if (!this._stateStored) {
  21667. return false;
  21668. }
  21669. this.fov = this._storedFov;
  21670. return true;
  21671. };
  21672. /**
  21673. * Restored camera state. You must call storeState() first
  21674. */
  21675. Camera.prototype.restoreState = function () {
  21676. if (this._restoreStateValues()) {
  21677. this.onRestoreStateObservable.notifyObservers(this);
  21678. return true;
  21679. }
  21680. return false;
  21681. };
  21682. Camera.prototype.getClassName = function () {
  21683. return "Camera";
  21684. };
  21685. /**
  21686. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21687. */
  21688. Camera.prototype.toString = function (fullDetails) {
  21689. var ret = "Name: " + this.name;
  21690. ret += ", type: " + this.getClassName();
  21691. if (this.animations) {
  21692. for (var i = 0; i < this.animations.length; i++) {
  21693. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21694. }
  21695. }
  21696. if (fullDetails) {
  21697. }
  21698. return ret;
  21699. };
  21700. Object.defineProperty(Camera.prototype, "globalPosition", {
  21701. get: function () {
  21702. return this._globalPosition;
  21703. },
  21704. enumerable: true,
  21705. configurable: true
  21706. });
  21707. Camera.prototype.getActiveMeshes = function () {
  21708. return this._activeMeshes;
  21709. };
  21710. Camera.prototype.isActiveMesh = function (mesh) {
  21711. return (this._activeMeshes.indexOf(mesh) !== -1);
  21712. };
  21713. /**
  21714. * Is this camera ready to be used/rendered
  21715. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  21716. * @return true if the camera is ready
  21717. */
  21718. Camera.prototype.isReady = function (completeCheck) {
  21719. if (completeCheck === void 0) { completeCheck = false; }
  21720. if (completeCheck) {
  21721. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  21722. var pp = _a[_i];
  21723. if (pp && !pp.isReady()) {
  21724. return false;
  21725. }
  21726. }
  21727. }
  21728. return _super.prototype.isReady.call(this, completeCheck);
  21729. };
  21730. //Cache
  21731. Camera.prototype._initCache = function () {
  21732. _super.prototype._initCache.call(this);
  21733. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21734. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21735. this._cache.mode = undefined;
  21736. this._cache.minZ = undefined;
  21737. this._cache.maxZ = undefined;
  21738. this._cache.fov = undefined;
  21739. this._cache.fovMode = undefined;
  21740. this._cache.aspectRatio = undefined;
  21741. this._cache.orthoLeft = undefined;
  21742. this._cache.orthoRight = undefined;
  21743. this._cache.orthoBottom = undefined;
  21744. this._cache.orthoTop = undefined;
  21745. this._cache.renderWidth = undefined;
  21746. this._cache.renderHeight = undefined;
  21747. };
  21748. Camera.prototype._updateCache = function (ignoreParentClass) {
  21749. if (!ignoreParentClass) {
  21750. _super.prototype._updateCache.call(this);
  21751. }
  21752. this._cache.position.copyFrom(this.position);
  21753. this._cache.upVector.copyFrom(this.upVector);
  21754. };
  21755. // Synchronized
  21756. Camera.prototype._isSynchronized = function () {
  21757. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  21758. };
  21759. Camera.prototype._isSynchronizedViewMatrix = function () {
  21760. if (!_super.prototype._isSynchronized.call(this))
  21761. return false;
  21762. return this._cache.position.equals(this.position)
  21763. && this._cache.upVector.equals(this.upVector)
  21764. && this.isSynchronizedWithParent();
  21765. };
  21766. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  21767. var check = this._cache.mode === this.mode
  21768. && this._cache.minZ === this.minZ
  21769. && this._cache.maxZ === this.maxZ;
  21770. if (!check) {
  21771. return false;
  21772. }
  21773. var engine = this.getEngine();
  21774. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  21775. check = this._cache.fov === this.fov
  21776. && this._cache.fovMode === this.fovMode
  21777. && this._cache.aspectRatio === engine.getAspectRatio(this);
  21778. }
  21779. else {
  21780. check = this._cache.orthoLeft === this.orthoLeft
  21781. && this._cache.orthoRight === this.orthoRight
  21782. && this._cache.orthoBottom === this.orthoBottom
  21783. && this._cache.orthoTop === this.orthoTop
  21784. && this._cache.renderWidth === engine.getRenderWidth()
  21785. && this._cache.renderHeight === engine.getRenderHeight();
  21786. }
  21787. return check;
  21788. };
  21789. // Controls
  21790. Camera.prototype.attachControl = function (element, noPreventDefault) {
  21791. };
  21792. Camera.prototype.detachControl = function (element) {
  21793. };
  21794. Camera.prototype.update = function () {
  21795. this._checkInputs();
  21796. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21797. this._updateRigCameras();
  21798. }
  21799. };
  21800. Camera.prototype._checkInputs = function () {
  21801. this.onAfterCheckInputsObservable.notifyObservers(this);
  21802. };
  21803. Object.defineProperty(Camera.prototype, "rigCameras", {
  21804. get: function () {
  21805. return this._rigCameras;
  21806. },
  21807. enumerable: true,
  21808. configurable: true
  21809. });
  21810. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  21811. get: function () {
  21812. return this._rigPostProcess;
  21813. },
  21814. enumerable: true,
  21815. configurable: true
  21816. });
  21817. /**
  21818. * Internal, gets the first post proces.
  21819. * @returns the first post process to be run on this camera.
  21820. */
  21821. Camera.prototype._getFirstPostProcess = function () {
  21822. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  21823. if (this._postProcesses[ppIndex] !== null) {
  21824. return this._postProcesses[ppIndex];
  21825. }
  21826. }
  21827. return null;
  21828. };
  21829. Camera.prototype._cascadePostProcessesToRigCams = function () {
  21830. // invalidate framebuffer
  21831. var firstPostProcess = this._getFirstPostProcess();
  21832. if (firstPostProcess) {
  21833. firstPostProcess.markTextureDirty();
  21834. }
  21835. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  21836. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  21837. var cam = this._rigCameras[i];
  21838. var rigPostProcess = cam._rigPostProcess;
  21839. // for VR rig, there does not have to be a post process
  21840. if (rigPostProcess) {
  21841. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  21842. if (isPass) {
  21843. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  21844. cam.isIntermediate = this._postProcesses.length === 0;
  21845. }
  21846. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  21847. rigPostProcess.markTextureDirty();
  21848. }
  21849. else {
  21850. cam._postProcesses = this._postProcesses.slice(0);
  21851. }
  21852. }
  21853. };
  21854. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  21855. if (insertAt === void 0) { insertAt = null; }
  21856. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  21857. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  21858. return 0;
  21859. }
  21860. if (insertAt == null || insertAt < 0) {
  21861. this._postProcesses.push(postProcess);
  21862. }
  21863. else if (this._postProcesses[insertAt] === null) {
  21864. this._postProcesses[insertAt] = postProcess;
  21865. }
  21866. else {
  21867. this._postProcesses.splice(insertAt, 0, postProcess);
  21868. }
  21869. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  21870. return this._postProcesses.indexOf(postProcess);
  21871. };
  21872. Camera.prototype.detachPostProcess = function (postProcess) {
  21873. var idx = this._postProcesses.indexOf(postProcess);
  21874. if (idx !== -1) {
  21875. this._postProcesses[idx] = null;
  21876. }
  21877. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  21878. };
  21879. Camera.prototype.getWorldMatrix = function () {
  21880. if (!this._worldMatrix) {
  21881. this._worldMatrix = BABYLON.Matrix.Identity();
  21882. }
  21883. var viewMatrix = this.getViewMatrix();
  21884. viewMatrix.invertToRef(this._worldMatrix);
  21885. return this._worldMatrix;
  21886. };
  21887. Camera.prototype._getViewMatrix = function () {
  21888. return BABYLON.Matrix.Identity();
  21889. };
  21890. Camera.prototype.getViewMatrix = function (force) {
  21891. if (!force && this._isSynchronizedViewMatrix()) {
  21892. return this._computedViewMatrix;
  21893. }
  21894. this.updateCache();
  21895. this._computedViewMatrix = this._getViewMatrix();
  21896. this._currentRenderId = this.getScene().getRenderId();
  21897. this._childRenderId = this._currentRenderId;
  21898. this._refreshFrustumPlanes = true;
  21899. if (!this.parent || !this.parent.getWorldMatrix) {
  21900. this._globalPosition.copyFrom(this.position);
  21901. }
  21902. else {
  21903. if (!this._worldMatrix) {
  21904. this._worldMatrix = BABYLON.Matrix.Identity();
  21905. }
  21906. this._computedViewMatrix.invertToRef(this._worldMatrix);
  21907. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  21908. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  21909. this._computedViewMatrix.invert();
  21910. this._markSyncedWithParent();
  21911. }
  21912. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  21913. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  21914. }
  21915. this.onViewMatrixChangedObservable.notifyObservers(this);
  21916. return this._computedViewMatrix;
  21917. };
  21918. Camera.prototype.freezeProjectionMatrix = function (projection) {
  21919. this._doNotComputeProjectionMatrix = true;
  21920. if (projection !== undefined) {
  21921. this._projectionMatrix = projection;
  21922. }
  21923. };
  21924. ;
  21925. Camera.prototype.unfreezeProjectionMatrix = function () {
  21926. this._doNotComputeProjectionMatrix = false;
  21927. };
  21928. ;
  21929. Camera.prototype.getProjectionMatrix = function (force) {
  21930. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  21931. return this._projectionMatrix;
  21932. }
  21933. // Cache
  21934. this._cache.mode = this.mode;
  21935. this._cache.minZ = this.minZ;
  21936. this._cache.maxZ = this.maxZ;
  21937. // Matrix
  21938. this._refreshFrustumPlanes = true;
  21939. var engine = this.getEngine();
  21940. var scene = this.getScene();
  21941. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  21942. this._cache.fov = this.fov;
  21943. this._cache.fovMode = this.fovMode;
  21944. this._cache.aspectRatio = engine.getAspectRatio(this);
  21945. if (this.minZ <= 0) {
  21946. this.minZ = 0.1;
  21947. }
  21948. if (scene.useRightHandedSystem) {
  21949. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  21950. }
  21951. else {
  21952. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  21953. }
  21954. }
  21955. else {
  21956. var halfWidth = engine.getRenderWidth() / 2.0;
  21957. var halfHeight = engine.getRenderHeight() / 2.0;
  21958. if (scene.useRightHandedSystem) {
  21959. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  21960. }
  21961. else {
  21962. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  21963. }
  21964. this._cache.orthoLeft = this.orthoLeft;
  21965. this._cache.orthoRight = this.orthoRight;
  21966. this._cache.orthoBottom = this.orthoBottom;
  21967. this._cache.orthoTop = this.orthoTop;
  21968. this._cache.renderWidth = engine.getRenderWidth();
  21969. this._cache.renderHeight = engine.getRenderHeight();
  21970. }
  21971. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  21972. return this._projectionMatrix;
  21973. };
  21974. Camera.prototype.getTranformationMatrix = function () {
  21975. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21976. return this._transformMatrix;
  21977. };
  21978. Camera.prototype.updateFrustumPlanes = function () {
  21979. if (!this._refreshFrustumPlanes) {
  21980. return;
  21981. }
  21982. this.getTranformationMatrix();
  21983. if (!this._frustumPlanes) {
  21984. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21985. }
  21986. else {
  21987. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21988. }
  21989. this._refreshFrustumPlanes = false;
  21990. };
  21991. Camera.prototype.isInFrustum = function (target) {
  21992. this.updateFrustumPlanes();
  21993. return target.isInFrustum(this._frustumPlanes);
  21994. };
  21995. Camera.prototype.isCompletelyInFrustum = function (target) {
  21996. this.updateFrustumPlanes();
  21997. return target.isCompletelyInFrustum(this._frustumPlanes);
  21998. };
  21999. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22000. if (length === void 0) { length = 100; }
  22001. if (!transform) {
  22002. transform = this.getWorldMatrix();
  22003. }
  22004. if (!origin) {
  22005. origin = this.position;
  22006. }
  22007. var forward = new BABYLON.Vector3(0, 0, 1);
  22008. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22009. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22010. return new BABYLON.Ray(origin, direction, length);
  22011. };
  22012. /**
  22013. * Releases resources associated with this node.
  22014. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22015. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22016. */
  22017. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22018. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22019. // Observables
  22020. this.onViewMatrixChangedObservable.clear();
  22021. this.onProjectionMatrixChangedObservable.clear();
  22022. this.onAfterCheckInputsObservable.clear();
  22023. this.onRestoreStateObservable.clear();
  22024. // Inputs
  22025. if (this.inputs) {
  22026. this.inputs.clear();
  22027. }
  22028. // Animations
  22029. this.getScene().stopAnimation(this);
  22030. // Remove from scene
  22031. this.getScene().removeCamera(this);
  22032. while (this._rigCameras.length > 0) {
  22033. var camera = this._rigCameras.pop();
  22034. if (camera) {
  22035. camera.dispose();
  22036. }
  22037. }
  22038. // Postprocesses
  22039. if (this._rigPostProcess) {
  22040. this._rigPostProcess.dispose(this);
  22041. this._rigPostProcess = null;
  22042. this._postProcesses = [];
  22043. }
  22044. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22045. this._rigPostProcess = null;
  22046. this._postProcesses = [];
  22047. }
  22048. else {
  22049. var i = this._postProcesses.length;
  22050. while (--i >= 0) {
  22051. var postProcess = this._postProcesses[i];
  22052. if (postProcess) {
  22053. postProcess.dispose(this);
  22054. }
  22055. }
  22056. }
  22057. // Render targets
  22058. var i = this.customRenderTargets.length;
  22059. while (--i >= 0) {
  22060. this.customRenderTargets[i].dispose();
  22061. }
  22062. this.customRenderTargets = [];
  22063. // Active Meshes
  22064. this._activeMeshes.dispose();
  22065. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22066. };
  22067. Object.defineProperty(Camera.prototype, "leftCamera", {
  22068. // ---- Camera rigs section ----
  22069. get: function () {
  22070. if (this._rigCameras.length < 1) {
  22071. return null;
  22072. }
  22073. return this._rigCameras[0];
  22074. },
  22075. enumerable: true,
  22076. configurable: true
  22077. });
  22078. Object.defineProperty(Camera.prototype, "rightCamera", {
  22079. get: function () {
  22080. if (this._rigCameras.length < 2) {
  22081. return null;
  22082. }
  22083. return this._rigCameras[1];
  22084. },
  22085. enumerable: true,
  22086. configurable: true
  22087. });
  22088. Camera.prototype.getLeftTarget = function () {
  22089. if (this._rigCameras.length < 1) {
  22090. return null;
  22091. }
  22092. return this._rigCameras[0].getTarget();
  22093. };
  22094. Camera.prototype.getRightTarget = function () {
  22095. if (this._rigCameras.length < 2) {
  22096. return null;
  22097. }
  22098. return this._rigCameras[1].getTarget();
  22099. };
  22100. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22101. if (this.cameraRigMode === mode) {
  22102. return;
  22103. }
  22104. while (this._rigCameras.length > 0) {
  22105. var camera = this._rigCameras.pop();
  22106. if (camera) {
  22107. camera.dispose();
  22108. }
  22109. }
  22110. this.cameraRigMode = mode;
  22111. this._cameraRigParams = {};
  22112. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22113. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22114. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22115. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22116. // create the rig cameras, unless none
  22117. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22118. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22119. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22120. if (leftCamera && rightCamera) {
  22121. this._rigCameras.push(leftCamera);
  22122. this._rigCameras.push(rightCamera);
  22123. }
  22124. }
  22125. switch (this.cameraRigMode) {
  22126. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22127. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22128. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22129. break;
  22130. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22131. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22132. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22133. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22134. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22135. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22136. break;
  22137. case Camera.RIG_MODE_VR:
  22138. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22139. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22140. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22141. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22142. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22143. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22144. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22145. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22146. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22147. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22148. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22149. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22150. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22151. if (metrics.compensateDistortion) {
  22152. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22153. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22154. }
  22155. break;
  22156. case Camera.RIG_MODE_WEBVR:
  22157. if (rigParams.vrDisplay) {
  22158. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22159. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22160. //Left eye
  22161. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22162. this._rigCameras[0].setCameraRigParameter("left", true);
  22163. //leaving this for future reference
  22164. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22165. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22166. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22167. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22168. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22169. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22170. this._rigCameras[0].parent = this;
  22171. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22172. //Right eye
  22173. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22174. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22175. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22176. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22177. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22178. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22179. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22180. this._rigCameras[1].parent = this;
  22181. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22182. if (Camera.UseAlternateWebVRRendering) {
  22183. this._rigCameras[1]._skipRendering = true;
  22184. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22185. }
  22186. }
  22187. break;
  22188. }
  22189. this._cascadePostProcessesToRigCams();
  22190. this.update();
  22191. };
  22192. Camera.prototype._getVRProjectionMatrix = function () {
  22193. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22194. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22195. return this._projectionMatrix;
  22196. };
  22197. Camera.prototype._updateCameraRotationMatrix = function () {
  22198. //Here for WebVR
  22199. };
  22200. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22201. //Here for WebVR
  22202. };
  22203. /**
  22204. * This function MUST be overwritten by the different WebVR cameras available.
  22205. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22206. */
  22207. Camera.prototype._getWebVRProjectionMatrix = function () {
  22208. return BABYLON.Matrix.Identity();
  22209. };
  22210. /**
  22211. * This function MUST be overwritten by the different WebVR cameras available.
  22212. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22213. */
  22214. Camera.prototype._getWebVRViewMatrix = function () {
  22215. return BABYLON.Matrix.Identity();
  22216. };
  22217. Camera.prototype.setCameraRigParameter = function (name, value) {
  22218. if (!this._cameraRigParams) {
  22219. this._cameraRigParams = {};
  22220. }
  22221. this._cameraRigParams[name] = value;
  22222. //provisionnally:
  22223. if (name === "interaxialDistance") {
  22224. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22225. }
  22226. };
  22227. /**
  22228. * needs to be overridden by children so sub has required properties to be copied
  22229. */
  22230. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22231. return null;
  22232. };
  22233. /**
  22234. * May need to be overridden by children
  22235. */
  22236. Camera.prototype._updateRigCameras = function () {
  22237. for (var i = 0; i < this._rigCameras.length; i++) {
  22238. this._rigCameras[i].minZ = this.minZ;
  22239. this._rigCameras[i].maxZ = this.maxZ;
  22240. this._rigCameras[i].fov = this.fov;
  22241. }
  22242. // only update viewport when ANAGLYPH
  22243. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22244. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22245. }
  22246. };
  22247. Camera.prototype._setupInputs = function () {
  22248. };
  22249. Camera.prototype.serialize = function () {
  22250. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22251. // Type
  22252. serializationObject.type = this.getClassName();
  22253. // Parent
  22254. if (this.parent) {
  22255. serializationObject.parentId = this.parent.id;
  22256. }
  22257. if (this.inputs) {
  22258. this.inputs.serialize(serializationObject);
  22259. }
  22260. // Animations
  22261. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22262. serializationObject.ranges = this.serializeAnimationRanges();
  22263. return serializationObject;
  22264. };
  22265. Camera.prototype.clone = function (name) {
  22266. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22267. };
  22268. Camera.prototype.getDirection = function (localAxis) {
  22269. var result = BABYLON.Vector3.Zero();
  22270. this.getDirectionToRef(localAxis, result);
  22271. return result;
  22272. };
  22273. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22274. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22275. };
  22276. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22277. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22278. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22279. switch (type) {
  22280. case "ArcRotateCamera":
  22281. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22282. case "DeviceOrientationCamera":
  22283. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22284. case "FollowCamera":
  22285. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22286. case "ArcFollowCamera":
  22287. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22288. case "GamepadCamera":
  22289. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22290. case "TouchCamera":
  22291. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22292. case "VirtualJoysticksCamera":
  22293. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22294. case "WebVRFreeCamera":
  22295. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22296. case "WebVRGamepadCamera":
  22297. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22298. case "VRDeviceOrientationFreeCamera":
  22299. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22300. case "VRDeviceOrientationGamepadCamera":
  22301. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22302. case "AnaglyphArcRotateCamera":
  22303. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22304. case "AnaglyphFreeCamera":
  22305. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22306. case "AnaglyphGamepadCamera":
  22307. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22308. case "AnaglyphUniversalCamera":
  22309. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22310. case "StereoscopicArcRotateCamera":
  22311. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22312. case "StereoscopicFreeCamera":
  22313. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22314. case "StereoscopicGamepadCamera":
  22315. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22316. case "StereoscopicUniversalCamera":
  22317. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22318. case "FreeCamera":// Forcing Universal here
  22319. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22320. default:// Universal Camera is the default value
  22321. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22322. }
  22323. };
  22324. Camera.prototype.computeWorldMatrix = function () {
  22325. return this.getWorldMatrix();
  22326. };
  22327. Camera.Parse = function (parsedCamera, scene) {
  22328. var type = parsedCamera.type;
  22329. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22330. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22331. // Parent
  22332. if (parsedCamera.parentId) {
  22333. camera._waitingParentId = parsedCamera.parentId;
  22334. }
  22335. //If camera has an input manager, let it parse inputs settings
  22336. if (camera.inputs) {
  22337. camera.inputs.parse(parsedCamera);
  22338. camera._setupInputs();
  22339. }
  22340. if (camera.setPosition) {
  22341. camera.position.copyFromFloats(0, 0, 0);
  22342. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22343. }
  22344. // Target
  22345. if (parsedCamera.target) {
  22346. if (camera.setTarget) {
  22347. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22348. }
  22349. }
  22350. // Apply 3d rig, when found
  22351. if (parsedCamera.cameraRigMode) {
  22352. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22353. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22354. }
  22355. // Animations
  22356. if (parsedCamera.animations) {
  22357. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22358. var parsedAnimation = parsedCamera.animations[animationIndex];
  22359. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22360. }
  22361. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22362. }
  22363. if (parsedCamera.autoAnimate) {
  22364. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22365. }
  22366. return camera;
  22367. };
  22368. // Statics
  22369. Camera._PERSPECTIVE_CAMERA = 0;
  22370. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22371. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22372. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22373. Camera._RIG_MODE_NONE = 0;
  22374. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22375. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22376. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22377. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22378. Camera._RIG_MODE_VR = 20;
  22379. Camera._RIG_MODE_WEBVR = 21;
  22380. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22381. Camera.UseAlternateWebVRRendering = false;
  22382. __decorate([
  22383. BABYLON.serializeAsVector3()
  22384. ], Camera.prototype, "position", void 0);
  22385. __decorate([
  22386. BABYLON.serializeAsVector3()
  22387. ], Camera.prototype, "upVector", void 0);
  22388. __decorate([
  22389. BABYLON.serialize()
  22390. ], Camera.prototype, "orthoLeft", void 0);
  22391. __decorate([
  22392. BABYLON.serialize()
  22393. ], Camera.prototype, "orthoRight", void 0);
  22394. __decorate([
  22395. BABYLON.serialize()
  22396. ], Camera.prototype, "orthoBottom", void 0);
  22397. __decorate([
  22398. BABYLON.serialize()
  22399. ], Camera.prototype, "orthoTop", void 0);
  22400. __decorate([
  22401. BABYLON.serialize()
  22402. ], Camera.prototype, "fov", void 0);
  22403. __decorate([
  22404. BABYLON.serialize()
  22405. ], Camera.prototype, "minZ", void 0);
  22406. __decorate([
  22407. BABYLON.serialize()
  22408. ], Camera.prototype, "maxZ", void 0);
  22409. __decorate([
  22410. BABYLON.serialize()
  22411. ], Camera.prototype, "inertia", void 0);
  22412. __decorate([
  22413. BABYLON.serialize()
  22414. ], Camera.prototype, "mode", void 0);
  22415. __decorate([
  22416. BABYLON.serialize()
  22417. ], Camera.prototype, "layerMask", void 0);
  22418. __decorate([
  22419. BABYLON.serialize()
  22420. ], Camera.prototype, "fovMode", void 0);
  22421. __decorate([
  22422. BABYLON.serialize()
  22423. ], Camera.prototype, "cameraRigMode", void 0);
  22424. __decorate([
  22425. BABYLON.serialize()
  22426. ], Camera.prototype, "interaxialDistance", void 0);
  22427. __decorate([
  22428. BABYLON.serialize()
  22429. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22430. return Camera;
  22431. }(BABYLON.Node));
  22432. BABYLON.Camera = Camera;
  22433. })(BABYLON || (BABYLON = {}));
  22434. //# sourceMappingURL=babylon.camera.js.map
  22435. "use strict";
  22436. var BABYLON;
  22437. (function (BABYLON) {
  22438. var RenderingManager = /** @class */ (function () {
  22439. function RenderingManager(scene) {
  22440. this._renderingGroups = new Array();
  22441. this._autoClearDepthStencil = {};
  22442. this._customOpaqueSortCompareFn = {};
  22443. this._customAlphaTestSortCompareFn = {};
  22444. this._customTransparentSortCompareFn = {};
  22445. this._renderinGroupInfo = null;
  22446. this._scene = scene;
  22447. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22448. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22449. }
  22450. }
  22451. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22452. if (depth === void 0) { depth = true; }
  22453. if (stencil === void 0) { stencil = true; }
  22454. if (this._depthStencilBufferAlreadyCleaned) {
  22455. return;
  22456. }
  22457. this._scene.getEngine().clear(null, false, depth, stencil);
  22458. this._depthStencilBufferAlreadyCleaned = true;
  22459. };
  22460. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22461. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22462. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22463. var info = null;
  22464. if (observable) {
  22465. if (!this._renderinGroupInfo) {
  22466. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22467. }
  22468. info = this._renderinGroupInfo;
  22469. info.scene = this._scene;
  22470. info.camera = this._scene.activeCamera;
  22471. }
  22472. // Dispatch sprites
  22473. if (renderSprites) {
  22474. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22475. var manager = this._scene.spriteManagers[index];
  22476. this.dispatchSprites(manager);
  22477. }
  22478. }
  22479. // Render
  22480. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22481. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22482. var renderingGroup = this._renderingGroups[index];
  22483. if (!renderingGroup && !observable)
  22484. continue;
  22485. var renderingGroupMask = 0;
  22486. // Fire PRECLEAR stage
  22487. if (observable && info) {
  22488. renderingGroupMask = Math.pow(2, index);
  22489. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22490. info.renderingGroupId = index;
  22491. observable.notifyObservers(info, renderingGroupMask);
  22492. }
  22493. // Clear depth/stencil if needed
  22494. if (RenderingManager.AUTOCLEAR) {
  22495. var autoClear = this._autoClearDepthStencil[index];
  22496. if (autoClear && autoClear.autoClear) {
  22497. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22498. }
  22499. }
  22500. if (observable && info) {
  22501. // Fire PREOPAQUE stage
  22502. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22503. observable.notifyObservers(info, renderingGroupMask);
  22504. // Fire PRETRANSPARENT stage
  22505. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22506. observable.notifyObservers(info, renderingGroupMask);
  22507. }
  22508. if (renderingGroup)
  22509. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22510. // Fire POSTTRANSPARENT stage
  22511. if (observable && info) {
  22512. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22513. observable.notifyObservers(info, renderingGroupMask);
  22514. }
  22515. }
  22516. };
  22517. RenderingManager.prototype.reset = function () {
  22518. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22519. var renderingGroup = this._renderingGroups[index];
  22520. if (renderingGroup) {
  22521. renderingGroup.prepare();
  22522. }
  22523. }
  22524. };
  22525. RenderingManager.prototype.dispose = function () {
  22526. this.freeRenderingGroups();
  22527. this._renderingGroups.length = 0;
  22528. };
  22529. /**
  22530. * Clear the info related to rendering groups preventing retention points during dispose.
  22531. */
  22532. RenderingManager.prototype.freeRenderingGroups = function () {
  22533. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22534. var renderingGroup = this._renderingGroups[index];
  22535. if (renderingGroup) {
  22536. renderingGroup.dispose();
  22537. }
  22538. }
  22539. };
  22540. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22541. if (this._renderingGroups[renderingGroupId] === undefined) {
  22542. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22543. }
  22544. };
  22545. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22546. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22547. this._prepareRenderingGroup(renderingGroupId);
  22548. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22549. };
  22550. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22551. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22552. this._prepareRenderingGroup(renderingGroupId);
  22553. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22554. };
  22555. /**
  22556. * @param subMesh The submesh to dispatch
  22557. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22558. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22559. */
  22560. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22561. if (mesh === undefined) {
  22562. mesh = subMesh.getMesh();
  22563. }
  22564. var renderingGroupId = mesh.renderingGroupId || 0;
  22565. this._prepareRenderingGroup(renderingGroupId);
  22566. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22567. };
  22568. /**
  22569. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22570. * This allowed control for front to back rendering or reversly depending of the special needs.
  22571. *
  22572. * @param renderingGroupId The rendering group id corresponding to its index
  22573. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22574. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22575. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22576. */
  22577. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22578. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22579. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22580. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22581. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22582. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22583. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22584. if (this._renderingGroups[renderingGroupId]) {
  22585. var group = this._renderingGroups[renderingGroupId];
  22586. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22587. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22588. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22589. }
  22590. };
  22591. /**
  22592. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22593. *
  22594. * @param renderingGroupId The rendering group id corresponding to its index
  22595. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22596. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22597. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22598. */
  22599. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22600. if (depth === void 0) { depth = true; }
  22601. if (stencil === void 0) { stencil = true; }
  22602. this._autoClearDepthStencil[renderingGroupId] = {
  22603. autoClear: autoClearDepthStencil,
  22604. depth: depth,
  22605. stencil: stencil
  22606. };
  22607. };
  22608. /**
  22609. * The max id used for rendering groups (not included)
  22610. */
  22611. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22612. /**
  22613. * The min id used for rendering groups (included)
  22614. */
  22615. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22616. /**
  22617. * Used to globally prevent autoclearing scenes.
  22618. */
  22619. RenderingManager.AUTOCLEAR = true;
  22620. return RenderingManager;
  22621. }());
  22622. BABYLON.RenderingManager = RenderingManager;
  22623. })(BABYLON || (BABYLON = {}));
  22624. //# sourceMappingURL=babylon.renderingManager.js.map
  22625. "use strict";
  22626. var BABYLON;
  22627. (function (BABYLON) {
  22628. var RenderingGroup = /** @class */ (function () {
  22629. /**
  22630. * Creates a new rendering group.
  22631. * @param index The rendering group index
  22632. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22633. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22634. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22635. */
  22636. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22637. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22638. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22639. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22640. this.index = index;
  22641. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22642. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22643. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22644. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22645. this._particleSystems = new BABYLON.SmartArray(256);
  22646. this._spriteManagers = new BABYLON.SmartArray(256);
  22647. this._edgesRenderers = new BABYLON.SmartArray(16);
  22648. this._scene = scene;
  22649. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22650. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22651. this.transparentSortCompareFn = transparentSortCompareFn;
  22652. }
  22653. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22654. /**
  22655. * Set the opaque sort comparison function.
  22656. * If null the sub meshes will be render in the order they were created
  22657. */
  22658. set: function (value) {
  22659. this._opaqueSortCompareFn = value;
  22660. if (value) {
  22661. this._renderOpaque = this.renderOpaqueSorted;
  22662. }
  22663. else {
  22664. this._renderOpaque = RenderingGroup.renderUnsorted;
  22665. }
  22666. },
  22667. enumerable: true,
  22668. configurable: true
  22669. });
  22670. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  22671. /**
  22672. * Set the alpha test sort comparison function.
  22673. * If null the sub meshes will be render in the order they were created
  22674. */
  22675. set: function (value) {
  22676. this._alphaTestSortCompareFn = value;
  22677. if (value) {
  22678. this._renderAlphaTest = this.renderAlphaTestSorted;
  22679. }
  22680. else {
  22681. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  22682. }
  22683. },
  22684. enumerable: true,
  22685. configurable: true
  22686. });
  22687. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  22688. /**
  22689. * Set the transparent sort comparison function.
  22690. * If null the sub meshes will be render in the order they were created
  22691. */
  22692. set: function (value) {
  22693. if (value) {
  22694. this._transparentSortCompareFn = value;
  22695. }
  22696. else {
  22697. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  22698. }
  22699. this._renderTransparent = this.renderTransparentSorted;
  22700. },
  22701. enumerable: true,
  22702. configurable: true
  22703. });
  22704. /**
  22705. * Render all the sub meshes contained in the group.
  22706. * @param customRenderFunction Used to override the default render behaviour of the group.
  22707. * @returns true if rendered some submeshes.
  22708. */
  22709. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  22710. if (customRenderFunction) {
  22711. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  22712. return;
  22713. }
  22714. var engine = this._scene.getEngine();
  22715. // Depth only
  22716. if (this._depthOnlySubMeshes.length !== 0) {
  22717. engine.setColorWrite(false);
  22718. this._renderAlphaTest(this._depthOnlySubMeshes);
  22719. engine.setColorWrite(true);
  22720. }
  22721. // Opaque
  22722. if (this._opaqueSubMeshes.length !== 0) {
  22723. this._renderOpaque(this._opaqueSubMeshes);
  22724. }
  22725. // Alpha test
  22726. if (this._alphaTestSubMeshes.length !== 0) {
  22727. this._renderAlphaTest(this._alphaTestSubMeshes);
  22728. }
  22729. var stencilState = engine.getStencilBuffer();
  22730. engine.setStencilBuffer(false);
  22731. // Sprites
  22732. if (renderSprites) {
  22733. this._renderSprites();
  22734. }
  22735. // Particles
  22736. if (renderParticles) {
  22737. this._renderParticles(activeMeshes);
  22738. }
  22739. if (this.onBeforeTransparentRendering) {
  22740. this.onBeforeTransparentRendering();
  22741. }
  22742. // Transparent
  22743. if (this._transparentSubMeshes.length !== 0) {
  22744. this._renderTransparent(this._transparentSubMeshes);
  22745. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22746. }
  22747. // Set back stencil to false in case it changes before the edge renderer.
  22748. engine.setStencilBuffer(false);
  22749. // Edges
  22750. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  22751. this._edgesRenderers.data[edgesRendererIndex].render();
  22752. }
  22753. // Restore Stencil state.
  22754. engine.setStencilBuffer(stencilState);
  22755. };
  22756. /**
  22757. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  22758. * @param subMeshes The submeshes to render
  22759. */
  22760. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  22761. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  22762. };
  22763. /**
  22764. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  22765. * @param subMeshes The submeshes to render
  22766. */
  22767. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  22768. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  22769. };
  22770. /**
  22771. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  22772. * @param subMeshes The submeshes to render
  22773. */
  22774. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  22775. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  22776. };
  22777. /**
  22778. * Renders the submeshes in a specified order.
  22779. * @param subMeshes The submeshes to sort before render
  22780. * @param sortCompareFn The comparison function use to sort
  22781. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  22782. * @param transparent Specifies to activate blending if true
  22783. */
  22784. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  22785. var subIndex = 0;
  22786. var subMesh;
  22787. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  22788. for (; subIndex < subMeshes.length; subIndex++) {
  22789. subMesh = subMeshes.data[subIndex];
  22790. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  22791. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  22792. }
  22793. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  22794. if (sortCompareFn) {
  22795. sortedArray.sort(sortCompareFn);
  22796. }
  22797. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  22798. subMesh = sortedArray[subIndex];
  22799. if (transparent) {
  22800. var material = subMesh.getMaterial();
  22801. if (material && material.needDepthPrePass) {
  22802. var engine = material.getScene().getEngine();
  22803. engine.setColorWrite(false);
  22804. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22805. subMesh.render(false);
  22806. engine.setColorWrite(true);
  22807. }
  22808. }
  22809. subMesh.render(transparent);
  22810. }
  22811. };
  22812. /**
  22813. * Renders the submeshes in the order they were dispatched (no sort applied).
  22814. * @param subMeshes The submeshes to render
  22815. */
  22816. RenderingGroup.renderUnsorted = function (subMeshes) {
  22817. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  22818. var submesh = subMeshes.data[subIndex];
  22819. submesh.render(false);
  22820. }
  22821. };
  22822. /**
  22823. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22824. * are rendered back to front if in the same alpha index.
  22825. *
  22826. * @param a The first submesh
  22827. * @param b The second submesh
  22828. * @returns The result of the comparison
  22829. */
  22830. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  22831. // Alpha index first
  22832. if (a._alphaIndex > b._alphaIndex) {
  22833. return 1;
  22834. }
  22835. if (a._alphaIndex < b._alphaIndex) {
  22836. return -1;
  22837. }
  22838. // Then distance to camera
  22839. return RenderingGroup.backToFrontSortCompare(a, b);
  22840. };
  22841. /**
  22842. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22843. * are rendered back to front.
  22844. *
  22845. * @param a The first submesh
  22846. * @param b The second submesh
  22847. * @returns The result of the comparison
  22848. */
  22849. RenderingGroup.backToFrontSortCompare = function (a, b) {
  22850. // Then distance to camera
  22851. if (a._distanceToCamera < b._distanceToCamera) {
  22852. return 1;
  22853. }
  22854. if (a._distanceToCamera > b._distanceToCamera) {
  22855. return -1;
  22856. }
  22857. return 0;
  22858. };
  22859. /**
  22860. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22861. * are rendered front to back (prevent overdraw).
  22862. *
  22863. * @param a The first submesh
  22864. * @param b The second submesh
  22865. * @returns The result of the comparison
  22866. */
  22867. RenderingGroup.frontToBackSortCompare = function (a, b) {
  22868. // Then distance to camera
  22869. if (a._distanceToCamera < b._distanceToCamera) {
  22870. return -1;
  22871. }
  22872. if (a._distanceToCamera > b._distanceToCamera) {
  22873. return 1;
  22874. }
  22875. return 0;
  22876. };
  22877. /**
  22878. * Resets the different lists of submeshes to prepare a new frame.
  22879. */
  22880. RenderingGroup.prototype.prepare = function () {
  22881. this._opaqueSubMeshes.reset();
  22882. this._transparentSubMeshes.reset();
  22883. this._alphaTestSubMeshes.reset();
  22884. this._depthOnlySubMeshes.reset();
  22885. this._particleSystems.reset();
  22886. this._spriteManagers.reset();
  22887. this._edgesRenderers.reset();
  22888. };
  22889. RenderingGroup.prototype.dispose = function () {
  22890. this._opaqueSubMeshes.dispose();
  22891. this._transparentSubMeshes.dispose();
  22892. this._alphaTestSubMeshes.dispose();
  22893. this._depthOnlySubMeshes.dispose();
  22894. this._particleSystems.dispose();
  22895. this._spriteManagers.dispose();
  22896. this._edgesRenderers.dispose();
  22897. };
  22898. /**
  22899. * Inserts the submesh in its correct queue depending on its material.
  22900. * @param subMesh The submesh to dispatch
  22901. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22902. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22903. */
  22904. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  22905. // Get mesh and materials if not provided
  22906. if (mesh === undefined) {
  22907. mesh = subMesh.getMesh();
  22908. }
  22909. if (material === undefined) {
  22910. material = subMesh.getMaterial();
  22911. }
  22912. if (material === null || material === undefined) {
  22913. return;
  22914. }
  22915. if (material.needAlphaBlendingForMesh(mesh)) {
  22916. this._transparentSubMeshes.push(subMesh);
  22917. }
  22918. else if (material.needAlphaTesting()) {
  22919. if (material.needDepthPrePass) {
  22920. this._depthOnlySubMeshes.push(subMesh);
  22921. }
  22922. this._alphaTestSubMeshes.push(subMesh);
  22923. }
  22924. else {
  22925. if (material.needDepthPrePass) {
  22926. this._depthOnlySubMeshes.push(subMesh);
  22927. }
  22928. this._opaqueSubMeshes.push(subMesh); // Opaque
  22929. }
  22930. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  22931. this._edgesRenderers.push(mesh._edgesRenderer);
  22932. }
  22933. };
  22934. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  22935. this._spriteManagers.push(spriteManager);
  22936. };
  22937. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  22938. this._particleSystems.push(particleSystem);
  22939. };
  22940. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  22941. if (this._particleSystems.length === 0) {
  22942. return;
  22943. }
  22944. // Particles
  22945. var activeCamera = this._scene.activeCamera;
  22946. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  22947. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  22948. var particleSystem = this._particleSystems.data[particleIndex];
  22949. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  22950. continue;
  22951. }
  22952. var emitter = particleSystem.emitter;
  22953. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  22954. this._scene._activeParticles.addCount(particleSystem.render(), false);
  22955. }
  22956. }
  22957. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  22958. };
  22959. RenderingGroup.prototype._renderSprites = function () {
  22960. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  22961. return;
  22962. }
  22963. // Sprites
  22964. var activeCamera = this._scene.activeCamera;
  22965. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  22966. for (var id = 0; id < this._spriteManagers.length; id++) {
  22967. var spriteManager = this._spriteManagers.data[id];
  22968. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  22969. spriteManager.render();
  22970. }
  22971. }
  22972. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  22973. };
  22974. return RenderingGroup;
  22975. }());
  22976. BABYLON.RenderingGroup = RenderingGroup;
  22977. })(BABYLON || (BABYLON = {}));
  22978. //# sourceMappingURL=babylon.renderingGroup.js.map
  22979. "use strict";
  22980. var BABYLON;
  22981. (function (BABYLON) {
  22982. /** @ignore */
  22983. var ClickInfo = /** @class */ (function () {
  22984. function ClickInfo() {
  22985. this._singleClick = false;
  22986. this._doubleClick = false;
  22987. this._hasSwiped = false;
  22988. this._ignore = false;
  22989. }
  22990. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  22991. get: function () {
  22992. return this._singleClick;
  22993. },
  22994. set: function (b) {
  22995. this._singleClick = b;
  22996. },
  22997. enumerable: true,
  22998. configurable: true
  22999. });
  23000. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23001. get: function () {
  23002. return this._doubleClick;
  23003. },
  23004. set: function (b) {
  23005. this._doubleClick = b;
  23006. },
  23007. enumerable: true,
  23008. configurable: true
  23009. });
  23010. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23011. get: function () {
  23012. return this._hasSwiped;
  23013. },
  23014. set: function (b) {
  23015. this._hasSwiped = b;
  23016. },
  23017. enumerable: true,
  23018. configurable: true
  23019. });
  23020. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23021. get: function () {
  23022. return this._ignore;
  23023. },
  23024. set: function (b) {
  23025. this._ignore = b;
  23026. },
  23027. enumerable: true,
  23028. configurable: true
  23029. });
  23030. return ClickInfo;
  23031. }());
  23032. /**
  23033. * This class is used by the onRenderingGroupObservable
  23034. */
  23035. var RenderingGroupInfo = /** @class */ (function () {
  23036. function RenderingGroupInfo() {
  23037. }
  23038. /**
  23039. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23040. * This stage will be fired no matter what
  23041. */
  23042. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23043. /**
  23044. * Called before opaque object are rendered.
  23045. * This stage will be fired only if there's 3D Opaque content to render
  23046. */
  23047. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23048. /**
  23049. * Called after the opaque objects are rendered and before the transparent ones
  23050. * This stage will be fired only if there's 3D transparent content to render
  23051. */
  23052. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23053. /**
  23054. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23055. * This stage will be fired no matter what
  23056. */
  23057. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23058. return RenderingGroupInfo;
  23059. }());
  23060. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23061. /**
  23062. * Represents a scene to be rendered by the engine.
  23063. * @see http://doc.babylonjs.com/features/scene
  23064. */
  23065. var Scene = /** @class */ (function () {
  23066. /**
  23067. * Creates a new Scene
  23068. * @param engine defines the engine to use to render this scene
  23069. */
  23070. function Scene(engine) {
  23071. // Members
  23072. /**
  23073. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23074. */
  23075. this.autoClear = true;
  23076. /**
  23077. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23078. */
  23079. this.autoClearDepthAndStencil = true;
  23080. /**
  23081. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23082. */
  23083. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23084. /**
  23085. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23086. */
  23087. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23088. this._forceWireframe = false;
  23089. this._forcePointsCloud = false;
  23090. /**
  23091. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23092. */
  23093. this.forceShowBoundingBoxes = false;
  23094. /**
  23095. * Gets or sets a boolean indicating if animations are enabled
  23096. */
  23097. this.animationsEnabled = true;
  23098. /**
  23099. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23100. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23101. */
  23102. this.useConstantAnimationDeltaTime = false;
  23103. /**
  23104. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23105. * Please note that it requires to run a ray cast through the scene on every frame
  23106. */
  23107. this.constantlyUpdateMeshUnderPointer = false;
  23108. /**
  23109. * Defines the HTML cursor to use when hovering over interactive elements
  23110. */
  23111. this.hoverCursor = "pointer";
  23112. /**
  23113. * Defines the HTML default cursor to use (empty by default)
  23114. */
  23115. this.defaultCursor = "";
  23116. /**
  23117. * This is used to call preventDefault() on pointer down
  23118. * in order to block unwanted artifacts like system double clicks
  23119. */
  23120. this.preventDefaultOnPointerDown = true;
  23121. // Metadata
  23122. /**
  23123. * Gets or sets user defined metadata
  23124. */
  23125. this.metadata = null;
  23126. /**
  23127. * Use this array to add regular expressions used to disable offline support for specific urls
  23128. */
  23129. this.disableOfflineSupportExceptionRules = new Array();
  23130. /**
  23131. * An event triggered when the scene is disposed.
  23132. */
  23133. this.onDisposeObservable = new BABYLON.Observable();
  23134. this._onDisposeObserver = null;
  23135. /**
  23136. * An event triggered before rendering the scene (right after animations and physics)
  23137. */
  23138. this.onBeforeRenderObservable = new BABYLON.Observable();
  23139. this._onBeforeRenderObserver = null;
  23140. /**
  23141. * An event triggered after rendering the scene
  23142. */
  23143. this.onAfterRenderObservable = new BABYLON.Observable();
  23144. this._onAfterRenderObserver = null;
  23145. /**
  23146. * An event triggered before animating the scene
  23147. */
  23148. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23149. /**
  23150. * An event triggered after animations processing
  23151. */
  23152. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23153. /**
  23154. * An event triggered before draw calls are ready to be sent
  23155. */
  23156. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23157. /**
  23158. * An event triggered after draw calls have been sent
  23159. */
  23160. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23161. /**
  23162. * An event triggered when physic simulation is about to be run
  23163. */
  23164. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23165. /**
  23166. * An event triggered when physic simulation has been done
  23167. */
  23168. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23169. /**
  23170. * An event triggered when the scene is ready
  23171. */
  23172. this.onReadyObservable = new BABYLON.Observable();
  23173. /**
  23174. * An event triggered before rendering a camera
  23175. */
  23176. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23177. this._onBeforeCameraRenderObserver = null;
  23178. /**
  23179. * An event triggered after rendering a camera
  23180. */
  23181. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23182. this._onAfterCameraRenderObserver = null;
  23183. /**
  23184. * An event triggered when active meshes evaluation is about to start
  23185. */
  23186. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23187. /**
  23188. * An event triggered when active meshes evaluation is done
  23189. */
  23190. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23191. /**
  23192. * An event triggered when particles rendering is about to start
  23193. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23194. */
  23195. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23196. /**
  23197. * An event triggered when particles rendering is done
  23198. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23199. */
  23200. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23201. /**
  23202. * An event triggered when sprites rendering is about to start
  23203. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23204. */
  23205. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23206. /**
  23207. * An event triggered when sprites rendering is done
  23208. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23209. */
  23210. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23211. /**
  23212. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23213. */
  23214. this.onDataLoadedObservable = new BABYLON.Observable();
  23215. /**
  23216. * An event triggered when a camera is created
  23217. */
  23218. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23219. /**
  23220. * An event triggered when a camera is removed
  23221. */
  23222. this.onCameraRemovedObservable = new BABYLON.Observable();
  23223. /**
  23224. * An event triggered when a light is created
  23225. */
  23226. this.onNewLightAddedObservable = new BABYLON.Observable();
  23227. /**
  23228. * An event triggered when a light is removed
  23229. */
  23230. this.onLightRemovedObservable = new BABYLON.Observable();
  23231. /**
  23232. * An event triggered when a geometry is created
  23233. */
  23234. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23235. /**
  23236. * An event triggered when a geometry is removed
  23237. */
  23238. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23239. /**
  23240. * An event triggered when a transform node is created
  23241. */
  23242. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23243. /**
  23244. * An event triggered when a transform node is removed
  23245. */
  23246. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23247. /**
  23248. * An event triggered when a mesh is created
  23249. */
  23250. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23251. /**
  23252. * An event triggered when a mesh is removed
  23253. */
  23254. this.onMeshRemovedObservable = new BABYLON.Observable();
  23255. /**
  23256. * An event triggered when render targets are about to be rendered
  23257. * Can happen multiple times per frame.
  23258. */
  23259. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23260. /**
  23261. * An event triggered when render targets were rendered.
  23262. * Can happen multiple times per frame.
  23263. */
  23264. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23265. /**
  23266. * An event triggered before calculating deterministic simulation step
  23267. */
  23268. this.onBeforeStepObservable = new BABYLON.Observable();
  23269. /**
  23270. * An event triggered after calculating deterministic simulation step
  23271. */
  23272. this.onAfterStepObservable = new BABYLON.Observable();
  23273. /**
  23274. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23275. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23276. * 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)
  23277. */
  23278. this.onRenderingGroupObservable = new BABYLON.Observable();
  23279. // Animations
  23280. /**
  23281. * Gets a list of Animations associated with the scene
  23282. */
  23283. this.animations = [];
  23284. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23285. /**
  23286. * 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).
  23287. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23288. */
  23289. this.onPrePointerObservable = new BABYLON.Observable();
  23290. /**
  23291. * Observable event triggered each time an input event is received from the rendering canvas
  23292. */
  23293. this.onPointerObservable = new BABYLON.Observable();
  23294. this._meshPickProceed = false;
  23295. this._currentPickResult = null;
  23296. this._previousPickResult = null;
  23297. this._totalPointersPressed = 0;
  23298. this._doubleClickOccured = false;
  23299. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23300. this.cameraToUseForPointers = null;
  23301. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23302. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23303. this._startingPointerTime = 0;
  23304. this._previousStartingPointerTime = 0;
  23305. // Deterministic lockstep
  23306. this._timeAccumulator = 0;
  23307. this._currentStepId = 0;
  23308. this._currentInternalStep = 0;
  23309. // Keyboard
  23310. /**
  23311. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23312. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23313. */
  23314. this.onPreKeyboardObservable = new BABYLON.Observable();
  23315. /**
  23316. * Observable event triggered each time an keyboard event is received from the hosting window
  23317. */
  23318. this.onKeyboardObservable = new BABYLON.Observable();
  23319. // Coordinates system
  23320. this._useRightHandedSystem = false;
  23321. // Fog
  23322. this._fogEnabled = true;
  23323. this._fogMode = Scene.FOGMODE_NONE;
  23324. /**
  23325. * Gets or sets the fog color to use
  23326. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23327. */
  23328. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23329. /**
  23330. * Gets or sets the fog density to use
  23331. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23332. */
  23333. this.fogDensity = 0.1;
  23334. /**
  23335. * Gets or sets the fog start distance to use
  23336. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23337. */
  23338. this.fogStart = 0;
  23339. /**
  23340. * Gets or sets the fog end distance to use
  23341. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23342. */
  23343. this.fogEnd = 1000.0;
  23344. // Lights
  23345. this._shadowsEnabled = true;
  23346. this._lightsEnabled = true;
  23347. /**
  23348. * All of the lights added to this scene
  23349. * @see http://doc.babylonjs.com/babylon101/lights
  23350. */
  23351. this.lights = new Array();
  23352. // Cameras
  23353. /** All of the cameras added to this scene.
  23354. * @see http://doc.babylonjs.com/babylon101/cameras
  23355. */
  23356. this.cameras = new Array();
  23357. /** All of the active cameras added to this scene. */
  23358. this.activeCameras = new Array();
  23359. // Meshes
  23360. /**
  23361. * All of the tranform nodes added to this scene
  23362. * @see http://doc.babylonjs.com/how_to/transformnode
  23363. */
  23364. this.transformNodes = new Array();
  23365. /**
  23366. * All of the (abstract) meshes added to this scene
  23367. */
  23368. this.meshes = new Array();
  23369. /**
  23370. * All of the animation groups added to this scene
  23371. * @see http://doc.babylonjs.com/how_to/group
  23372. */
  23373. this.animationGroups = new Array();
  23374. // Geometries
  23375. this._geometries = new Array();
  23376. /**
  23377. * All of the materials added to this scene
  23378. * @see http://doc.babylonjs.com/babylon101/materials
  23379. */
  23380. this.materials = new Array();
  23381. /**
  23382. * All of the multi-materials added to this scene
  23383. * @see http://doc.babylonjs.com/how_to/multi_materials
  23384. */
  23385. this.multiMaterials = new Array();
  23386. // Textures
  23387. this._texturesEnabled = true;
  23388. /**
  23389. * All of the textures added to this scene
  23390. */
  23391. this.textures = new Array();
  23392. // Particles
  23393. /**
  23394. * Gets or sets a boolean indicating if particles are enabled on this scene
  23395. */
  23396. this.particlesEnabled = true;
  23397. /**
  23398. * All of the particle systems added to this scene
  23399. * @see http://doc.babylonjs.com/babylon101/particles
  23400. */
  23401. this.particleSystems = new Array();
  23402. // Sprites
  23403. /**
  23404. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23405. */
  23406. this.spritesEnabled = true;
  23407. /**
  23408. * All of the sprite managers added to this scene
  23409. * @see http://doc.babylonjs.com/babylon101/sprites
  23410. */
  23411. this.spriteManagers = new Array();
  23412. /**
  23413. * The list of layers (background and foreground) of the scene
  23414. */
  23415. this.layers = new Array();
  23416. /**
  23417. * The list of effect layers (highlights/glow) added to the scene
  23418. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23419. * @see http://doc.babylonjs.com/how_to/glow_layer
  23420. */
  23421. this.effectLayers = new Array();
  23422. // Skeletons
  23423. this._skeletonsEnabled = true;
  23424. /**
  23425. * The list of skeletons added to the scene
  23426. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23427. */
  23428. this.skeletons = new Array();
  23429. // Morph targets
  23430. /**
  23431. * The list of morph target managers added to the scene
  23432. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23433. */
  23434. this.morphTargetManagers = new Array();
  23435. // Lens flares
  23436. /**
  23437. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23438. */
  23439. this.lensFlaresEnabled = true;
  23440. /**
  23441. * The list of lens flare system added to the scene
  23442. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23443. */
  23444. this.lensFlareSystems = new Array();
  23445. // Collisions
  23446. /**
  23447. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23448. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23449. */
  23450. this.collisionsEnabled = true;
  23451. /**
  23452. * Defines the gravity applied to this scene (used only for collisions)
  23453. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23454. */
  23455. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23456. // Postprocesses
  23457. /**
  23458. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23459. */
  23460. this.postProcessesEnabled = true;
  23461. /**
  23462. * The list of postprocesses added to the scene
  23463. */
  23464. this.postProcesses = new Array();
  23465. // Customs render targets
  23466. /**
  23467. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23468. */
  23469. this.renderTargetsEnabled = true;
  23470. /**
  23471. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23472. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23473. */
  23474. this.dumpNextRenderTargets = false;
  23475. /**
  23476. * The list of user defined render targets added to the scene
  23477. */
  23478. this.customRenderTargets = new Array();
  23479. /**
  23480. * Gets the list of meshes imported to the scene through SceneLoader
  23481. */
  23482. this.importedMeshesFiles = new Array();
  23483. // Probes
  23484. /**
  23485. * Gets or sets a boolean indicating if probes are enabled on this scene
  23486. */
  23487. this.probesEnabled = true;
  23488. /**
  23489. * The list of reflection probes added to the scene
  23490. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23491. */
  23492. this.reflectionProbes = new Array();
  23493. /** @ignore */
  23494. this._actionManagers = new Array();
  23495. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23496. // Procedural textures
  23497. /**
  23498. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23499. */
  23500. this.proceduralTexturesEnabled = true;
  23501. /**
  23502. * The list of procedural textures added to the scene
  23503. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23504. */
  23505. this.proceduralTextures = new Array();
  23506. /**
  23507. * The list of sound tracks added to the scene
  23508. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23509. */
  23510. this.soundTracks = new Array();
  23511. this._audioEnabled = true;
  23512. this._headphone = false;
  23513. // Performance counters
  23514. this._totalVertices = new BABYLON.PerfCounter();
  23515. /** @ignore */
  23516. this._activeIndices = new BABYLON.PerfCounter();
  23517. /** @ignore */
  23518. this._activeParticles = new BABYLON.PerfCounter();
  23519. /** @ignore */
  23520. this._activeBones = new BABYLON.PerfCounter();
  23521. this._animationTime = 0;
  23522. /**
  23523. * Gets or sets a general scale for animation speed
  23524. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23525. */
  23526. this.animationTimeScale = 1;
  23527. this._renderId = 0;
  23528. this._executeWhenReadyTimeoutId = -1;
  23529. this._intermediateRendering = false;
  23530. this._viewUpdateFlag = -1;
  23531. this._projectionUpdateFlag = -1;
  23532. this._alternateViewUpdateFlag = -1;
  23533. this._alternateProjectionUpdateFlag = -1;
  23534. /** @ignore */
  23535. this._toBeDisposed = new BABYLON.SmartArray(256);
  23536. this._activeRequests = new Array();
  23537. this._pendingData = new Array();
  23538. this._isDisposed = false;
  23539. /**
  23540. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23541. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23542. */
  23543. this.dispatchAllSubMeshesOfActiveMeshes = false;
  23544. this._activeMeshes = new BABYLON.SmartArray(256);
  23545. this._processedMaterials = new BABYLON.SmartArray(256);
  23546. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23547. /** @ignore */
  23548. this._activeParticleSystems = new BABYLON.SmartArray(256);
  23549. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23550. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23551. /** @ignore */
  23552. this._activeAnimatables = new Array();
  23553. this._transformMatrix = BABYLON.Matrix.Zero();
  23554. this._useAlternateCameraConfiguration = false;
  23555. this._alternateRendering = false;
  23556. /**
  23557. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  23558. * This is useful if there are more lights that the maximum simulteanous authorized
  23559. */
  23560. this.requireLightSorting = false;
  23561. this._depthRenderer = {};
  23562. this._activeMeshesFrozen = false;
  23563. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  23564. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  23565. this._engine.scenes.push(this);
  23566. this._uid = null;
  23567. this._renderingManager = new BABYLON.RenderingManager(this);
  23568. this.postProcessManager = new BABYLON.PostProcessManager(this);
  23569. if (BABYLON.OutlineRenderer) {
  23570. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  23571. }
  23572. if (BABYLON.Tools.IsWindowObjectExist()) {
  23573. this.attachControl();
  23574. }
  23575. //simplification queue
  23576. if (BABYLON.SimplificationQueue) {
  23577. this.simplificationQueue = new BABYLON.SimplificationQueue();
  23578. }
  23579. //collision coordinator initialization. For now legacy per default.
  23580. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  23581. // Uniform Buffer
  23582. this._createUbo();
  23583. // Default Image processing definition.
  23584. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  23585. }
  23586. Object.defineProperty(Scene, "FOGMODE_NONE", {
  23587. /** The fog is deactivated */
  23588. get: function () {
  23589. return Scene._FOGMODE_NONE;
  23590. },
  23591. enumerable: true,
  23592. configurable: true
  23593. });
  23594. Object.defineProperty(Scene, "FOGMODE_EXP", {
  23595. /** The fog density is following an exponential function */
  23596. get: function () {
  23597. return Scene._FOGMODE_EXP;
  23598. },
  23599. enumerable: true,
  23600. configurable: true
  23601. });
  23602. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  23603. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  23604. get: function () {
  23605. return Scene._FOGMODE_EXP2;
  23606. },
  23607. enumerable: true,
  23608. configurable: true
  23609. });
  23610. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  23611. /** The fog density is following a linear function. */
  23612. get: function () {
  23613. return Scene._FOGMODE_LINEAR;
  23614. },
  23615. enumerable: true,
  23616. configurable: true
  23617. });
  23618. Object.defineProperty(Scene.prototype, "environmentTexture", {
  23619. /**
  23620. * Texture used in all pbr material as the reflection texture.
  23621. * As in the majority of the scene they are the same (exception for multi room and so on),
  23622. * this is easier to reference from here than from all the materials.
  23623. */
  23624. get: function () {
  23625. return this._environmentTexture;
  23626. },
  23627. /**
  23628. * Texture used in all pbr material as the reflection texture.
  23629. * As in the majority of the scene they are the same (exception for multi room and so on),
  23630. * this is easier to set here than in all the materials.
  23631. */
  23632. set: function (value) {
  23633. if (this._environmentTexture === value) {
  23634. return;
  23635. }
  23636. this._environmentTexture = value;
  23637. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23638. },
  23639. enumerable: true,
  23640. configurable: true
  23641. });
  23642. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  23643. /**
  23644. * Default image processing configuration used either in the rendering
  23645. * Forward main pass or through the imageProcessingPostProcess if present.
  23646. * As in the majority of the scene they are the same (exception for multi camera),
  23647. * this is easier to reference from here than from all the materials and post process.
  23648. *
  23649. * No setter as we it is a shared configuration, you can set the values instead.
  23650. */
  23651. get: function () {
  23652. return this._imageProcessingConfiguration;
  23653. },
  23654. enumerable: true,
  23655. configurable: true
  23656. });
  23657. Object.defineProperty(Scene.prototype, "forceWireframe", {
  23658. get: function () {
  23659. return this._forceWireframe;
  23660. },
  23661. /**
  23662. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  23663. */
  23664. set: function (value) {
  23665. if (this._forceWireframe === value) {
  23666. return;
  23667. }
  23668. this._forceWireframe = value;
  23669. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23670. },
  23671. enumerable: true,
  23672. configurable: true
  23673. });
  23674. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  23675. get: function () {
  23676. return this._forcePointsCloud;
  23677. },
  23678. /**
  23679. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  23680. */
  23681. set: function (value) {
  23682. if (this._forcePointsCloud === value) {
  23683. return;
  23684. }
  23685. this._forcePointsCloud = value;
  23686. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23687. },
  23688. enumerable: true,
  23689. configurable: true
  23690. });
  23691. Object.defineProperty(Scene.prototype, "onDispose", {
  23692. /** Sets a function to be executed when this scene is disposed. */
  23693. set: function (callback) {
  23694. if (this._onDisposeObserver) {
  23695. this.onDisposeObservable.remove(this._onDisposeObserver);
  23696. }
  23697. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23698. },
  23699. enumerable: true,
  23700. configurable: true
  23701. });
  23702. Object.defineProperty(Scene.prototype, "beforeRender", {
  23703. /** Sets a function to be executed before rendering this scene */
  23704. set: function (callback) {
  23705. if (this._onBeforeRenderObserver) {
  23706. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23707. }
  23708. if (callback) {
  23709. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23710. }
  23711. },
  23712. enumerable: true,
  23713. configurable: true
  23714. });
  23715. Object.defineProperty(Scene.prototype, "afterRender", {
  23716. /** Sets a function to be executed after rendering this scene */
  23717. set: function (callback) {
  23718. if (this._onAfterRenderObserver) {
  23719. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23720. }
  23721. if (callback) {
  23722. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23723. }
  23724. },
  23725. enumerable: true,
  23726. configurable: true
  23727. });
  23728. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  23729. /** Sets a function to be executed before rendering a camera*/
  23730. set: function (callback) {
  23731. if (this._onBeforeCameraRenderObserver) {
  23732. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  23733. }
  23734. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  23735. },
  23736. enumerable: true,
  23737. configurable: true
  23738. });
  23739. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  23740. /** Sets a function to be executed after rendering a camera*/
  23741. set: function (callback) {
  23742. if (this._onAfterCameraRenderObserver) {
  23743. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  23744. }
  23745. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  23746. },
  23747. enumerable: true,
  23748. configurable: true
  23749. });
  23750. Object.defineProperty(Scene.prototype, "gamepadManager", {
  23751. /**
  23752. * Gets the gamepad manager associated with the scene
  23753. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  23754. */
  23755. get: function () {
  23756. if (!this._gamepadManager) {
  23757. this._gamepadManager = new BABYLON.GamepadManager(this);
  23758. }
  23759. return this._gamepadManager;
  23760. },
  23761. enumerable: true,
  23762. configurable: true
  23763. });
  23764. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  23765. /**
  23766. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  23767. */
  23768. get: function () {
  23769. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  23770. },
  23771. enumerable: true,
  23772. configurable: true
  23773. });
  23774. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  23775. get: function () {
  23776. return this._useRightHandedSystem;
  23777. },
  23778. /**
  23779. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  23780. */
  23781. set: function (value) {
  23782. if (this._useRightHandedSystem === value) {
  23783. return;
  23784. }
  23785. this._useRightHandedSystem = value;
  23786. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23787. },
  23788. enumerable: true,
  23789. configurable: true
  23790. });
  23791. /**
  23792. * Sets the step Id used by deterministic lock step
  23793. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23794. * @param newStepId defines the step Id
  23795. */
  23796. Scene.prototype.setStepId = function (newStepId) {
  23797. this._currentStepId = newStepId;
  23798. };
  23799. ;
  23800. /**
  23801. * Gets the step Id used by deterministic lock step
  23802. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23803. * @returns the step Id
  23804. */
  23805. Scene.prototype.getStepId = function () {
  23806. return this._currentStepId;
  23807. };
  23808. ;
  23809. /**
  23810. * Gets the internal step used by deterministic lock step
  23811. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23812. * @returns the internal step
  23813. */
  23814. Scene.prototype.getInternalStep = function () {
  23815. return this._currentInternalStep;
  23816. };
  23817. ;
  23818. Object.defineProperty(Scene.prototype, "fogEnabled", {
  23819. get: function () {
  23820. return this._fogEnabled;
  23821. },
  23822. /**
  23823. * Gets or sets a boolean indicating if fog is enabled on this scene
  23824. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23825. */
  23826. set: function (value) {
  23827. if (this._fogEnabled === value) {
  23828. return;
  23829. }
  23830. this._fogEnabled = value;
  23831. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23832. },
  23833. enumerable: true,
  23834. configurable: true
  23835. });
  23836. Object.defineProperty(Scene.prototype, "fogMode", {
  23837. get: function () {
  23838. return this._fogMode;
  23839. },
  23840. /**
  23841. * Gets or sets the fog mode to use
  23842. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23843. */
  23844. set: function (value) {
  23845. if (this._fogMode === value) {
  23846. return;
  23847. }
  23848. this._fogMode = value;
  23849. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23850. },
  23851. enumerable: true,
  23852. configurable: true
  23853. });
  23854. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  23855. get: function () {
  23856. return this._shadowsEnabled;
  23857. },
  23858. /**
  23859. * Gets or sets a boolean indicating if shadows are enabled on this scene
  23860. */
  23861. set: function (value) {
  23862. if (this._shadowsEnabled === value) {
  23863. return;
  23864. }
  23865. this._shadowsEnabled = value;
  23866. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  23867. },
  23868. enumerable: true,
  23869. configurable: true
  23870. });
  23871. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  23872. get: function () {
  23873. return this._lightsEnabled;
  23874. },
  23875. /**
  23876. * Gets or sets a boolean indicating if lights are enabled on this scene
  23877. */
  23878. set: function (value) {
  23879. if (this._lightsEnabled === value) {
  23880. return;
  23881. }
  23882. this._lightsEnabled = value;
  23883. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  23884. },
  23885. enumerable: true,
  23886. configurable: true
  23887. });
  23888. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  23889. /** The default material used on meshes when no material is affected */
  23890. get: function () {
  23891. if (!this._defaultMaterial) {
  23892. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  23893. }
  23894. return this._defaultMaterial;
  23895. },
  23896. /** The default material used on meshes when no material is affected */
  23897. set: function (value) {
  23898. this._defaultMaterial = value;
  23899. },
  23900. enumerable: true,
  23901. configurable: true
  23902. });
  23903. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  23904. get: function () {
  23905. return this._texturesEnabled;
  23906. },
  23907. /**
  23908. * Gets or sets a boolean indicating if textures are enabled on this scene
  23909. */
  23910. set: function (value) {
  23911. if (this._texturesEnabled === value) {
  23912. return;
  23913. }
  23914. this._texturesEnabled = value;
  23915. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23916. },
  23917. enumerable: true,
  23918. configurable: true
  23919. });
  23920. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  23921. get: function () {
  23922. return this._skeletonsEnabled;
  23923. },
  23924. /**
  23925. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  23926. */
  23927. set: function (value) {
  23928. if (this._skeletonsEnabled === value) {
  23929. return;
  23930. }
  23931. this._skeletonsEnabled = value;
  23932. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  23933. },
  23934. enumerable: true,
  23935. configurable: true
  23936. });
  23937. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  23938. /**
  23939. * Gets the postprocess render pipeline manager
  23940. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  23941. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  23942. */
  23943. get: function () {
  23944. if (!this._postProcessRenderPipelineManager) {
  23945. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  23946. }
  23947. return this._postProcessRenderPipelineManager;
  23948. },
  23949. enumerable: true,
  23950. configurable: true
  23951. });
  23952. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  23953. /**
  23954. * Gets the main soundtrack associated with the scene
  23955. */
  23956. get: function () {
  23957. if (!this._mainSoundTrack) {
  23958. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  23959. }
  23960. return this._mainSoundTrack;
  23961. },
  23962. enumerable: true,
  23963. configurable: true
  23964. });
  23965. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  23966. /** @ignore */
  23967. get: function () {
  23968. return this._alternateRendering;
  23969. },
  23970. enumerable: true,
  23971. configurable: true
  23972. });
  23973. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  23974. /**
  23975. * Gets the list of frustum planes (built from the active camera)
  23976. */
  23977. get: function () {
  23978. return this._frustumPlanes;
  23979. },
  23980. enumerable: true,
  23981. configurable: true
  23982. });
  23983. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  23984. /**
  23985. * Gets the current geometry buffer associated to the scene.
  23986. */
  23987. get: function () {
  23988. return this._geometryBufferRenderer;
  23989. },
  23990. /**
  23991. * Sets the current geometry buffer for the scene.
  23992. */
  23993. set: function (geometryBufferRenderer) {
  23994. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  23995. this._geometryBufferRenderer = geometryBufferRenderer;
  23996. }
  23997. },
  23998. enumerable: true,
  23999. configurable: true
  24000. });
  24001. Object.defineProperty(Scene.prototype, "debugLayer", {
  24002. /**
  24003. * Gets the debug layer associated with the scene
  24004. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24005. */
  24006. get: function () {
  24007. if (!this._debugLayer) {
  24008. this._debugLayer = new BABYLON.DebugLayer(this);
  24009. }
  24010. return this._debugLayer;
  24011. },
  24012. enumerable: true,
  24013. configurable: true
  24014. });
  24015. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24016. /**
  24017. * Gets a boolean indicating if collisions are processed on a web worker
  24018. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24019. */
  24020. get: function () {
  24021. return this._workerCollisions;
  24022. },
  24023. set: function (enabled) {
  24024. if (!BABYLON.CollisionCoordinatorLegacy) {
  24025. return;
  24026. }
  24027. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24028. this._workerCollisions = enabled;
  24029. if (this.collisionCoordinator) {
  24030. this.collisionCoordinator.destroy();
  24031. }
  24032. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24033. this.collisionCoordinator.init(this);
  24034. },
  24035. enumerable: true,
  24036. configurable: true
  24037. });
  24038. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24039. /**
  24040. * Gets the octree used to boost mesh selection (picking)
  24041. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24042. */
  24043. get: function () {
  24044. return this._selectionOctree;
  24045. },
  24046. enumerable: true,
  24047. configurable: true
  24048. });
  24049. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24050. /**
  24051. * Gets the mesh that is currently under the pointer
  24052. */
  24053. get: function () {
  24054. return this._pointerOverMesh;
  24055. },
  24056. enumerable: true,
  24057. configurable: true
  24058. });
  24059. Object.defineProperty(Scene.prototype, "pointerX", {
  24060. /**
  24061. * Gets the current on-screen X position of the pointer
  24062. */
  24063. get: function () {
  24064. return this._pointerX;
  24065. },
  24066. enumerable: true,
  24067. configurable: true
  24068. });
  24069. Object.defineProperty(Scene.prototype, "pointerY", {
  24070. /**
  24071. * Gets the current on-screen Y position of the pointer
  24072. */
  24073. get: function () {
  24074. return this._pointerY;
  24075. },
  24076. enumerable: true,
  24077. configurable: true
  24078. });
  24079. /**
  24080. * Gets the cached material (ie. the latest rendered one)
  24081. * @returns the cached material
  24082. */
  24083. Scene.prototype.getCachedMaterial = function () {
  24084. return this._cachedMaterial;
  24085. };
  24086. /**
  24087. * Gets the cached effect (ie. the latest rendered one)
  24088. * @returns the cached effect
  24089. */
  24090. Scene.prototype.getCachedEffect = function () {
  24091. return this._cachedEffect;
  24092. };
  24093. /**
  24094. * Gets the cached visibility state (ie. the latest rendered one)
  24095. * @returns the cached visibility state
  24096. */
  24097. Scene.prototype.getCachedVisibility = function () {
  24098. return this._cachedVisibility;
  24099. };
  24100. /**
  24101. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24102. * @param material defines the current material
  24103. * @param effect defines the current effect
  24104. * @param visibility defines the current visibility state
  24105. * @returns true if one parameter is not cached
  24106. */
  24107. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24108. if (visibility === void 0) { visibility = 1; }
  24109. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24110. };
  24111. /**
  24112. * Gets the bounding box renderer associated with the scene
  24113. * @returns a BoundingBoxRenderer
  24114. */
  24115. Scene.prototype.getBoundingBoxRenderer = function () {
  24116. if (!this._boundingBoxRenderer) {
  24117. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24118. }
  24119. return this._boundingBoxRenderer;
  24120. };
  24121. /**
  24122. * Gets the outline renderer associated with the scene
  24123. * @returns a OutlineRenderer
  24124. */
  24125. Scene.prototype.getOutlineRenderer = function () {
  24126. return this._outlineRenderer;
  24127. };
  24128. /**
  24129. * Gets the engine associated with the scene
  24130. * @returns an Engine
  24131. */
  24132. Scene.prototype.getEngine = function () {
  24133. return this._engine;
  24134. };
  24135. /**
  24136. * Gets the total number of vertices rendered per frame
  24137. * @returns the total number of vertices rendered per frame
  24138. */
  24139. Scene.prototype.getTotalVertices = function () {
  24140. return this._totalVertices.current;
  24141. };
  24142. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24143. /**
  24144. * Gets the performance counter for total vertices
  24145. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24146. */
  24147. get: function () {
  24148. return this._totalVertices;
  24149. },
  24150. enumerable: true,
  24151. configurable: true
  24152. });
  24153. /**
  24154. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24155. * @returns the total number of active indices rendered per frame
  24156. */
  24157. Scene.prototype.getActiveIndices = function () {
  24158. return this._activeIndices.current;
  24159. };
  24160. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24161. /**
  24162. * Gets the performance counter for active indices
  24163. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24164. */
  24165. get: function () {
  24166. return this._activeIndices;
  24167. },
  24168. enumerable: true,
  24169. configurable: true
  24170. });
  24171. /**
  24172. * Gets the total number of active particles rendered per frame
  24173. * @returns the total number of active particles rendered per frame
  24174. */
  24175. Scene.prototype.getActiveParticles = function () {
  24176. return this._activeParticles.current;
  24177. };
  24178. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24179. /**
  24180. * Gets the performance counter for active particles
  24181. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24182. */
  24183. get: function () {
  24184. return this._activeParticles;
  24185. },
  24186. enumerable: true,
  24187. configurable: true
  24188. });
  24189. /**
  24190. * Gets the total number of active bones rendered per frame
  24191. * @returns the total number of active bones rendered per frame
  24192. */
  24193. Scene.prototype.getActiveBones = function () {
  24194. return this._activeBones.current;
  24195. };
  24196. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24197. /**
  24198. * Gets the performance counter for active bones
  24199. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24200. */
  24201. get: function () {
  24202. return this._activeBones;
  24203. },
  24204. enumerable: true,
  24205. configurable: true
  24206. });
  24207. /** @ignore */
  24208. Scene.prototype.getInterFramePerfCounter = function () {
  24209. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24210. return 0;
  24211. };
  24212. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24213. /** @ignore */
  24214. get: function () {
  24215. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24216. return null;
  24217. },
  24218. enumerable: true,
  24219. configurable: true
  24220. });
  24221. /** @ignore */
  24222. Scene.prototype.getLastFrameDuration = function () {
  24223. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24224. return 0;
  24225. };
  24226. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24227. /** @ignore */
  24228. get: function () {
  24229. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24230. return null;
  24231. },
  24232. enumerable: true,
  24233. configurable: true
  24234. });
  24235. /** @ignore */
  24236. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24237. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24238. return 0;
  24239. };
  24240. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24241. /** @ignore */
  24242. get: function () {
  24243. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24244. return null;
  24245. },
  24246. enumerable: true,
  24247. configurable: true
  24248. });
  24249. /**
  24250. * Gets the array of active meshes
  24251. * @returns an array of AbstractMesh
  24252. */
  24253. Scene.prototype.getActiveMeshes = function () {
  24254. return this._activeMeshes;
  24255. };
  24256. /** @ignore */
  24257. Scene.prototype.getRenderTargetsDuration = function () {
  24258. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24259. return 0;
  24260. };
  24261. /** @ignore */
  24262. Scene.prototype.getRenderDuration = function () {
  24263. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24264. return 0;
  24265. };
  24266. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24267. /** @ignore */
  24268. get: function () {
  24269. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24270. return null;
  24271. },
  24272. enumerable: true,
  24273. configurable: true
  24274. });
  24275. /** @ignore */
  24276. Scene.prototype.getParticlesDuration = function () {
  24277. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24278. return 0;
  24279. };
  24280. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24281. /** @ignore */
  24282. get: function () {
  24283. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24284. return null;
  24285. },
  24286. enumerable: true,
  24287. configurable: true
  24288. });
  24289. /** @ignore */
  24290. Scene.prototype.getSpritesDuration = function () {
  24291. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24292. return 0;
  24293. };
  24294. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24295. /** @ignore */
  24296. get: function () {
  24297. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24298. return null;
  24299. },
  24300. enumerable: true,
  24301. configurable: true
  24302. });
  24303. /**
  24304. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24305. * @returns a number
  24306. */
  24307. Scene.prototype.getAnimationRatio = function () {
  24308. return this._animationRatio;
  24309. };
  24310. /**
  24311. * Gets an unique Id for the current frame
  24312. * @returns a number
  24313. */
  24314. Scene.prototype.getRenderId = function () {
  24315. return this._renderId;
  24316. };
  24317. /** Call this function if you want to manually increment the render Id*/
  24318. Scene.prototype.incrementRenderId = function () {
  24319. this._renderId++;
  24320. };
  24321. Scene.prototype._updatePointerPosition = function (evt) {
  24322. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24323. if (!canvasRect) {
  24324. return;
  24325. }
  24326. this._pointerX = evt.clientX - canvasRect.left;
  24327. this._pointerY = evt.clientY - canvasRect.top;
  24328. this._unTranslatedPointerX = this._pointerX;
  24329. this._unTranslatedPointerY = this._pointerY;
  24330. };
  24331. Scene.prototype._createUbo = function () {
  24332. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24333. this._sceneUbo.addUniform("viewProjection", 16);
  24334. this._sceneUbo.addUniform("view", 16);
  24335. };
  24336. Scene.prototype._createAlternateUbo = function () {
  24337. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24338. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24339. this._alternateSceneUbo.addUniform("view", 16);
  24340. };
  24341. // Pointers handling
  24342. /**
  24343. * Use this method to simulate a pointer move on a mesh
  24344. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24345. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24346. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24347. * @returns the current scene
  24348. */
  24349. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24350. var evt = new PointerEvent("pointermove", pointerEventInit);
  24351. return this._processPointerMove(pickResult, evt);
  24352. };
  24353. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24354. var canvas = this._engine.getRenderingCanvas();
  24355. if (!canvas) {
  24356. return this;
  24357. }
  24358. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24359. this.setPointerOverSprite(null);
  24360. this.setPointerOverMesh(pickResult.pickedMesh);
  24361. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24362. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24363. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24364. }
  24365. else {
  24366. canvas.style.cursor = this.hoverCursor;
  24367. }
  24368. }
  24369. else {
  24370. canvas.style.cursor = this.defaultCursor;
  24371. }
  24372. }
  24373. else {
  24374. this.setPointerOverMesh(null);
  24375. // Sprites
  24376. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24377. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24378. this.setPointerOverSprite(pickResult.pickedSprite);
  24379. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24380. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24381. }
  24382. else {
  24383. canvas.style.cursor = this.hoverCursor;
  24384. }
  24385. }
  24386. else {
  24387. this.setPointerOverSprite(null);
  24388. // Restore pointer
  24389. canvas.style.cursor = this.defaultCursor;
  24390. }
  24391. }
  24392. if (pickResult) {
  24393. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24394. if (this.onPointerMove) {
  24395. this.onPointerMove(evt, pickResult, type);
  24396. }
  24397. if (this.onPointerObservable.hasObservers()) {
  24398. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24399. this.onPointerObservable.notifyObservers(pi, type);
  24400. }
  24401. }
  24402. return this;
  24403. };
  24404. /**
  24405. * Use this method to simulate a pointer down on a mesh
  24406. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24407. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24408. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24409. * @returns the current scene
  24410. */
  24411. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24412. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24413. return this._processPointerDown(pickResult, evt);
  24414. };
  24415. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24416. var _this = this;
  24417. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24418. this._pickedDownMesh = pickResult.pickedMesh;
  24419. var actionManager = pickResult.pickedMesh.actionManager;
  24420. if (actionManager) {
  24421. if (actionManager.hasPickTriggers) {
  24422. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24423. switch (evt.button) {
  24424. case 0:
  24425. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24426. break;
  24427. case 1:
  24428. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24429. break;
  24430. case 2:
  24431. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24432. break;
  24433. }
  24434. }
  24435. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24436. window.setTimeout(function () {
  24437. 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);
  24438. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24439. if (_this._totalPointersPressed !== 0 &&
  24440. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24441. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24442. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24443. _this._startingPointerTime = 0;
  24444. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24445. }
  24446. }
  24447. }, Scene.LongPressDelay);
  24448. }
  24449. }
  24450. }
  24451. if (pickResult) {
  24452. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24453. if (this.onPointerDown) {
  24454. this.onPointerDown(evt, pickResult, type);
  24455. }
  24456. if (this.onPointerObservable.hasObservers()) {
  24457. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24458. this.onPointerObservable.notifyObservers(pi, type);
  24459. }
  24460. }
  24461. return this;
  24462. };
  24463. /**
  24464. * Use this method to simulate a pointer up on a mesh
  24465. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24466. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24467. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24468. * @returns the current scene
  24469. */
  24470. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24471. var evt = new PointerEvent("pointerup", pointerEventInit);
  24472. var clickInfo = new ClickInfo();
  24473. clickInfo.singleClick = true;
  24474. clickInfo.ignore = true;
  24475. return this._processPointerUp(pickResult, evt, clickInfo);
  24476. };
  24477. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24478. if (pickResult && pickResult && pickResult.pickedMesh) {
  24479. this._pickedUpMesh = pickResult.pickedMesh;
  24480. if (this._pickedDownMesh === this._pickedUpMesh) {
  24481. if (this.onPointerPick) {
  24482. this.onPointerPick(evt, pickResult);
  24483. }
  24484. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24485. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24486. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24487. this.onPointerObservable.notifyObservers(pi, type_1);
  24488. }
  24489. }
  24490. if (pickResult.pickedMesh.actionManager) {
  24491. if (clickInfo.ignore) {
  24492. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24493. }
  24494. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24495. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24496. }
  24497. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24498. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24499. }
  24500. }
  24501. }
  24502. if (this._pickedDownMesh &&
  24503. this._pickedDownMesh.actionManager &&
  24504. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24505. this._pickedDownMesh !== this._pickedUpMesh) {
  24506. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24507. }
  24508. var type = BABYLON.PointerEventTypes.POINTERUP;
  24509. if (this.onPointerObservable.hasObservers()) {
  24510. if (!clickInfo.ignore) {
  24511. if (!clickInfo.hasSwiped) {
  24512. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24513. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24514. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24515. this.onPointerObservable.notifyObservers(pi, type_2);
  24516. }
  24517. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24518. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24519. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24520. this.onPointerObservable.notifyObservers(pi, type_3);
  24521. }
  24522. }
  24523. }
  24524. else {
  24525. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24526. this.onPointerObservable.notifyObservers(pi, type);
  24527. }
  24528. }
  24529. if (this.onPointerUp) {
  24530. this.onPointerUp(evt, pickResult, type);
  24531. }
  24532. return this;
  24533. };
  24534. /**
  24535. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  24536. * @param attachUp defines if you want to attach events to pointerup
  24537. * @param attachDown defines if you want to attach events to pointerdown
  24538. * @param attachMove defines if you want to attach events to pointermove
  24539. */
  24540. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  24541. var _this = this;
  24542. if (attachUp === void 0) { attachUp = true; }
  24543. if (attachDown === void 0) { attachDown = true; }
  24544. if (attachMove === void 0) { attachMove = true; }
  24545. this._initActionManager = function (act, clickInfo) {
  24546. if (!_this._meshPickProceed) {
  24547. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24548. _this._currentPickResult = pickResult;
  24549. if (pickResult) {
  24550. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  24551. }
  24552. _this._meshPickProceed = true;
  24553. }
  24554. return act;
  24555. };
  24556. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  24557. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  24558. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  24559. btn !== _this._previousButtonPressed) {
  24560. _this._doubleClickOccured = false;
  24561. clickInfo.singleClick = true;
  24562. clickInfo.ignore = false;
  24563. cb(clickInfo, _this._currentPickResult);
  24564. }
  24565. };
  24566. this._initClickEvent = function (obs1, obs2, evt, cb) {
  24567. var clickInfo = new ClickInfo();
  24568. _this._currentPickResult = null;
  24569. var act = null;
  24570. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  24571. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  24572. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24573. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  24574. act = _this._initActionManager(act, clickInfo);
  24575. if (act)
  24576. checkPicking = act.hasPickTriggers;
  24577. }
  24578. if (checkPicking) {
  24579. var btn = evt.button;
  24580. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  24581. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  24582. if (!clickInfo.hasSwiped) {
  24583. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  24584. if (!checkSingleClickImmediately) {
  24585. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  24586. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24587. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24588. act = _this._initActionManager(act, clickInfo);
  24589. if (act)
  24590. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24591. }
  24592. }
  24593. if (checkSingleClickImmediately) {
  24594. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  24595. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  24596. btn !== _this._previousButtonPressed) {
  24597. clickInfo.singleClick = true;
  24598. cb(clickInfo, _this._currentPickResult);
  24599. }
  24600. }
  24601. else {
  24602. // wait that no double click has been raised during the double click delay
  24603. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24604. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  24605. }
  24606. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  24607. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24608. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24609. act = _this._initActionManager(act, clickInfo);
  24610. if (act)
  24611. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24612. }
  24613. if (checkDoubleClick) {
  24614. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  24615. if (btn === _this._previousButtonPressed &&
  24616. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  24617. !_this._doubleClickOccured) {
  24618. // pointer has not moved for 2 clicks, it's a double click
  24619. if (!clickInfo.hasSwiped &&
  24620. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  24621. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  24622. _this._previousStartingPointerTime = 0;
  24623. _this._doubleClickOccured = true;
  24624. clickInfo.doubleClick = true;
  24625. clickInfo.ignore = false;
  24626. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  24627. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24628. }
  24629. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24630. cb(clickInfo, _this._currentPickResult);
  24631. }
  24632. else {
  24633. _this._doubleClickOccured = false;
  24634. _this._previousStartingPointerTime = _this._startingPointerTime;
  24635. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24636. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24637. _this._previousButtonPressed = btn;
  24638. if (Scene.ExclusiveDoubleClickMode) {
  24639. if (_this._previousDelayedSimpleClickTimeout) {
  24640. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24641. }
  24642. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24643. cb(clickInfo, _this._previousPickResult);
  24644. }
  24645. else {
  24646. cb(clickInfo, _this._currentPickResult);
  24647. }
  24648. }
  24649. }
  24650. else {
  24651. _this._doubleClickOccured = false;
  24652. _this._previousStartingPointerTime = _this._startingPointerTime;
  24653. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24654. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24655. _this._previousButtonPressed = btn;
  24656. }
  24657. }
  24658. }
  24659. }
  24660. clickInfo.ignore = true;
  24661. cb(clickInfo, _this._currentPickResult);
  24662. };
  24663. this._spritePredicate = function (sprite) {
  24664. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  24665. };
  24666. this._onPointerMove = function (evt) {
  24667. _this._updatePointerPosition(evt);
  24668. // PreObservable support
  24669. if (_this.onPrePointerObservable.hasObservers()) {
  24670. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24671. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24672. _this.onPrePointerObservable.notifyObservers(pi, type);
  24673. if (pi.skipOnPointerObservable) {
  24674. return;
  24675. }
  24676. }
  24677. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24678. return;
  24679. }
  24680. if (!_this.pointerMovePredicate) {
  24681. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  24682. }
  24683. // Meshes
  24684. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  24685. _this._processPointerMove(pickResult, evt);
  24686. };
  24687. this._onPointerDown = function (evt) {
  24688. _this._totalPointersPressed++;
  24689. _this._pickedDownMesh = null;
  24690. _this._meshPickProceed = false;
  24691. _this._updatePointerPosition(evt);
  24692. if (_this.preventDefaultOnPointerDown && canvas) {
  24693. evt.preventDefault();
  24694. canvas.focus();
  24695. }
  24696. // PreObservable support
  24697. if (_this.onPrePointerObservable.hasObservers()) {
  24698. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24699. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24700. _this.onPrePointerObservable.notifyObservers(pi, type);
  24701. if (pi.skipOnPointerObservable) {
  24702. return;
  24703. }
  24704. }
  24705. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24706. return;
  24707. }
  24708. _this._startingPointerPosition.x = _this._pointerX;
  24709. _this._startingPointerPosition.y = _this._pointerY;
  24710. _this._startingPointerTime = new Date().getTime();
  24711. if (!_this.pointerDownPredicate) {
  24712. _this.pointerDownPredicate = function (mesh) {
  24713. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24714. };
  24715. }
  24716. // Meshes
  24717. _this._pickedDownMesh = null;
  24718. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24719. _this._processPointerDown(pickResult, evt);
  24720. // Sprites
  24721. _this._pickedDownSprite = null;
  24722. if (_this.spriteManagers.length > 0) {
  24723. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24724. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24725. if (pickResult.pickedSprite.actionManager) {
  24726. _this._pickedDownSprite = pickResult.pickedSprite;
  24727. switch (evt.button) {
  24728. case 0:
  24729. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24730. break;
  24731. case 1:
  24732. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24733. break;
  24734. case 2:
  24735. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24736. break;
  24737. }
  24738. if (pickResult.pickedSprite.actionManager) {
  24739. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24740. }
  24741. }
  24742. }
  24743. }
  24744. };
  24745. this._onPointerUp = function (evt) {
  24746. if (_this._totalPointersPressed === 0) {
  24747. return; // So we need to test it the pointer down was pressed before.
  24748. }
  24749. _this._totalPointersPressed--;
  24750. _this._pickedUpMesh = null;
  24751. _this._meshPickProceed = false;
  24752. _this._updatePointerPosition(evt);
  24753. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  24754. // PreObservable support
  24755. if (_this.onPrePointerObservable.hasObservers()) {
  24756. if (!clickInfo.ignore) {
  24757. if (!clickInfo.hasSwiped) {
  24758. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24759. var type = BABYLON.PointerEventTypes.POINTERTAP;
  24760. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24761. _this.onPrePointerObservable.notifyObservers(pi, type);
  24762. if (pi.skipOnPointerObservable) {
  24763. return;
  24764. }
  24765. }
  24766. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24767. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24768. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24769. _this.onPrePointerObservable.notifyObservers(pi, type);
  24770. if (pi.skipOnPointerObservable) {
  24771. return;
  24772. }
  24773. }
  24774. }
  24775. }
  24776. else {
  24777. var type = BABYLON.PointerEventTypes.POINTERUP;
  24778. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24779. _this.onPrePointerObservable.notifyObservers(pi, type);
  24780. if (pi.skipOnPointerObservable) {
  24781. return;
  24782. }
  24783. }
  24784. }
  24785. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24786. return;
  24787. }
  24788. if (!_this.pointerUpPredicate) {
  24789. _this.pointerUpPredicate = function (mesh) {
  24790. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24791. };
  24792. }
  24793. // Meshes
  24794. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  24795. _this._initActionManager(null, clickInfo);
  24796. }
  24797. if (!pickResult) {
  24798. pickResult = _this._currentPickResult;
  24799. }
  24800. _this._processPointerUp(pickResult, evt, clickInfo);
  24801. // Sprites
  24802. if (_this.spriteManagers.length > 0) {
  24803. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24804. if (spritePickResult) {
  24805. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  24806. if (spritePickResult.pickedSprite.actionManager) {
  24807. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24808. if (spritePickResult.pickedSprite.actionManager) {
  24809. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  24810. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24811. }
  24812. }
  24813. }
  24814. }
  24815. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  24816. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  24817. }
  24818. }
  24819. }
  24820. _this._previousPickResult = _this._currentPickResult;
  24821. });
  24822. };
  24823. this._onKeyDown = function (evt) {
  24824. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  24825. if (_this.onPreKeyboardObservable.hasObservers()) {
  24826. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24827. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24828. if (pi.skipOnPointerObservable) {
  24829. return;
  24830. }
  24831. }
  24832. if (_this.onKeyboardObservable.hasObservers()) {
  24833. var pi = new BABYLON.KeyboardInfo(type, evt);
  24834. _this.onKeyboardObservable.notifyObservers(pi, type);
  24835. }
  24836. if (_this.actionManager) {
  24837. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24838. }
  24839. };
  24840. this._onKeyUp = function (evt) {
  24841. var type = BABYLON.KeyboardEventTypes.KEYUP;
  24842. if (_this.onPreKeyboardObservable.hasObservers()) {
  24843. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24844. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24845. if (pi.skipOnPointerObservable) {
  24846. return;
  24847. }
  24848. }
  24849. if (_this.onKeyboardObservable.hasObservers()) {
  24850. var pi = new BABYLON.KeyboardInfo(type, evt);
  24851. _this.onKeyboardObservable.notifyObservers(pi, type);
  24852. }
  24853. if (_this.actionManager) {
  24854. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24855. }
  24856. };
  24857. var engine = this.getEngine();
  24858. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  24859. if (!canvas) {
  24860. return;
  24861. }
  24862. canvas.addEventListener("keydown", _this._onKeyDown, false);
  24863. canvas.addEventListener("keyup", _this._onKeyUp, false);
  24864. });
  24865. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  24866. if (!canvas) {
  24867. return;
  24868. }
  24869. canvas.removeEventListener("keydown", _this._onKeyDown);
  24870. canvas.removeEventListener("keyup", _this._onKeyUp);
  24871. });
  24872. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  24873. var canvas = this._engine.getRenderingCanvas();
  24874. if (!canvas) {
  24875. return;
  24876. }
  24877. if (attachMove) {
  24878. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  24879. // Wheel
  24880. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  24881. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  24882. }
  24883. if (attachDown) {
  24884. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  24885. }
  24886. if (attachUp) {
  24887. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  24888. }
  24889. canvas.tabIndex = 1;
  24890. };
  24891. /** Detaches all event handlers*/
  24892. Scene.prototype.detachControl = function () {
  24893. var engine = this.getEngine();
  24894. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  24895. var canvas = engine.getRenderingCanvas();
  24896. if (!canvas) {
  24897. return;
  24898. }
  24899. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  24900. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  24901. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  24902. if (this._onCanvasBlurObserver) {
  24903. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  24904. }
  24905. if (this._onCanvasFocusObserver) {
  24906. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  24907. }
  24908. // Wheel
  24909. canvas.removeEventListener('mousewheel', this._onPointerMove);
  24910. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  24911. // Keyboard
  24912. canvas.removeEventListener("keydown", this._onKeyDown);
  24913. canvas.removeEventListener("keyup", this._onKeyUp);
  24914. // Observables
  24915. this.onKeyboardObservable.clear();
  24916. this.onPreKeyboardObservable.clear();
  24917. this.onPointerObservable.clear();
  24918. this.onPrePointerObservable.clear();
  24919. };
  24920. /**
  24921. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  24922. * Delay loaded resources are not taking in account
  24923. * @return true if all required resources are ready
  24924. */
  24925. Scene.prototype.isReady = function () {
  24926. if (this._isDisposed) {
  24927. return false;
  24928. }
  24929. if (this._pendingData.length > 0) {
  24930. return false;
  24931. }
  24932. var index;
  24933. var engine = this.getEngine();
  24934. // Geometries
  24935. for (index = 0; index < this._geometries.length; index++) {
  24936. var geometry = this._geometries[index];
  24937. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24938. return false;
  24939. }
  24940. }
  24941. // Meshes
  24942. for (index = 0; index < this.meshes.length; index++) {
  24943. var mesh = this.meshes[index];
  24944. if (!mesh.isEnabled()) {
  24945. continue;
  24946. }
  24947. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24948. continue;
  24949. }
  24950. if (!mesh.isReady(true)) {
  24951. return false;
  24952. }
  24953. // Effect layers
  24954. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  24955. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  24956. var layer = _a[_i];
  24957. if (!layer.hasMesh(mesh)) {
  24958. continue;
  24959. }
  24960. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24961. var subMesh = _c[_b];
  24962. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  24963. return false;
  24964. }
  24965. }
  24966. }
  24967. }
  24968. // Post-processes
  24969. if (this.activeCameras && this.activeCameras.length > 0) {
  24970. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  24971. var camera = _e[_d];
  24972. if (!camera.isReady(true)) {
  24973. return false;
  24974. }
  24975. }
  24976. }
  24977. else if (this.activeCamera) {
  24978. if (!this.activeCamera.isReady(true)) {
  24979. return false;
  24980. }
  24981. }
  24982. // Particles
  24983. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  24984. var particleSystem = _g[_f];
  24985. if (!particleSystem.isReady()) {
  24986. return false;
  24987. }
  24988. }
  24989. return true;
  24990. };
  24991. /** Resets all cached information relative to material (including effect and visibility) */
  24992. Scene.prototype.resetCachedMaterial = function () {
  24993. this._cachedMaterial = null;
  24994. this._cachedEffect = null;
  24995. this._cachedVisibility = null;
  24996. };
  24997. /**
  24998. * Registers a function to be called before every frame render
  24999. * @param func defines the function to register
  25000. */
  25001. Scene.prototype.registerBeforeRender = function (func) {
  25002. this.onBeforeRenderObservable.add(func);
  25003. };
  25004. /**
  25005. * Unregisters a function called before every frame render
  25006. * @param func defines the function to unregister
  25007. */
  25008. Scene.prototype.unregisterBeforeRender = function (func) {
  25009. this.onBeforeRenderObservable.removeCallback(func);
  25010. };
  25011. /**
  25012. * Registers a function to be called after every frame render
  25013. * @param func defines the function to register
  25014. */
  25015. Scene.prototype.registerAfterRender = function (func) {
  25016. this.onAfterRenderObservable.add(func);
  25017. };
  25018. /**
  25019. * Unregisters a function called after every frame render
  25020. * @param func defines the function to unregister
  25021. */
  25022. Scene.prototype.unregisterAfterRender = function (func) {
  25023. this.onAfterRenderObservable.removeCallback(func);
  25024. };
  25025. Scene.prototype._executeOnceBeforeRender = function (func) {
  25026. var _this = this;
  25027. var execFunc = function () {
  25028. func();
  25029. setTimeout(function () {
  25030. _this.unregisterBeforeRender(execFunc);
  25031. });
  25032. };
  25033. this.registerBeforeRender(execFunc);
  25034. };
  25035. /**
  25036. * The provided function will run before render once and will be disposed afterwards.
  25037. * A timeout delay can be provided so that the function will be executed in N ms.
  25038. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25039. * @param func The function to be executed.
  25040. * @param timeout optional delay in ms
  25041. */
  25042. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25043. var _this = this;
  25044. if (timeout !== undefined) {
  25045. setTimeout(function () {
  25046. _this._executeOnceBeforeRender(func);
  25047. }, timeout);
  25048. }
  25049. else {
  25050. this._executeOnceBeforeRender(func);
  25051. }
  25052. };
  25053. /** @ignore */
  25054. Scene.prototype._addPendingData = function (data) {
  25055. this._pendingData.push(data);
  25056. };
  25057. /** @ignore */
  25058. Scene.prototype._removePendingData = function (data) {
  25059. var wasLoading = this.isLoading;
  25060. var index = this._pendingData.indexOf(data);
  25061. if (index !== -1) {
  25062. this._pendingData.splice(index, 1);
  25063. }
  25064. if (wasLoading && !this.isLoading) {
  25065. this.onDataLoadedObservable.notifyObservers(this);
  25066. }
  25067. };
  25068. /**
  25069. * Returns the number of items waiting to be loaded
  25070. * @returns the number of items waiting to be loaded
  25071. */
  25072. Scene.prototype.getWaitingItemsCount = function () {
  25073. return this._pendingData.length;
  25074. };
  25075. Object.defineProperty(Scene.prototype, "isLoading", {
  25076. /**
  25077. * Returns a boolean indicating if the scene is still loading data
  25078. */
  25079. get: function () {
  25080. return this._pendingData.length > 0;
  25081. },
  25082. enumerable: true,
  25083. configurable: true
  25084. });
  25085. /**
  25086. * Registers a function to be executed when the scene is ready
  25087. * @param {Function} func - the function to be executed
  25088. */
  25089. Scene.prototype.executeWhenReady = function (func) {
  25090. var _this = this;
  25091. this.onReadyObservable.add(func);
  25092. if (this._executeWhenReadyTimeoutId !== -1) {
  25093. return;
  25094. }
  25095. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25096. _this._checkIsReady();
  25097. }, 150);
  25098. };
  25099. /**
  25100. * Returns a promise that resolves when the scene is ready
  25101. * @returns A promise that resolves when the scene is ready
  25102. */
  25103. Scene.prototype.whenReadyAsync = function () {
  25104. var _this = this;
  25105. return new Promise(function (resolve) {
  25106. _this.executeWhenReady(function () {
  25107. resolve();
  25108. });
  25109. });
  25110. };
  25111. /** @ignore */
  25112. Scene.prototype._checkIsReady = function () {
  25113. var _this = this;
  25114. if (this.isReady()) {
  25115. this.onReadyObservable.notifyObservers(this);
  25116. this.onReadyObservable.clear();
  25117. this._executeWhenReadyTimeoutId = -1;
  25118. return;
  25119. }
  25120. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25121. _this._checkIsReady();
  25122. }, 150);
  25123. };
  25124. // Animations
  25125. /**
  25126. * Will start the animation sequence of a given target
  25127. * @param target defines the target
  25128. * @param from defines from which frame should animation start
  25129. * @param to defines until which frame should animation run.
  25130. * @param weight defines the weight to apply to the animation (1.0 by default)
  25131. * @param loop defines if the animation loops
  25132. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25133. * @param onAnimationEnd defines the function to be executed when the animation ends
  25134. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25135. * @returns the animatable object created for this animation
  25136. */
  25137. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25138. if (weight === void 0) { weight = 1.0; }
  25139. if (speedRatio === void 0) { speedRatio = 1.0; }
  25140. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25141. returnedAnimatable.weight = weight;
  25142. return returnedAnimatable;
  25143. };
  25144. /**
  25145. * Will start the animation sequence of a given target
  25146. * @param target defines the target
  25147. * @param from defines from which frame should animation start
  25148. * @param to defines until which frame should animation run.
  25149. * @param loop defines if the animation loops
  25150. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25151. * @param onAnimationEnd defines the function to be executed when the animation ends
  25152. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25153. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25154. * @returns the animatable object created for this animation
  25155. */
  25156. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25157. if (speedRatio === void 0) { speedRatio = 1.0; }
  25158. if (stopCurrent === void 0) { stopCurrent = true; }
  25159. if (from > to && speedRatio > 0) {
  25160. speedRatio *= -1;
  25161. }
  25162. if (stopCurrent) {
  25163. this.stopAnimation(target);
  25164. }
  25165. if (!animatable) {
  25166. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25167. }
  25168. // Local animations
  25169. if (target.animations) {
  25170. animatable.appendAnimations(target, target.animations);
  25171. }
  25172. // Children animations
  25173. if (target.getAnimatables) {
  25174. var animatables = target.getAnimatables();
  25175. for (var index = 0; index < animatables.length; index++) {
  25176. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25177. }
  25178. }
  25179. animatable.reset();
  25180. return animatable;
  25181. };
  25182. /**
  25183. * Begin a new animation on a given node
  25184. * @param target defines the target where the animation will take place
  25185. * @param animations defines the list of animations to start
  25186. * @param from defines the initial value
  25187. * @param to defines the final value
  25188. * @param loop defines if you want animation to loop (off by default)
  25189. * @param speedRatio defines the speed ratio to apply to all animations
  25190. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25191. * @returns the list of created animatables
  25192. */
  25193. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25194. if (speedRatio === undefined) {
  25195. speedRatio = 1.0;
  25196. }
  25197. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25198. return animatable;
  25199. };
  25200. /**
  25201. * Begin a new animation on a given node and its hierarchy
  25202. * @param target defines the root node where the animation will take place
  25203. * @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.
  25204. * @param animations defines the list of animations to start
  25205. * @param from defines the initial value
  25206. * @param to defines the final value
  25207. * @param loop defines if you want animation to loop (off by default)
  25208. * @param speedRatio defines the speed ratio to apply to all animations
  25209. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25210. * @returns the list of animatables created for all nodes
  25211. */
  25212. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25213. var children = target.getDescendants(directDescendantsOnly);
  25214. var result = [];
  25215. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25216. var child = children_1[_i];
  25217. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25218. }
  25219. return result;
  25220. };
  25221. /**
  25222. * Gets the animatable associated with a specific target
  25223. * @param target defines the target of the animatable
  25224. * @returns the required animatable if found
  25225. */
  25226. Scene.prototype.getAnimatableByTarget = function (target) {
  25227. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25228. if (this._activeAnimatables[index].target === target) {
  25229. return this._activeAnimatables[index];
  25230. }
  25231. }
  25232. return null;
  25233. };
  25234. /**
  25235. * Gets all animatables associated with a given target
  25236. * @param target defines the target to look animatables for
  25237. * @returns an array of Animatables
  25238. */
  25239. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25240. var result = [];
  25241. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25242. if (this._activeAnimatables[index].target === target) {
  25243. result.push(this._activeAnimatables[index]);
  25244. }
  25245. }
  25246. return result;
  25247. };
  25248. Object.defineProperty(Scene.prototype, "animatables", {
  25249. /**
  25250. * Gets all animatable attached to the scene
  25251. */
  25252. get: function () {
  25253. return this._activeAnimatables;
  25254. },
  25255. enumerable: true,
  25256. configurable: true
  25257. });
  25258. /**
  25259. * Will stop the animation of the given target
  25260. * @param target - the target
  25261. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25262. */
  25263. Scene.prototype.stopAnimation = function (target, animationName) {
  25264. var animatables = this.getAllAnimatablesByTarget(target);
  25265. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25266. var animatable = animatables_1[_i];
  25267. animatable.stop(animationName);
  25268. }
  25269. };
  25270. /**
  25271. * Stops and removes all animations that have been applied to the scene
  25272. */
  25273. Scene.prototype.stopAllAnimations = function () {
  25274. if (this._activeAnimatables) {
  25275. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25276. this._activeAnimatables[i].stop();
  25277. }
  25278. this._activeAnimatables = [];
  25279. }
  25280. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25281. var group = _a[_i];
  25282. group.stop();
  25283. }
  25284. };
  25285. Scene.prototype._animate = function () {
  25286. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25287. return;
  25288. }
  25289. // Getting time
  25290. var now = BABYLON.Tools.Now;
  25291. if (!this._animationTimeLast) {
  25292. if (this._pendingData.length > 0) {
  25293. return;
  25294. }
  25295. this._animationTimeLast = now;
  25296. }
  25297. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25298. this._animationTime += deltaTime;
  25299. this._animationTimeLast = now;
  25300. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25301. this._activeAnimatables[index]._animate(this._animationTime);
  25302. }
  25303. // Late animation bindings
  25304. this._processLateAnimationBindings();
  25305. };
  25306. /** @ignore */
  25307. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25308. var target = runtimeAnimation.target;
  25309. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25310. if (!target._lateAnimationHolders) {
  25311. target._lateAnimationHolders = {};
  25312. }
  25313. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25314. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25315. totalWeight: 0,
  25316. animations: []
  25317. };
  25318. }
  25319. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25320. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25321. };
  25322. Scene.prototype._processLateAnimationBindings = function () {
  25323. if (!this._registeredForLateAnimationBindings.length) {
  25324. return;
  25325. }
  25326. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25327. var target = this._registeredForLateAnimationBindings.data[index];
  25328. for (var path in target._lateAnimationHolders) {
  25329. var holder = target._lateAnimationHolders[path];
  25330. var originalValue = holder.animations[0].originalValue;
  25331. // Sanity check
  25332. if (!originalValue.scaleAndAddToRef) {
  25333. continue;
  25334. }
  25335. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25336. var normalizer = 1.0;
  25337. var finalValue = void 0;
  25338. if (holder.totalWeight < 1.0) {
  25339. // We need to mix the original value in
  25340. if (matrixDecomposeMode) {
  25341. finalValue = originalValue.clone();
  25342. }
  25343. else {
  25344. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25345. }
  25346. }
  25347. else {
  25348. // We need to normalize the weights
  25349. normalizer = holder.totalWeight;
  25350. }
  25351. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25352. var runtimeAnimation = holder.animations[animIndex];
  25353. var scale = runtimeAnimation.weight / normalizer;
  25354. if (finalValue) {
  25355. if (matrixDecomposeMode) {
  25356. BABYLON.Matrix.DecomposeLerpToRef(finalValue, runtimeAnimation.currentValue, scale, finalValue);
  25357. }
  25358. else {
  25359. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25360. }
  25361. }
  25362. else {
  25363. if (scale !== 1) {
  25364. if (matrixDecomposeMode) {
  25365. finalValue = runtimeAnimation.currentValue.clone();
  25366. }
  25367. else {
  25368. finalValue = runtimeAnimation.currentValue.scale(scale);
  25369. }
  25370. }
  25371. else {
  25372. finalValue = runtimeAnimation.currentValue;
  25373. }
  25374. }
  25375. }
  25376. runtimeAnimation.target[path] = finalValue;
  25377. }
  25378. target._lateAnimationHolders = {};
  25379. }
  25380. this._registeredForLateAnimationBindings.reset();
  25381. };
  25382. // Matrix
  25383. /** @ignore */
  25384. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25385. this._useAlternateCameraConfiguration = active;
  25386. };
  25387. /**
  25388. * Gets the current view matrix
  25389. * @returns a Matrix
  25390. */
  25391. Scene.prototype.getViewMatrix = function () {
  25392. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25393. };
  25394. /**
  25395. * Gets the current projection matrix
  25396. * @returns a Matrix
  25397. */
  25398. Scene.prototype.getProjectionMatrix = function () {
  25399. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25400. };
  25401. /**
  25402. * Gets the current transform matrix
  25403. * @returns a Matrix made of View * Projection
  25404. */
  25405. Scene.prototype.getTransformMatrix = function () {
  25406. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25407. };
  25408. /**
  25409. * Sets the current transform matrix
  25410. * @param view defines the View matrix to use
  25411. * @param projection defines the Projection matrix to use
  25412. */
  25413. Scene.prototype.setTransformMatrix = function (view, projection) {
  25414. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25415. return;
  25416. }
  25417. this._viewUpdateFlag = view.updateFlag;
  25418. this._projectionUpdateFlag = projection.updateFlag;
  25419. this._viewMatrix = view;
  25420. this._projectionMatrix = projection;
  25421. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25422. // Update frustum
  25423. if (!this._frustumPlanes) {
  25424. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25425. }
  25426. else {
  25427. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25428. }
  25429. if (this.activeCamera && this.activeCamera._alternateCamera) {
  25430. var otherCamera = this.activeCamera._alternateCamera;
  25431. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  25432. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  25433. }
  25434. if (this._sceneUbo.useUbo) {
  25435. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  25436. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  25437. this._sceneUbo.update();
  25438. }
  25439. };
  25440. /** @ignore */
  25441. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  25442. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  25443. return;
  25444. }
  25445. this._alternateViewUpdateFlag = view.updateFlag;
  25446. this._alternateProjectionUpdateFlag = projection.updateFlag;
  25447. this._alternateViewMatrix = view;
  25448. this._alternateProjectionMatrix = projection;
  25449. if (!this._alternateTransformMatrix) {
  25450. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  25451. }
  25452. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  25453. if (!this._alternateSceneUbo) {
  25454. this._createAlternateUbo();
  25455. }
  25456. if (this._alternateSceneUbo.useUbo) {
  25457. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  25458. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  25459. this._alternateSceneUbo.update();
  25460. }
  25461. };
  25462. /**
  25463. * Gets the uniform buffer used to store scene data
  25464. * @returns a UniformBuffer
  25465. */
  25466. Scene.prototype.getSceneUniformBuffer = function () {
  25467. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  25468. };
  25469. /**
  25470. * Gets an unique (relatively to the current scene) Id
  25471. * @returns an unique number for the scene
  25472. */
  25473. Scene.prototype.getUniqueId = function () {
  25474. var result = Scene._uniqueIdCounter;
  25475. Scene._uniqueIdCounter++;
  25476. return result;
  25477. };
  25478. /**
  25479. * Add a mesh to the list of scene's meshes
  25480. * @param newMesh defines the mesh to add
  25481. */
  25482. Scene.prototype.addMesh = function (newMesh) {
  25483. this.meshes.push(newMesh);
  25484. //notify the collision coordinator
  25485. if (this.collisionCoordinator) {
  25486. this.collisionCoordinator.onMeshAdded(newMesh);
  25487. }
  25488. newMesh._resyncLightSources();
  25489. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  25490. };
  25491. /**
  25492. * Remove a mesh for the list of scene's meshes
  25493. * @param toRemove defines the mesh to remove
  25494. * @returns the index where the mesh was in the mesh list
  25495. */
  25496. Scene.prototype.removeMesh = function (toRemove) {
  25497. var index = this.meshes.indexOf(toRemove);
  25498. if (index !== -1) {
  25499. // Remove from the scene if mesh found
  25500. this.meshes.splice(index, 1);
  25501. }
  25502. this.onMeshRemovedObservable.notifyObservers(toRemove);
  25503. return index;
  25504. };
  25505. /**
  25506. * Add a transform node to the list of scene's transform nodes
  25507. * @param newTransformNode defines the transform node to add
  25508. */
  25509. Scene.prototype.addTransformNode = function (newTransformNode) {
  25510. this.transformNodes.push(newTransformNode);
  25511. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  25512. };
  25513. /**
  25514. * Remove a transform node for the list of scene's transform nodes
  25515. * @param toRemove defines the transform node to remove
  25516. * @returns the index where the transform node was in the transform node list
  25517. */
  25518. Scene.prototype.removeTransformNode = function (toRemove) {
  25519. var index = this.transformNodes.indexOf(toRemove);
  25520. if (index !== -1) {
  25521. // Remove from the scene if found
  25522. this.transformNodes.splice(index, 1);
  25523. }
  25524. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  25525. return index;
  25526. };
  25527. /**
  25528. * Remove a skeleton for the list of scene's skeletons
  25529. * @param toRemove defines the skeleton to remove
  25530. * @returns the index where the skeleton was in the skeleton list
  25531. */
  25532. Scene.prototype.removeSkeleton = function (toRemove) {
  25533. var index = this.skeletons.indexOf(toRemove);
  25534. if (index !== -1) {
  25535. // Remove from the scene if found
  25536. this.skeletons.splice(index, 1);
  25537. }
  25538. return index;
  25539. };
  25540. /**
  25541. * Remove a morph target for the list of scene's morph targets
  25542. * @param toRemove defines the morph target to remove
  25543. * @returns the index where the morph target was in the morph target list
  25544. */
  25545. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  25546. var index = this.morphTargetManagers.indexOf(toRemove);
  25547. if (index !== -1) {
  25548. // Remove from the scene if found
  25549. this.morphTargetManagers.splice(index, 1);
  25550. }
  25551. return index;
  25552. };
  25553. /**
  25554. * Remove a light for the list of scene's lights
  25555. * @param toRemove defines the light to remove
  25556. * @returns the index where the light was in the light list
  25557. */
  25558. Scene.prototype.removeLight = function (toRemove) {
  25559. var index = this.lights.indexOf(toRemove);
  25560. if (index !== -1) {
  25561. // Remove from meshes
  25562. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25563. var mesh = _a[_i];
  25564. mesh._removeLightSource(toRemove);
  25565. }
  25566. // Remove from the scene if mesh found
  25567. this.lights.splice(index, 1);
  25568. this.sortLightsByPriority();
  25569. }
  25570. this.onLightRemovedObservable.notifyObservers(toRemove);
  25571. return index;
  25572. };
  25573. /**
  25574. * Remove a camera for the list of scene's cameras
  25575. * @param toRemove defines the camera to remove
  25576. * @returns the index where the camera was in the camera list
  25577. */
  25578. Scene.prototype.removeCamera = function (toRemove) {
  25579. var index = this.cameras.indexOf(toRemove);
  25580. if (index !== -1) {
  25581. // Remove from the scene if mesh found
  25582. this.cameras.splice(index, 1);
  25583. }
  25584. // Remove from activeCameras
  25585. var index2 = this.activeCameras.indexOf(toRemove);
  25586. if (index2 !== -1) {
  25587. // Remove from the scene if mesh found
  25588. this.activeCameras.splice(index2, 1);
  25589. }
  25590. // Reset the activeCamera
  25591. if (this.activeCamera === toRemove) {
  25592. if (this.cameras.length > 0) {
  25593. this.activeCamera = this.cameras[0];
  25594. }
  25595. else {
  25596. this.activeCamera = null;
  25597. }
  25598. }
  25599. this.onCameraRemovedObservable.notifyObservers(toRemove);
  25600. return index;
  25601. };
  25602. /**
  25603. * Remove a particle system for the list of scene's particle systems
  25604. * @param toRemove defines the particle system to remove
  25605. * @returns the index where the particle system was in the particle system list
  25606. */
  25607. Scene.prototype.removeParticleSystem = function (toRemove) {
  25608. var index = this.particleSystems.indexOf(toRemove);
  25609. if (index !== -1) {
  25610. this.particleSystems.splice(index, 1);
  25611. }
  25612. return index;
  25613. };
  25614. /**
  25615. * Remove a animation for the list of scene's animations
  25616. * @param toRemove defines the animation to remove
  25617. * @returns the index where the animation was in the animation list
  25618. */
  25619. Scene.prototype.removeAnimation = function (toRemove) {
  25620. var index = this.animations.indexOf(toRemove);
  25621. if (index !== -1) {
  25622. this.animations.splice(index, 1);
  25623. }
  25624. return index;
  25625. };
  25626. /**
  25627. * Removes the given animation group from this scene.
  25628. * @param toRemove The animation group to remove
  25629. * @returns The index of the removed animation group
  25630. */
  25631. Scene.prototype.removeAnimationGroup = function (toRemove) {
  25632. var index = this.animationGroups.indexOf(toRemove);
  25633. if (index !== -1) {
  25634. this.animationGroups.splice(index, 1);
  25635. }
  25636. return index;
  25637. };
  25638. /**
  25639. * Removes the given multi-material from this scene.
  25640. * @param toRemove The multi-material to remove
  25641. * @returns The index of the removed multi-material
  25642. */
  25643. Scene.prototype.removeMultiMaterial = function (toRemove) {
  25644. var index = this.multiMaterials.indexOf(toRemove);
  25645. if (index !== -1) {
  25646. this.multiMaterials.splice(index, 1);
  25647. }
  25648. return index;
  25649. };
  25650. /**
  25651. * Removes the given material from this scene.
  25652. * @param toRemove The material to remove
  25653. * @returns The index of the removed material
  25654. */
  25655. Scene.prototype.removeMaterial = function (toRemove) {
  25656. var index = this.materials.indexOf(toRemove);
  25657. if (index !== -1) {
  25658. this.materials.splice(index, 1);
  25659. }
  25660. return index;
  25661. };
  25662. /**
  25663. * Removes the given lens flare system from this scene.
  25664. * @param toRemove The lens flare system to remove
  25665. * @returns The index of the removed lens flare system
  25666. */
  25667. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  25668. var index = this.lensFlareSystems.indexOf(toRemove);
  25669. if (index !== -1) {
  25670. this.lensFlareSystems.splice(index, 1);
  25671. }
  25672. return index;
  25673. };
  25674. /**
  25675. * Removes the given action manager from this scene.
  25676. * @param toRemove The action manager to remove
  25677. * @returns The index of the removed action manager
  25678. */
  25679. Scene.prototype.removeActionManager = function (toRemove) {
  25680. var index = this._actionManagers.indexOf(toRemove);
  25681. if (index !== -1) {
  25682. this._actionManagers.splice(index, 1);
  25683. }
  25684. return index;
  25685. };
  25686. /**
  25687. * Removes the given effect layer from this scene.
  25688. * @param toRemove defines the effect layer to remove
  25689. * @returns the index of the removed effect layer
  25690. */
  25691. Scene.prototype.removeEffectLayer = function (toRemove) {
  25692. var index = this.effectLayers.indexOf(toRemove);
  25693. if (index !== -1) {
  25694. this.effectLayers.splice(index, 1);
  25695. }
  25696. return index;
  25697. };
  25698. /**
  25699. * Removes the given texture from this scene.
  25700. * @param toRemove The texture to remove
  25701. * @returns The index of the removed texture
  25702. */
  25703. Scene.prototype.removeTexture = function (toRemove) {
  25704. var index = this.textures.indexOf(toRemove);
  25705. if (index !== -1) {
  25706. this.textures.splice(index, 1);
  25707. }
  25708. return index;
  25709. };
  25710. /**
  25711. * Adds the given light to this scene
  25712. * @param newLight The light to add
  25713. */
  25714. Scene.prototype.addLight = function (newLight) {
  25715. this.lights.push(newLight);
  25716. this.sortLightsByPriority();
  25717. // Add light to all meshes (To support if the light is removed and then readded)
  25718. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25719. var mesh = _a[_i];
  25720. if (mesh._lightSources.indexOf(newLight) === -1) {
  25721. mesh._lightSources.push(newLight);
  25722. mesh._resyncLightSources();
  25723. }
  25724. }
  25725. this.onNewLightAddedObservable.notifyObservers(newLight);
  25726. };
  25727. /**
  25728. * Sorts the list list based on light priorities
  25729. */
  25730. Scene.prototype.sortLightsByPriority = function () {
  25731. if (this.requireLightSorting) {
  25732. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  25733. }
  25734. };
  25735. /**
  25736. * Adds the given camera to this scene
  25737. * @param newCamera The camera to add
  25738. */
  25739. Scene.prototype.addCamera = function (newCamera) {
  25740. this.cameras.push(newCamera);
  25741. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  25742. };
  25743. /**
  25744. * Adds the given skeleton to this scene
  25745. * @param newSkeleton The skeleton to add
  25746. */
  25747. Scene.prototype.addSkeleton = function (newSkeleton) {
  25748. this.skeletons.push(newSkeleton);
  25749. };
  25750. /**
  25751. * Adds the given particle system to this scene
  25752. * @param newParticleSystem The particle system to add
  25753. */
  25754. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  25755. this.particleSystems.push(newParticleSystem);
  25756. };
  25757. /**
  25758. * Adds the given animation to this scene
  25759. * @param newAnimation The animation to add
  25760. */
  25761. Scene.prototype.addAnimation = function (newAnimation) {
  25762. this.animations.push(newAnimation);
  25763. };
  25764. /**
  25765. * Adds the given animation group to this scene.
  25766. * @param newAnimationGroup The animation group to add
  25767. */
  25768. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  25769. this.animationGroups.push(newAnimationGroup);
  25770. };
  25771. /**
  25772. * Adds the given multi-material to this scene
  25773. * @param newMultiMaterial The multi-material to add
  25774. */
  25775. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  25776. this.multiMaterials.push(newMultiMaterial);
  25777. };
  25778. /**
  25779. * Adds the given material to this scene
  25780. * @param newMaterial The material to add
  25781. */
  25782. Scene.prototype.addMaterial = function (newMaterial) {
  25783. this.materials.push(newMaterial);
  25784. };
  25785. /**
  25786. * Adds the given morph target to this scene
  25787. * @param newMorphTargetManager The morph target to add
  25788. */
  25789. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  25790. this.morphTargetManagers.push(newMorphTargetManager);
  25791. };
  25792. /**
  25793. * Adds the given geometry to this scene
  25794. * @param newGeometry The geometry to add
  25795. */
  25796. Scene.prototype.addGeometry = function (newGeometry) {
  25797. this._geometries.push(newGeometry);
  25798. };
  25799. /**
  25800. * Adds the given lens flare system to this scene
  25801. * @param newLensFlareSystem The lens flare system to add
  25802. */
  25803. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  25804. this.lensFlareSystems.push(newLensFlareSystem);
  25805. };
  25806. /**
  25807. * Adds the given effect layer to this scene
  25808. * @param newEffectLayer defines the effect layer to add
  25809. */
  25810. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  25811. this.effectLayers.push(newEffectLayer);
  25812. };
  25813. /**
  25814. * Adds the given action manager to this scene
  25815. * @param newActionManager The action manager to add
  25816. */
  25817. Scene.prototype.addActionManager = function (newActionManager) {
  25818. this._actionManagers.push(newActionManager);
  25819. };
  25820. /**
  25821. * Adds the given texture to this scene.
  25822. * @param newTexture The texture to add
  25823. */
  25824. Scene.prototype.addTexture = function (newTexture) {
  25825. this.textures.push(newTexture);
  25826. };
  25827. /**
  25828. * Switch active camera
  25829. * @param newCamera defines the new active camera
  25830. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  25831. */
  25832. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  25833. if (attachControl === void 0) { attachControl = true; }
  25834. var canvas = this._engine.getRenderingCanvas();
  25835. if (!canvas) {
  25836. return;
  25837. }
  25838. if (this.activeCamera) {
  25839. this.activeCamera.detachControl(canvas);
  25840. }
  25841. this.activeCamera = newCamera;
  25842. if (attachControl) {
  25843. newCamera.attachControl(canvas);
  25844. }
  25845. };
  25846. /**
  25847. * sets the active camera of the scene using its ID
  25848. * @param id defines the camera's ID
  25849. * @return the new active camera or null if none found.
  25850. */
  25851. Scene.prototype.setActiveCameraByID = function (id) {
  25852. var camera = this.getCameraByID(id);
  25853. if (camera) {
  25854. this.activeCamera = camera;
  25855. return camera;
  25856. }
  25857. return null;
  25858. };
  25859. /**
  25860. * sets the active camera of the scene using its name
  25861. * @param name defines the camera's name
  25862. * @returns the new active camera or null if none found.
  25863. */
  25864. Scene.prototype.setActiveCameraByName = function (name) {
  25865. var camera = this.getCameraByName(name);
  25866. if (camera) {
  25867. this.activeCamera = camera;
  25868. return camera;
  25869. }
  25870. return null;
  25871. };
  25872. /**
  25873. * get an animation group using its name
  25874. * @param name defines the material's name
  25875. * @return the animation group or null if none found.
  25876. */
  25877. Scene.prototype.getAnimationGroupByName = function (name) {
  25878. for (var index = 0; index < this.animationGroups.length; index++) {
  25879. if (this.animationGroups[index].name === name) {
  25880. return this.animationGroups[index];
  25881. }
  25882. }
  25883. return null;
  25884. };
  25885. /**
  25886. * get a material using its id
  25887. * @param id defines the material's ID
  25888. * @return the material or null if none found.
  25889. */
  25890. Scene.prototype.getMaterialByID = function (id) {
  25891. for (var index = 0; index < this.materials.length; index++) {
  25892. if (this.materials[index].id === id) {
  25893. return this.materials[index];
  25894. }
  25895. }
  25896. return null;
  25897. };
  25898. /**
  25899. * Gets a material using its name
  25900. * @param name defines the material's name
  25901. * @return the material or null if none found.
  25902. */
  25903. Scene.prototype.getMaterialByName = function (name) {
  25904. for (var index = 0; index < this.materials.length; index++) {
  25905. if (this.materials[index].name === name) {
  25906. return this.materials[index];
  25907. }
  25908. }
  25909. return null;
  25910. };
  25911. /**
  25912. * Gets a lens flare system using its name
  25913. * @param name defines the name to look for
  25914. * @returns the lens flare system or null if not found
  25915. */
  25916. Scene.prototype.getLensFlareSystemByName = function (name) {
  25917. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  25918. if (this.lensFlareSystems[index].name === name) {
  25919. return this.lensFlareSystems[index];
  25920. }
  25921. }
  25922. return null;
  25923. };
  25924. /**
  25925. * Gets a lens flare system using its id
  25926. * @param id defines the id to look for
  25927. * @returns the lens flare system or null if not found
  25928. */
  25929. Scene.prototype.getLensFlareSystemByID = function (id) {
  25930. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  25931. if (this.lensFlareSystems[index].id === id) {
  25932. return this.lensFlareSystems[index];
  25933. }
  25934. }
  25935. return null;
  25936. };
  25937. /**
  25938. * Gets a camera using its id
  25939. * @param id defines the id to look for
  25940. * @returns the camera or null if not found
  25941. */
  25942. Scene.prototype.getCameraByID = function (id) {
  25943. for (var index = 0; index < this.cameras.length; index++) {
  25944. if (this.cameras[index].id === id) {
  25945. return this.cameras[index];
  25946. }
  25947. }
  25948. return null;
  25949. };
  25950. /**
  25951. * Gets a camera using its unique id
  25952. * @param uniqueId defines the unique id to look for
  25953. * @returns the camera or null if not found
  25954. */
  25955. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  25956. for (var index = 0; index < this.cameras.length; index++) {
  25957. if (this.cameras[index].uniqueId === uniqueId) {
  25958. return this.cameras[index];
  25959. }
  25960. }
  25961. return null;
  25962. };
  25963. /**
  25964. * Gets a camera using its name
  25965. * @param name defines the camera's name
  25966. * @return the camera or null if none found.
  25967. */
  25968. Scene.prototype.getCameraByName = function (name) {
  25969. for (var index = 0; index < this.cameras.length; index++) {
  25970. if (this.cameras[index].name === name) {
  25971. return this.cameras[index];
  25972. }
  25973. }
  25974. return null;
  25975. };
  25976. /**
  25977. * Gets a bone using its id
  25978. * @param id defines the bone's id
  25979. * @return the bone or null if not found
  25980. */
  25981. Scene.prototype.getBoneByID = function (id) {
  25982. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  25983. var skeleton = this.skeletons[skeletonIndex];
  25984. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  25985. if (skeleton.bones[boneIndex].id === id) {
  25986. return skeleton.bones[boneIndex];
  25987. }
  25988. }
  25989. }
  25990. return null;
  25991. };
  25992. /**
  25993. * Gets a bone using its id
  25994. * @param name defines the bone's name
  25995. * @return the bone or null if not found
  25996. */
  25997. Scene.prototype.getBoneByName = function (name) {
  25998. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  25999. var skeleton = this.skeletons[skeletonIndex];
  26000. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26001. if (skeleton.bones[boneIndex].name === name) {
  26002. return skeleton.bones[boneIndex];
  26003. }
  26004. }
  26005. }
  26006. return null;
  26007. };
  26008. /**
  26009. * Gets a light node using its name
  26010. * @param name defines the the light's name
  26011. * @return the light or null if none found.
  26012. */
  26013. Scene.prototype.getLightByName = function (name) {
  26014. for (var index = 0; index < this.lights.length; index++) {
  26015. if (this.lights[index].name === name) {
  26016. return this.lights[index];
  26017. }
  26018. }
  26019. return null;
  26020. };
  26021. /**
  26022. * Gets a light node using its id
  26023. * @param id defines the light's id
  26024. * @return the light or null if none found.
  26025. */
  26026. Scene.prototype.getLightByID = function (id) {
  26027. for (var index = 0; index < this.lights.length; index++) {
  26028. if (this.lights[index].id === id) {
  26029. return this.lights[index];
  26030. }
  26031. }
  26032. return null;
  26033. };
  26034. /**
  26035. * Gets a light node using its scene-generated unique ID
  26036. * @param uniqueId defines the light's unique id
  26037. * @return the light or null if none found.
  26038. */
  26039. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26040. for (var index = 0; index < this.lights.length; index++) {
  26041. if (this.lights[index].uniqueId === uniqueId) {
  26042. return this.lights[index];
  26043. }
  26044. }
  26045. return null;
  26046. };
  26047. /**
  26048. * Gets a particle system by id
  26049. * @param id defines the particle system id
  26050. * @return the corresponding system or null if none found
  26051. */
  26052. Scene.prototype.getParticleSystemByID = function (id) {
  26053. for (var index = 0; index < this.particleSystems.length; index++) {
  26054. if (this.particleSystems[index].id === id) {
  26055. return this.particleSystems[index];
  26056. }
  26057. }
  26058. return null;
  26059. };
  26060. /**
  26061. * Gets a geometry using its ID
  26062. * @param id defines the geometry's id
  26063. * @return the geometry or null if none found.
  26064. */
  26065. Scene.prototype.getGeometryByID = function (id) {
  26066. for (var index = 0; index < this._geometries.length; index++) {
  26067. if (this._geometries[index].id === id) {
  26068. return this._geometries[index];
  26069. }
  26070. }
  26071. return null;
  26072. };
  26073. /**
  26074. * Add a new geometry to this scene
  26075. * @param geometry defines the geometry to be added to the scene.
  26076. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26077. * @return a boolean defining if the geometry was added or not
  26078. */
  26079. Scene.prototype.pushGeometry = function (geometry, force) {
  26080. if (!force && this.getGeometryByID(geometry.id)) {
  26081. return false;
  26082. }
  26083. this._geometries.push(geometry);
  26084. //notify the collision coordinator
  26085. if (this.collisionCoordinator) {
  26086. this.collisionCoordinator.onGeometryAdded(geometry);
  26087. }
  26088. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26089. return true;
  26090. };
  26091. /**
  26092. * Removes an existing geometry
  26093. * @param geometry defines the geometry to be removed from the scene
  26094. * @return a boolean defining if the geometry was removed or not
  26095. */
  26096. Scene.prototype.removeGeometry = function (geometry) {
  26097. var index = this._geometries.indexOf(geometry);
  26098. if (index > -1) {
  26099. this._geometries.splice(index, 1);
  26100. //notify the collision coordinator
  26101. if (this.collisionCoordinator) {
  26102. this.collisionCoordinator.onGeometryDeleted(geometry);
  26103. }
  26104. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26105. return true;
  26106. }
  26107. return false;
  26108. };
  26109. /**
  26110. * Gets the list of geometries attached to the scene
  26111. * @returns an array of Geometry
  26112. */
  26113. Scene.prototype.getGeometries = function () {
  26114. return this._geometries;
  26115. };
  26116. /**
  26117. * Gets the first added mesh found of a given ID
  26118. * @param id defines the id to search for
  26119. * @return the mesh found or null if not found at all
  26120. */
  26121. Scene.prototype.getMeshByID = function (id) {
  26122. for (var index = 0; index < this.meshes.length; index++) {
  26123. if (this.meshes[index].id === id) {
  26124. return this.meshes[index];
  26125. }
  26126. }
  26127. return null;
  26128. };
  26129. /**
  26130. * Gets a list of meshes using their id
  26131. * @param id defines the id to search for
  26132. * @returns a list of meshes
  26133. */
  26134. Scene.prototype.getMeshesByID = function (id) {
  26135. return this.meshes.filter(function (m) {
  26136. return m.id === id;
  26137. });
  26138. };
  26139. /**
  26140. * Gets the first added transform node found of a given ID
  26141. * @param id defines the id to search for
  26142. * @return the found transform node or null if not found at all.
  26143. */
  26144. Scene.prototype.getTransformNodeByID = function (id) {
  26145. for (var index = 0; index < this.transformNodes.length; index++) {
  26146. if (this.transformNodes[index].id === id) {
  26147. return this.transformNodes[index];
  26148. }
  26149. }
  26150. return null;
  26151. };
  26152. /**
  26153. * Gets a list of transform nodes using their id
  26154. * @param id defines the id to search for
  26155. * @returns a list of transform nodes
  26156. */
  26157. Scene.prototype.getTransformNodesByID = function (id) {
  26158. return this.transformNodes.filter(function (m) {
  26159. return m.id === id;
  26160. });
  26161. };
  26162. /**
  26163. * Gets a mesh with its auto-generated unique id
  26164. * @param uniqueId defines the unique id to search for
  26165. * @return the found mesh or null if not found at all.
  26166. */
  26167. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26168. for (var index = 0; index < this.meshes.length; index++) {
  26169. if (this.meshes[index].uniqueId === uniqueId) {
  26170. return this.meshes[index];
  26171. }
  26172. }
  26173. return null;
  26174. };
  26175. /**
  26176. * Gets a the last added mesh using a given id
  26177. * @param id defines the id to search for
  26178. * @return the found mesh or null if not found at all.
  26179. */
  26180. Scene.prototype.getLastMeshByID = function (id) {
  26181. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26182. if (this.meshes[index].id === id) {
  26183. return this.meshes[index];
  26184. }
  26185. }
  26186. return null;
  26187. };
  26188. /**
  26189. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26190. * @param id defines the id to search for
  26191. * @return the found node or null if not found at all
  26192. */
  26193. Scene.prototype.getLastEntryByID = function (id) {
  26194. var index;
  26195. for (index = this.meshes.length - 1; index >= 0; index--) {
  26196. if (this.meshes[index].id === id) {
  26197. return this.meshes[index];
  26198. }
  26199. }
  26200. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26201. if (this.transformNodes[index].id === id) {
  26202. return this.transformNodes[index];
  26203. }
  26204. }
  26205. for (index = this.cameras.length - 1; index >= 0; index--) {
  26206. if (this.cameras[index].id === id) {
  26207. return this.cameras[index];
  26208. }
  26209. }
  26210. for (index = this.lights.length - 1; index >= 0; index--) {
  26211. if (this.lights[index].id === id) {
  26212. return this.lights[index];
  26213. }
  26214. }
  26215. return null;
  26216. };
  26217. /**
  26218. * Gets a node (Mesh, Camera, Light) using a given id
  26219. * @param id defines the id to search for
  26220. * @return the found node or null if not found at all
  26221. */
  26222. Scene.prototype.getNodeByID = function (id) {
  26223. var mesh = this.getMeshByID(id);
  26224. if (mesh) {
  26225. return mesh;
  26226. }
  26227. var light = this.getLightByID(id);
  26228. if (light) {
  26229. return light;
  26230. }
  26231. var camera = this.getCameraByID(id);
  26232. if (camera) {
  26233. return camera;
  26234. }
  26235. var bone = this.getBoneByID(id);
  26236. return bone;
  26237. };
  26238. /**
  26239. * Gets a node (Mesh, Camera, Light) using a given name
  26240. * @param name defines the name to search for
  26241. * @return the found node or null if not found at all.
  26242. */
  26243. Scene.prototype.getNodeByName = function (name) {
  26244. var mesh = this.getMeshByName(name);
  26245. if (mesh) {
  26246. return mesh;
  26247. }
  26248. var light = this.getLightByName(name);
  26249. if (light) {
  26250. return light;
  26251. }
  26252. var camera = this.getCameraByName(name);
  26253. if (camera) {
  26254. return camera;
  26255. }
  26256. var bone = this.getBoneByName(name);
  26257. return bone;
  26258. };
  26259. /**
  26260. * Gets a mesh using a given name
  26261. * @param name defines the name to search for
  26262. * @return the found mesh or null if not found at all.
  26263. */
  26264. Scene.prototype.getMeshByName = function (name) {
  26265. for (var index = 0; index < this.meshes.length; index++) {
  26266. if (this.meshes[index].name === name) {
  26267. return this.meshes[index];
  26268. }
  26269. }
  26270. return null;
  26271. };
  26272. /**
  26273. * Gets a transform node using a given name
  26274. * @param name defines the name to search for
  26275. * @return the found transform node or null if not found at all.
  26276. */
  26277. Scene.prototype.getTransformNodeByName = function (name) {
  26278. for (var index = 0; index < this.transformNodes.length; index++) {
  26279. if (this.transformNodes[index].name === name) {
  26280. return this.transformNodes[index];
  26281. }
  26282. }
  26283. return null;
  26284. };
  26285. /**
  26286. * Gets a sound using a given name
  26287. * @param name defines the name to search for
  26288. * @return the found sound or null if not found at all.
  26289. */
  26290. Scene.prototype.getSoundByName = function (name) {
  26291. var index;
  26292. if (BABYLON.AudioEngine) {
  26293. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26294. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26295. return this.mainSoundTrack.soundCollection[index];
  26296. }
  26297. }
  26298. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26299. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26300. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26301. return this.soundTracks[sdIndex].soundCollection[index];
  26302. }
  26303. }
  26304. }
  26305. }
  26306. return null;
  26307. };
  26308. /**
  26309. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26310. * @param id defines the id to search for
  26311. * @return the found skeleton or null if not found at all.
  26312. */
  26313. Scene.prototype.getLastSkeletonByID = function (id) {
  26314. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26315. if (this.skeletons[index].id === id) {
  26316. return this.skeletons[index];
  26317. }
  26318. }
  26319. return null;
  26320. };
  26321. /**
  26322. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26323. * @param id defines the id to search for
  26324. * @return the found skeleton or null if not found at all.
  26325. */
  26326. Scene.prototype.getSkeletonById = function (id) {
  26327. for (var index = 0; index < this.skeletons.length; index++) {
  26328. if (this.skeletons[index].id === id) {
  26329. return this.skeletons[index];
  26330. }
  26331. }
  26332. return null;
  26333. };
  26334. /**
  26335. * Gets a skeleton using a given name
  26336. * @param name defines the name to search for
  26337. * @return the found skeleton or null if not found at all.
  26338. */
  26339. Scene.prototype.getSkeletonByName = function (name) {
  26340. for (var index = 0; index < this.skeletons.length; index++) {
  26341. if (this.skeletons[index].name === name) {
  26342. return this.skeletons[index];
  26343. }
  26344. }
  26345. return null;
  26346. };
  26347. /**
  26348. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26349. * @param id defines the id to search for
  26350. * @return the found morph target manager or null if not found at all.
  26351. */
  26352. Scene.prototype.getMorphTargetManagerById = function (id) {
  26353. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26354. if (this.morphTargetManagers[index].uniqueId === id) {
  26355. return this.morphTargetManagers[index];
  26356. }
  26357. }
  26358. return null;
  26359. };
  26360. /**
  26361. * Gets a boolean indicating if the given mesh is active
  26362. * @param mesh defines the mesh to look for
  26363. * @returns true if the mesh is in the active list
  26364. */
  26365. Scene.prototype.isActiveMesh = function (mesh) {
  26366. return (this._activeMeshes.indexOf(mesh) !== -1);
  26367. };
  26368. /**
  26369. * Return a the first highlight layer of the scene with a given name.
  26370. * @param name The name of the highlight layer to look for.
  26371. * @return The highlight layer if found otherwise null.
  26372. */
  26373. Scene.prototype.getHighlightLayerByName = function (name) {
  26374. for (var index = 0; index < this.effectLayers.length; index++) {
  26375. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26376. return this.effectLayers[index];
  26377. }
  26378. }
  26379. return null;
  26380. };
  26381. /**
  26382. * Return a the first highlight layer of the scene with a given name.
  26383. * @param name The name of the highlight layer to look for.
  26384. * @return The highlight layer if found otherwise null.
  26385. */
  26386. Scene.prototype.getGlowLayerByName = function (name) {
  26387. for (var index = 0; index < this.effectLayers.length; index++) {
  26388. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26389. return this.effectLayers[index];
  26390. }
  26391. }
  26392. return null;
  26393. };
  26394. Object.defineProperty(Scene.prototype, "uid", {
  26395. /**
  26396. * Return a unique id as a string which can serve as an identifier for the scene
  26397. */
  26398. get: function () {
  26399. if (!this._uid) {
  26400. this._uid = BABYLON.Tools.RandomId();
  26401. }
  26402. return this._uid;
  26403. },
  26404. enumerable: true,
  26405. configurable: true
  26406. });
  26407. /**
  26408. * Add an externaly attached data from its key.
  26409. * This method call will fail and return false, if such key already exists.
  26410. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26411. * @param key the unique key that identifies the data
  26412. * @param data the data object to associate to the key for this Engine instance
  26413. * @return true if no such key were already present and the data was added successfully, false otherwise
  26414. */
  26415. Scene.prototype.addExternalData = function (key, data) {
  26416. if (!this._externalData) {
  26417. this._externalData = new BABYLON.StringDictionary();
  26418. }
  26419. return this._externalData.add(key, data);
  26420. };
  26421. /**
  26422. * Get an externaly attached data from its key
  26423. * @param key the unique key that identifies the data
  26424. * @return the associated data, if present (can be null), or undefined if not present
  26425. */
  26426. Scene.prototype.getExternalData = function (key) {
  26427. if (!this._externalData) {
  26428. return null;
  26429. }
  26430. return this._externalData.get(key);
  26431. };
  26432. /**
  26433. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26434. * @param key the unique key that identifies the data
  26435. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26436. * @return the associated data, can be null if the factory returned null.
  26437. */
  26438. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26439. if (!this._externalData) {
  26440. this._externalData = new BABYLON.StringDictionary();
  26441. }
  26442. return this._externalData.getOrAddWithFactory(key, factory);
  26443. };
  26444. /**
  26445. * Remove an externaly attached data from the Engine instance
  26446. * @param key the unique key that identifies the data
  26447. * @return true if the data was successfully removed, false if it doesn't exist
  26448. */
  26449. Scene.prototype.removeExternalData = function (key) {
  26450. return this._externalData.remove(key);
  26451. };
  26452. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26453. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26454. if (mesh.showSubMeshesBoundingBox) {
  26455. var boundingInfo = subMesh.getBoundingInfo();
  26456. if (boundingInfo !== null && boundingInfo !== undefined) {
  26457. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26458. }
  26459. }
  26460. var material = subMesh.getMaterial();
  26461. if (material !== null && material !== undefined) {
  26462. // Render targets
  26463. if (material.getRenderTargetTextures !== undefined) {
  26464. if (this._processedMaterials.indexOf(material) === -1) {
  26465. this._processedMaterials.push(material);
  26466. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26467. }
  26468. }
  26469. // Dispatch
  26470. this._activeIndices.addCount(subMesh.indexCount, false);
  26471. this._renderingManager.dispatch(subMesh, mesh, material);
  26472. }
  26473. }
  26474. };
  26475. /**
  26476. * Clear the processed materials smart array preventing retention point in material dispose.
  26477. */
  26478. Scene.prototype.freeProcessedMaterials = function () {
  26479. this._processedMaterials.dispose();
  26480. };
  26481. /**
  26482. * Clear the active meshes smart array preventing retention point in mesh dispose.
  26483. */
  26484. Scene.prototype.freeActiveMeshes = function () {
  26485. this._activeMeshes.dispose();
  26486. if (this.activeCamera && this.activeCamera._activeMeshes) {
  26487. this.activeCamera._activeMeshes.dispose();
  26488. }
  26489. if (this.activeCameras) {
  26490. for (var i = 0; i < this.activeCameras.length; i++) {
  26491. var activeCamera = this.activeCameras[i];
  26492. if (activeCamera && activeCamera._activeMeshes) {
  26493. activeCamera._activeMeshes.dispose();
  26494. }
  26495. }
  26496. }
  26497. };
  26498. /**
  26499. * Clear the info related to rendering groups preventing retention points during dispose.
  26500. */
  26501. Scene.prototype.freeRenderingGroups = function () {
  26502. if (this._renderingManager) {
  26503. this._renderingManager.freeRenderingGroups();
  26504. }
  26505. if (this.textures) {
  26506. for (var i = 0; i < this.textures.length; i++) {
  26507. var texture = this.textures[i];
  26508. if (texture && texture.renderList) {
  26509. texture.freeRenderingGroups();
  26510. }
  26511. }
  26512. }
  26513. };
  26514. /** @ignore */
  26515. Scene.prototype._isInIntermediateRendering = function () {
  26516. return this._intermediateRendering;
  26517. };
  26518. /**
  26519. * Defines the current active mesh candidate provider
  26520. * @param provider defines the provider to use
  26521. */
  26522. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  26523. this._activeMeshCandidateProvider = provider;
  26524. };
  26525. /**
  26526. * Gets the current active mesh candidate provider
  26527. * @returns the current active mesh candidate provider
  26528. */
  26529. Scene.prototype.getActiveMeshCandidateProvider = function () {
  26530. return this._activeMeshCandidateProvider;
  26531. };
  26532. /**
  26533. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  26534. * @returns the current scene
  26535. */
  26536. Scene.prototype.freezeActiveMeshes = function () {
  26537. if (!this.activeCamera) {
  26538. return this;
  26539. }
  26540. if (!this._frustumPlanes) {
  26541. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26542. }
  26543. this._evaluateActiveMeshes();
  26544. this._activeMeshesFrozen = true;
  26545. return this;
  26546. };
  26547. /**
  26548. * Use this function to restart evaluating active meshes on every frame
  26549. * @returns the current scene
  26550. */
  26551. Scene.prototype.unfreezeActiveMeshes = function () {
  26552. this._activeMeshesFrozen = false;
  26553. return this;
  26554. };
  26555. Scene.prototype._evaluateActiveMeshes = function () {
  26556. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  26557. return;
  26558. }
  26559. if (!this.activeCamera) {
  26560. return;
  26561. }
  26562. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  26563. this.activeCamera._activeMeshes.reset();
  26564. this._activeMeshes.reset();
  26565. this._renderingManager.reset();
  26566. this._processedMaterials.reset();
  26567. this._activeParticleSystems.reset();
  26568. this._activeSkeletons.reset();
  26569. this._softwareSkinnedMeshes.reset();
  26570. if (this._boundingBoxRenderer) {
  26571. this._boundingBoxRenderer.reset();
  26572. }
  26573. // Meshes
  26574. var meshes;
  26575. var len;
  26576. var checkIsEnabled = true;
  26577. // Determine mesh candidates
  26578. if (this._activeMeshCandidateProvider !== undefined) {
  26579. // Use _activeMeshCandidateProvider
  26580. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  26581. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  26582. if (meshes !== undefined) {
  26583. len = meshes.length;
  26584. }
  26585. else {
  26586. len = 0;
  26587. }
  26588. }
  26589. else if (this._selectionOctree !== undefined) {
  26590. // Octree
  26591. var selection = this._selectionOctree.select(this._frustumPlanes);
  26592. meshes = selection.data;
  26593. len = selection.length;
  26594. }
  26595. else {
  26596. // Full scene traversal
  26597. len = this.meshes.length;
  26598. meshes = this.meshes;
  26599. }
  26600. // Check each mesh
  26601. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  26602. mesh = meshes[meshIndex];
  26603. if (mesh.isBlocked) {
  26604. continue;
  26605. }
  26606. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  26607. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  26608. continue;
  26609. }
  26610. mesh.computeWorldMatrix();
  26611. // Intersections
  26612. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  26613. this._meshesForIntersections.pushNoDuplicate(mesh);
  26614. }
  26615. // Switch to current LOD
  26616. meshLOD = mesh.getLOD(this.activeCamera);
  26617. if (meshLOD === undefined || meshLOD === null) {
  26618. continue;
  26619. }
  26620. mesh._preActivate();
  26621. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  26622. this._activeMeshes.push(mesh);
  26623. this.activeCamera._activeMeshes.push(mesh);
  26624. mesh._activate(this._renderId);
  26625. if (meshLOD !== mesh) {
  26626. meshLOD._activate(this._renderId);
  26627. }
  26628. this._activeMesh(mesh, meshLOD);
  26629. }
  26630. }
  26631. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  26632. // Particle systems
  26633. if (this.particlesEnabled) {
  26634. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  26635. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  26636. var particleSystem = this.particleSystems[particleIndex];
  26637. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  26638. continue;
  26639. }
  26640. var emitter = particleSystem.emitter;
  26641. if (!emitter.position || emitter.isEnabled()) {
  26642. this._activeParticleSystems.push(particleSystem);
  26643. particleSystem.animate();
  26644. this._renderingManager.dispatchParticles(particleSystem);
  26645. }
  26646. }
  26647. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  26648. }
  26649. };
  26650. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  26651. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  26652. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  26653. mesh.skeleton.prepare();
  26654. }
  26655. if (!mesh.computeBonesUsingShaders) {
  26656. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  26657. }
  26658. }
  26659. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  26660. var boundingInfo = sourceMesh.getBoundingInfo();
  26661. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26662. }
  26663. if (mesh !== undefined && mesh !== null
  26664. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  26665. // Submeshes Octrees
  26666. var len;
  26667. var subMeshes;
  26668. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  26669. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  26670. len = intersections.length;
  26671. subMeshes = intersections.data;
  26672. }
  26673. else {
  26674. subMeshes = mesh.subMeshes;
  26675. len = subMeshes.length;
  26676. }
  26677. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  26678. subMesh = subMeshes[subIndex];
  26679. this._evaluateSubMesh(subMesh, mesh);
  26680. }
  26681. }
  26682. };
  26683. /**
  26684. * Update the transform matrix to update from the current active camera
  26685. * @param force defines a boolean used to force the update even if cache is up to date
  26686. */
  26687. Scene.prototype.updateTransformMatrix = function (force) {
  26688. if (!this.activeCamera) {
  26689. return;
  26690. }
  26691. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  26692. };
  26693. /**
  26694. * 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)
  26695. * @param alternateCamera defines the camera to use
  26696. */
  26697. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  26698. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  26699. };
  26700. Scene.prototype._renderForCamera = function (camera, rigParent) {
  26701. if (camera && camera._skipRendering) {
  26702. return;
  26703. }
  26704. var engine = this._engine;
  26705. this.activeCamera = camera;
  26706. if (!this.activeCamera)
  26707. throw new Error("Active camera not set");
  26708. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  26709. // Viewport
  26710. engine.setViewport(this.activeCamera.viewport);
  26711. // Camera
  26712. this.resetCachedMaterial();
  26713. this._renderId++;
  26714. this.updateTransformMatrix();
  26715. if (camera._alternateCamera) {
  26716. this.updateAlternateTransformMatrix(camera._alternateCamera);
  26717. this._alternateRendering = true;
  26718. }
  26719. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  26720. // Meshes
  26721. this._evaluateActiveMeshes();
  26722. // Software skinning
  26723. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  26724. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  26725. mesh.applySkeleton(mesh.skeleton);
  26726. }
  26727. // Render targets
  26728. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  26729. var needsRestoreFrameBuffer = false;
  26730. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  26731. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  26732. }
  26733. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  26734. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  26735. }
  26736. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  26737. this._intermediateRendering = true;
  26738. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26739. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  26740. var renderTarget = this._renderTargets.data[renderIndex];
  26741. if (renderTarget._shouldRender()) {
  26742. this._renderId++;
  26743. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  26744. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  26745. }
  26746. }
  26747. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26748. this._intermediateRendering = false;
  26749. this._renderId++;
  26750. needsRestoreFrameBuffer = true; // Restore back buffer
  26751. }
  26752. // Render EffecttLayer Texture
  26753. var stencilState = this._engine.getStencilBuffer();
  26754. var renderEffects = false;
  26755. var needStencil = false;
  26756. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  26757. this._intermediateRendering = true;
  26758. for (var i = 0; i < this.effectLayers.length; i++) {
  26759. var effectLayer = this.effectLayers[i];
  26760. if (effectLayer.shouldRender() &&
  26761. (!effectLayer.camera ||
  26762. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  26763. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  26764. renderEffects = true;
  26765. needStencil = needStencil || effectLayer.needStencil();
  26766. var renderTarget = effectLayer._mainTexture;
  26767. if (renderTarget._shouldRender()) {
  26768. this._renderId++;
  26769. renderTarget.render(false, false);
  26770. needsRestoreFrameBuffer = true;
  26771. }
  26772. }
  26773. }
  26774. this._intermediateRendering = false;
  26775. this._renderId++;
  26776. }
  26777. if (needsRestoreFrameBuffer) {
  26778. engine.restoreDefaultFramebuffer(); // Restore back buffer
  26779. }
  26780. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  26781. // Prepare Frame
  26782. this.postProcessManager._prepareFrame();
  26783. // Backgrounds
  26784. var layerIndex;
  26785. var layer;
  26786. if (this.layers.length) {
  26787. engine.setDepthBuffer(false);
  26788. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  26789. layer = this.layers[layerIndex];
  26790. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  26791. layer.render();
  26792. }
  26793. }
  26794. engine.setDepthBuffer(true);
  26795. }
  26796. // Activate effect Layer stencil
  26797. if (needStencil) {
  26798. this._engine.setStencilBuffer(true);
  26799. }
  26800. // Render
  26801. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  26802. this._renderingManager.render(null, null, true, true);
  26803. this.onAfterDrawPhaseObservable.notifyObservers(this);
  26804. // Restore effect Layer stencil
  26805. if (needStencil) {
  26806. this._engine.setStencilBuffer(stencilState);
  26807. }
  26808. // Bounding boxes
  26809. if (this._boundingBoxRenderer) {
  26810. this._boundingBoxRenderer.render();
  26811. }
  26812. // Lens flares
  26813. if (this.lensFlaresEnabled) {
  26814. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  26815. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  26816. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  26817. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  26818. lensFlareSystem.render();
  26819. }
  26820. }
  26821. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  26822. }
  26823. // Effect Layer
  26824. if (renderEffects) {
  26825. engine.setDepthBuffer(false);
  26826. for (var i = 0; i < this.effectLayers.length; i++) {
  26827. if (this.effectLayers[i].shouldRender()) {
  26828. this.effectLayers[i].render();
  26829. }
  26830. }
  26831. engine.setDepthBuffer(true);
  26832. }
  26833. // Foregrounds
  26834. if (this.layers.length) {
  26835. engine.setDepthBuffer(false);
  26836. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  26837. layer = this.layers[layerIndex];
  26838. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  26839. layer.render();
  26840. }
  26841. }
  26842. engine.setDepthBuffer(true);
  26843. }
  26844. // Finalize frame
  26845. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  26846. // Reset some special arrays
  26847. this._renderTargets.reset();
  26848. this._alternateRendering = false;
  26849. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  26850. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  26851. };
  26852. Scene.prototype._processSubCameras = function (camera) {
  26853. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  26854. this._renderForCamera(camera);
  26855. return;
  26856. }
  26857. // rig cameras
  26858. for (var index = 0; index < camera._rigCameras.length; index++) {
  26859. this._renderForCamera(camera._rigCameras[index], camera);
  26860. }
  26861. this.activeCamera = camera;
  26862. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26863. };
  26864. Scene.prototype._checkIntersections = function () {
  26865. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  26866. var sourceMesh = this._meshesForIntersections.data[index];
  26867. if (!sourceMesh.actionManager) {
  26868. continue;
  26869. }
  26870. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  26871. var action = sourceMesh.actionManager.actions[actionIndex];
  26872. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26873. var parameters = action.getTriggerParameter();
  26874. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  26875. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  26876. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  26877. if (areIntersecting && currentIntersectionInProgress === -1) {
  26878. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  26879. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  26880. sourceMesh._intersectionsInProgress.push(otherMesh);
  26881. }
  26882. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26883. sourceMesh._intersectionsInProgress.push(otherMesh);
  26884. }
  26885. }
  26886. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  26887. //They intersected, and now they don't.
  26888. //is this trigger an exit trigger? execute an event.
  26889. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26890. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  26891. }
  26892. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  26893. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  26894. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  26895. return otherMesh === parameterMesh;
  26896. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26897. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  26898. }
  26899. }
  26900. }
  26901. }
  26902. }
  26903. };
  26904. /**
  26905. * Render the scene
  26906. */
  26907. Scene.prototype.render = function () {
  26908. if (this.isDisposed) {
  26909. return;
  26910. }
  26911. this._activeParticles.fetchNewFrame();
  26912. this._totalVertices.fetchNewFrame();
  26913. this._activeIndices.fetchNewFrame();
  26914. this._activeBones.fetchNewFrame();
  26915. this._meshesForIntersections.reset();
  26916. this.resetCachedMaterial();
  26917. this.onBeforeAnimationsObservable.notifyObservers(this);
  26918. // Actions
  26919. if (this.actionManager) {
  26920. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  26921. }
  26922. //Simplification Queue
  26923. if (this.simplificationQueue && !this.simplificationQueue.running) {
  26924. this.simplificationQueue.executeNext();
  26925. }
  26926. if (this._engine.isDeterministicLockStep()) {
  26927. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  26928. var defaultFPS = (60.0 / 1000.0);
  26929. var defaultFrameTime = 1000 / 60; // frame time in MS
  26930. if (this._physicsEngine) {
  26931. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  26932. }
  26933. var stepsTaken = 0;
  26934. var maxSubSteps = this._engine.getLockstepMaxSteps();
  26935. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  26936. internalSteps = Math.min(internalSteps, maxSubSteps);
  26937. do {
  26938. this.onBeforeStepObservable.notifyObservers(this);
  26939. // Animations
  26940. this._animationRatio = defaultFrameTime * defaultFPS;
  26941. this._animate();
  26942. this.onAfterAnimationsObservable.notifyObservers(this);
  26943. // Physics
  26944. if (this._physicsEngine) {
  26945. this.onBeforePhysicsObservable.notifyObservers(this);
  26946. this._physicsEngine._step(defaultFrameTime / 1000);
  26947. this.onAfterPhysicsObservable.notifyObservers(this);
  26948. }
  26949. this.onAfterStepObservable.notifyObservers(this);
  26950. this._currentStepId++;
  26951. stepsTaken++;
  26952. deltaTime -= defaultFrameTime;
  26953. } while (deltaTime > 0 && stepsTaken < internalSteps);
  26954. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  26955. }
  26956. else {
  26957. // Animations
  26958. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  26959. this._animationRatio = deltaTime * (60.0 / 1000.0);
  26960. this._animate();
  26961. this.onAfterAnimationsObservable.notifyObservers(this);
  26962. // Physics
  26963. if (this._physicsEngine) {
  26964. this.onBeforePhysicsObservable.notifyObservers(this);
  26965. this._physicsEngine._step(deltaTime / 1000.0);
  26966. this.onAfterPhysicsObservable.notifyObservers(this);
  26967. }
  26968. }
  26969. // update gamepad manager
  26970. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  26971. this._gamepadManager._checkGamepadsStatus();
  26972. }
  26973. // Update Cameras
  26974. if (this.activeCameras.length > 0) {
  26975. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  26976. var camera = this.activeCameras[cameraIndex];
  26977. camera.update();
  26978. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  26979. // rig cameras
  26980. for (var index = 0; index < camera._rigCameras.length; index++) {
  26981. camera._rigCameras[index].update();
  26982. }
  26983. }
  26984. }
  26985. }
  26986. else if (this.activeCamera) {
  26987. this.activeCamera.update();
  26988. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  26989. // rig cameras
  26990. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  26991. this.activeCamera._rigCameras[index].update();
  26992. }
  26993. }
  26994. }
  26995. // Before render
  26996. this.onBeforeRenderObservable.notifyObservers(this);
  26997. // Customs render targets
  26998. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  26999. var engine = this.getEngine();
  27000. var currentActiveCamera = this.activeCamera;
  27001. if (this.renderTargetsEnabled) {
  27002. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27003. this._intermediateRendering = true;
  27004. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27005. var renderTarget = this.customRenderTargets[customIndex];
  27006. if (renderTarget._shouldRender()) {
  27007. this._renderId++;
  27008. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27009. if (!this.activeCamera)
  27010. throw new Error("Active camera not set");
  27011. // Viewport
  27012. engine.setViewport(this.activeCamera.viewport);
  27013. // Camera
  27014. this.updateTransformMatrix();
  27015. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27016. }
  27017. }
  27018. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27019. this._intermediateRendering = false;
  27020. this._renderId++;
  27021. }
  27022. // Restore back buffer
  27023. if (this.customRenderTargets.length > 0) {
  27024. engine.restoreDefaultFramebuffer();
  27025. }
  27026. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27027. this.activeCamera = currentActiveCamera;
  27028. // Procedural textures
  27029. if (this.proceduralTexturesEnabled) {
  27030. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27031. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27032. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27033. if (proceduralTexture._shouldRender()) {
  27034. proceduralTexture.render();
  27035. }
  27036. }
  27037. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27038. }
  27039. // Clear
  27040. if (this.autoClearDepthAndStencil || this.autoClear) {
  27041. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27042. }
  27043. // Shadows
  27044. if (this.shadowsEnabled) {
  27045. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27046. var light = this.lights[lightIndex];
  27047. var shadowGenerator = light.getShadowGenerator();
  27048. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27049. var shadowMap = (shadowGenerator.getShadowMap());
  27050. if (this.textures.indexOf(shadowMap) !== -1) {
  27051. this._renderTargets.push(shadowMap);
  27052. }
  27053. }
  27054. }
  27055. }
  27056. // Depth renderer
  27057. for (var key in this._depthRenderer) {
  27058. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27059. }
  27060. // Geometry renderer
  27061. if (this._geometryBufferRenderer) {
  27062. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27063. }
  27064. // RenderPipeline
  27065. if (this._postProcessRenderPipelineManager) {
  27066. this._postProcessRenderPipelineManager.update();
  27067. }
  27068. // Multi-cameras?
  27069. if (this.activeCameras.length > 0) {
  27070. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27071. if (cameraIndex > 0) {
  27072. this._engine.clear(null, false, true, true);
  27073. }
  27074. this._processSubCameras(this.activeCameras[cameraIndex]);
  27075. }
  27076. }
  27077. else {
  27078. if (!this.activeCamera) {
  27079. throw new Error("No camera defined");
  27080. }
  27081. this._processSubCameras(this.activeCamera);
  27082. }
  27083. // Intersection checks
  27084. this._checkIntersections();
  27085. // Update the audio listener attached to the camera
  27086. if (BABYLON.AudioEngine) {
  27087. this._updateAudioParameters();
  27088. }
  27089. // After render
  27090. if (this.afterRender) {
  27091. this.afterRender();
  27092. }
  27093. this.onAfterRenderObservable.notifyObservers(this);
  27094. // Cleaning
  27095. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27096. var data = this._toBeDisposed.data[index];
  27097. if (data) {
  27098. data.dispose();
  27099. }
  27100. this._toBeDisposed[index] = null;
  27101. }
  27102. this._toBeDisposed.reset();
  27103. if (this.dumpNextRenderTargets) {
  27104. this.dumpNextRenderTargets = false;
  27105. }
  27106. this._activeBones.addCount(0, true);
  27107. this._activeIndices.addCount(0, true);
  27108. this._activeParticles.addCount(0, true);
  27109. };
  27110. Scene.prototype._updateAudioParameters = function () {
  27111. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27112. return;
  27113. }
  27114. var listeningCamera;
  27115. var audioEngine = BABYLON.Engine.audioEngine;
  27116. if (this.activeCameras.length > 0) {
  27117. listeningCamera = this.activeCameras[0];
  27118. }
  27119. else {
  27120. listeningCamera = this.activeCamera;
  27121. }
  27122. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27123. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27124. // for VR cameras
  27125. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27126. listeningCamera = listeningCamera.rigCameras[0];
  27127. }
  27128. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27129. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27130. cameraDirection.normalize();
  27131. // To avoid some errors on GearVR
  27132. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27133. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27134. }
  27135. var i;
  27136. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27137. var sound = this.mainSoundTrack.soundCollection[i];
  27138. if (sound.useCustomAttenuation) {
  27139. sound.updateDistanceFromListener();
  27140. }
  27141. }
  27142. for (i = 0; i < this.soundTracks.length; i++) {
  27143. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27144. sound = this.soundTracks[i].soundCollection[j];
  27145. if (sound.useCustomAttenuation) {
  27146. sound.updateDistanceFromListener();
  27147. }
  27148. }
  27149. }
  27150. }
  27151. };
  27152. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27153. // Audio
  27154. /**
  27155. * Gets or sets if audio support is enabled
  27156. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27157. */
  27158. get: function () {
  27159. return this._audioEnabled;
  27160. },
  27161. set: function (value) {
  27162. this._audioEnabled = value;
  27163. if (BABYLON.AudioEngine) {
  27164. if (this._audioEnabled) {
  27165. this._enableAudio();
  27166. }
  27167. else {
  27168. this._disableAudio();
  27169. }
  27170. }
  27171. },
  27172. enumerable: true,
  27173. configurable: true
  27174. });
  27175. Scene.prototype._disableAudio = function () {
  27176. var i;
  27177. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27178. this.mainSoundTrack.soundCollection[i].pause();
  27179. }
  27180. for (i = 0; i < this.soundTracks.length; i++) {
  27181. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27182. this.soundTracks[i].soundCollection[j].pause();
  27183. }
  27184. }
  27185. };
  27186. Scene.prototype._enableAudio = function () {
  27187. var i;
  27188. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27189. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27190. this.mainSoundTrack.soundCollection[i].play();
  27191. }
  27192. }
  27193. for (i = 0; i < this.soundTracks.length; i++) {
  27194. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27195. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27196. this.soundTracks[i].soundCollection[j].play();
  27197. }
  27198. }
  27199. }
  27200. };
  27201. Object.defineProperty(Scene.prototype, "headphone", {
  27202. /**
  27203. * Gets or sets if audio will be output to headphones
  27204. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27205. */
  27206. get: function () {
  27207. return this._headphone;
  27208. },
  27209. set: function (value) {
  27210. this._headphone = value;
  27211. if (BABYLON.AudioEngine) {
  27212. if (this._headphone) {
  27213. this._switchAudioModeForHeadphones();
  27214. }
  27215. else {
  27216. this._switchAudioModeForNormalSpeakers();
  27217. }
  27218. }
  27219. },
  27220. enumerable: true,
  27221. configurable: true
  27222. });
  27223. Scene.prototype._switchAudioModeForHeadphones = function () {
  27224. this.mainSoundTrack.switchPanningModelToHRTF();
  27225. for (var i = 0; i < this.soundTracks.length; i++) {
  27226. this.soundTracks[i].switchPanningModelToHRTF();
  27227. }
  27228. };
  27229. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27230. this.mainSoundTrack.switchPanningModelToEqualPower();
  27231. for (var i = 0; i < this.soundTracks.length; i++) {
  27232. this.soundTracks[i].switchPanningModelToEqualPower();
  27233. }
  27234. };
  27235. /**
  27236. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27237. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27238. * @returns the created depth renderer
  27239. */
  27240. Scene.prototype.enableDepthRenderer = function (camera) {
  27241. camera = camera || this.activeCamera;
  27242. if (!camera) {
  27243. throw "No camera available to enable depth renderer";
  27244. }
  27245. if (!this._depthRenderer[camera.id]) {
  27246. var textureType = 0;
  27247. if (this._engine.getCaps().textureHalfFloatRender) {
  27248. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27249. }
  27250. else if (this._engine.getCaps().textureFloatRender) {
  27251. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27252. }
  27253. else {
  27254. throw "Depth renderer does not support int texture type";
  27255. }
  27256. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27257. }
  27258. return this._depthRenderer[camera.id];
  27259. };
  27260. /**
  27261. * Disables a depth renderer for a given camera
  27262. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27263. */
  27264. Scene.prototype.disableDepthRenderer = function (camera) {
  27265. camera = camera || this.activeCamera;
  27266. if (!camera || !this._depthRenderer[camera.id]) {
  27267. return;
  27268. }
  27269. this._depthRenderer[camera.id].dispose();
  27270. delete this._depthRenderer[camera.id];
  27271. };
  27272. /**
  27273. * Enables a GeometryBufferRender and associates it with the scene
  27274. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27275. * @returns the GeometryBufferRenderer
  27276. */
  27277. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27278. if (ratio === void 0) { ratio = 1; }
  27279. if (this._geometryBufferRenderer) {
  27280. return this._geometryBufferRenderer;
  27281. }
  27282. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27283. if (!this._geometryBufferRenderer.isSupported) {
  27284. this._geometryBufferRenderer = null;
  27285. }
  27286. return this._geometryBufferRenderer;
  27287. };
  27288. /**
  27289. * Disables the GeometryBufferRender associated with the scene
  27290. */
  27291. Scene.prototype.disableGeometryBufferRenderer = function () {
  27292. if (!this._geometryBufferRenderer) {
  27293. return;
  27294. }
  27295. this._geometryBufferRenderer.dispose();
  27296. this._geometryBufferRenderer = null;
  27297. };
  27298. /**
  27299. * Freeze all materials
  27300. * A frozen material will not be updatable but should be faster to render
  27301. */
  27302. Scene.prototype.freezeMaterials = function () {
  27303. for (var i = 0; i < this.materials.length; i++) {
  27304. this.materials[i].freeze();
  27305. }
  27306. };
  27307. /**
  27308. * Unfreeze all materials
  27309. * A frozen material will not be updatable but should be faster to render
  27310. */
  27311. Scene.prototype.unfreezeMaterials = function () {
  27312. for (var i = 0; i < this.materials.length; i++) {
  27313. this.materials[i].unfreeze();
  27314. }
  27315. };
  27316. /**
  27317. * Releases all held ressources
  27318. */
  27319. Scene.prototype.dispose = function () {
  27320. this.beforeRender = null;
  27321. this.afterRender = null;
  27322. this.skeletons = [];
  27323. this.morphTargetManagers = [];
  27324. this.importedMeshesFiles = new Array();
  27325. this.stopAllAnimations();
  27326. this.resetCachedMaterial();
  27327. for (var key in this._depthRenderer) {
  27328. this._depthRenderer[key].dispose();
  27329. }
  27330. if (this._gamepadManager) {
  27331. this._gamepadManager.dispose();
  27332. this._gamepadManager = null;
  27333. }
  27334. // Smart arrays
  27335. if (this.activeCamera) {
  27336. this.activeCamera._activeMeshes.dispose();
  27337. this.activeCamera = null;
  27338. }
  27339. this._activeMeshes.dispose();
  27340. this._renderingManager.dispose();
  27341. this._processedMaterials.dispose();
  27342. this._activeParticleSystems.dispose();
  27343. this._activeSkeletons.dispose();
  27344. this._softwareSkinnedMeshes.dispose();
  27345. this._renderTargets.dispose();
  27346. this._registeredForLateAnimationBindings.dispose();
  27347. if (this._boundingBoxRenderer) {
  27348. this._boundingBoxRenderer.dispose();
  27349. }
  27350. this._meshesForIntersections.dispose();
  27351. this._toBeDisposed.dispose();
  27352. // Abort active requests
  27353. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27354. var request = _a[_i];
  27355. request.abort();
  27356. }
  27357. // Debug layer
  27358. if (this._debugLayer) {
  27359. this._debugLayer.hide();
  27360. }
  27361. // Events
  27362. this.onDisposeObservable.notifyObservers(this);
  27363. this.onDisposeObservable.clear();
  27364. this.onBeforeRenderObservable.clear();
  27365. this.onAfterRenderObservable.clear();
  27366. this.onBeforeRenderTargetsRenderObservable.clear();
  27367. this.onAfterRenderTargetsRenderObservable.clear();
  27368. this.onAfterStepObservable.clear();
  27369. this.onBeforeStepObservable.clear();
  27370. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27371. this.onAfterActiveMeshesEvaluationObservable.clear();
  27372. this.onBeforeParticlesRenderingObservable.clear();
  27373. this.onAfterParticlesRenderingObservable.clear();
  27374. this.onBeforeSpritesRenderingObservable.clear();
  27375. this.onAfterSpritesRenderingObservable.clear();
  27376. this.onBeforeDrawPhaseObservable.clear();
  27377. this.onAfterDrawPhaseObservable.clear();
  27378. this.onBeforePhysicsObservable.clear();
  27379. this.onAfterPhysicsObservable.clear();
  27380. this.onBeforeAnimationsObservable.clear();
  27381. this.onAfterAnimationsObservable.clear();
  27382. this.onDataLoadedObservable.clear();
  27383. this.detachControl();
  27384. // Release sounds & sounds tracks
  27385. if (BABYLON.AudioEngine) {
  27386. this.disposeSounds();
  27387. }
  27388. // VR Helper
  27389. if (this.VRHelper) {
  27390. this.VRHelper.dispose();
  27391. }
  27392. // Detach cameras
  27393. var canvas = this._engine.getRenderingCanvas();
  27394. if (canvas) {
  27395. var index;
  27396. for (index = 0; index < this.cameras.length; index++) {
  27397. this.cameras[index].detachControl(canvas);
  27398. }
  27399. }
  27400. // Release animation groups
  27401. while (this.animationGroups.length) {
  27402. this.animationGroups[0].dispose();
  27403. }
  27404. // Release lights
  27405. while (this.lights.length) {
  27406. this.lights[0].dispose();
  27407. }
  27408. // Release meshes
  27409. while (this.meshes.length) {
  27410. this.meshes[0].dispose(true);
  27411. }
  27412. while (this.transformNodes.length) {
  27413. this.removeTransformNode(this.transformNodes[0]);
  27414. }
  27415. // Release cameras
  27416. while (this.cameras.length) {
  27417. this.cameras[0].dispose();
  27418. }
  27419. // Release materials
  27420. if (this.defaultMaterial) {
  27421. this.defaultMaterial.dispose();
  27422. }
  27423. while (this.multiMaterials.length) {
  27424. this.multiMaterials[0].dispose();
  27425. }
  27426. while (this.materials.length) {
  27427. this.materials[0].dispose();
  27428. }
  27429. // Release particles
  27430. while (this.particleSystems.length) {
  27431. this.particleSystems[0].dispose();
  27432. }
  27433. // Release sprites
  27434. while (this.spriteManagers.length) {
  27435. this.spriteManagers[0].dispose();
  27436. }
  27437. // Release postProcesses
  27438. while (this.postProcesses.length) {
  27439. this.postProcesses[0].dispose();
  27440. }
  27441. // Release layers
  27442. while (this.layers.length) {
  27443. this.layers[0].dispose();
  27444. }
  27445. while (this.effectLayers.length) {
  27446. this.effectLayers[0].dispose();
  27447. }
  27448. // Release textures
  27449. while (this.textures.length) {
  27450. this.textures[0].dispose();
  27451. }
  27452. // Release UBO
  27453. this._sceneUbo.dispose();
  27454. if (this._alternateSceneUbo) {
  27455. this._alternateSceneUbo.dispose();
  27456. }
  27457. // Post-processes
  27458. this.postProcessManager.dispose();
  27459. if (this._postProcessRenderPipelineManager) {
  27460. this._postProcessRenderPipelineManager.dispose();
  27461. }
  27462. // Physics
  27463. if (this._physicsEngine) {
  27464. this.disablePhysicsEngine();
  27465. }
  27466. // Remove from engine
  27467. index = this._engine.scenes.indexOf(this);
  27468. if (index > -1) {
  27469. this._engine.scenes.splice(index, 1);
  27470. }
  27471. this._engine.wipeCaches(true);
  27472. this._isDisposed = true;
  27473. };
  27474. Object.defineProperty(Scene.prototype, "isDisposed", {
  27475. /**
  27476. * Gets if the scene is already disposed
  27477. */
  27478. get: function () {
  27479. return this._isDisposed;
  27480. },
  27481. enumerable: true,
  27482. configurable: true
  27483. });
  27484. /**
  27485. * Releases sounds & soundtracks
  27486. */
  27487. Scene.prototype.disposeSounds = function () {
  27488. if (!this._mainSoundTrack) {
  27489. return;
  27490. }
  27491. this.mainSoundTrack.dispose();
  27492. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27493. this.soundTracks[scIndex].dispose();
  27494. }
  27495. };
  27496. // Octrees
  27497. /**
  27498. * Get the world extend vectors with an optional filter
  27499. *
  27500. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  27501. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  27502. */
  27503. Scene.prototype.getWorldExtends = function (filterPredicate) {
  27504. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  27505. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  27506. filterPredicate = filterPredicate || (function () { return true; });
  27507. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  27508. mesh.computeWorldMatrix(true);
  27509. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  27510. return;
  27511. }
  27512. var boundingInfo = mesh.getBoundingInfo();
  27513. var minBox = boundingInfo.boundingBox.minimumWorld;
  27514. var maxBox = boundingInfo.boundingBox.maximumWorld;
  27515. BABYLON.Tools.CheckExtends(minBox, min, max);
  27516. BABYLON.Tools.CheckExtends(maxBox, min, max);
  27517. });
  27518. return {
  27519. min: min,
  27520. max: max
  27521. };
  27522. };
  27523. /**
  27524. * Creates or updates the octree used to boost selection (picking)
  27525. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  27526. * @param maxCapacity defines the maximum capacity per leaf
  27527. * @param maxDepth defines the maximum depth of the octree
  27528. * @returns an octree of AbstractMesh
  27529. */
  27530. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  27531. if (maxCapacity === void 0) { maxCapacity = 64; }
  27532. if (maxDepth === void 0) { maxDepth = 2; }
  27533. if (!this._selectionOctree) {
  27534. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  27535. }
  27536. var worldExtends = this.getWorldExtends();
  27537. // Update octree
  27538. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  27539. return this._selectionOctree;
  27540. };
  27541. // Picking
  27542. /**
  27543. * Creates a ray that can be used to pick in the scene
  27544. * @param x defines the x coordinate of the origin (on-screen)
  27545. * @param y defines the y coordinate of the origin (on-screen)
  27546. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27547. * @param camera defines the camera to use for the picking
  27548. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27549. * @returns a Ray
  27550. */
  27551. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  27552. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27553. var result = BABYLON.Ray.Zero();
  27554. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  27555. return result;
  27556. };
  27557. /**
  27558. * Creates a ray that can be used to pick in the scene
  27559. * @param x defines the x coordinate of the origin (on-screen)
  27560. * @param y defines the y coordinate of the origin (on-screen)
  27561. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27562. * @param result defines the ray where to store the picking ray
  27563. * @param camera defines the camera to use for the picking
  27564. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27565. * @returns the current scene
  27566. */
  27567. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  27568. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27569. var engine = this._engine;
  27570. if (!camera) {
  27571. if (!this.activeCamera)
  27572. throw new Error("Active camera not set");
  27573. camera = this.activeCamera;
  27574. }
  27575. var cameraViewport = camera.viewport;
  27576. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27577. // Moving coordinates to local viewport world
  27578. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27579. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27580. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  27581. return this;
  27582. };
  27583. /**
  27584. * Creates a ray that can be used to pick in the scene
  27585. * @param x defines the x coordinate of the origin (on-screen)
  27586. * @param y defines the y coordinate of the origin (on-screen)
  27587. * @param camera defines the camera to use for the picking
  27588. * @returns a Ray
  27589. */
  27590. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  27591. var result = BABYLON.Ray.Zero();
  27592. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  27593. return result;
  27594. };
  27595. /**
  27596. * Creates a ray that can be used to pick in the scene
  27597. * @param x defines the x coordinate of the origin (on-screen)
  27598. * @param y defines the y coordinate of the origin (on-screen)
  27599. * @param result defines the ray where to store the picking ray
  27600. * @param camera defines the camera to use for the picking
  27601. * @returns the current scene
  27602. */
  27603. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  27604. if (!BABYLON.PickingInfo) {
  27605. return this;
  27606. }
  27607. var engine = this._engine;
  27608. if (!camera) {
  27609. if (!this.activeCamera)
  27610. throw new Error("Active camera not set");
  27611. camera = this.activeCamera;
  27612. }
  27613. var cameraViewport = camera.viewport;
  27614. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27615. var identity = BABYLON.Matrix.Identity();
  27616. // Moving coordinates to local viewport world
  27617. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27618. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27619. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  27620. return this;
  27621. };
  27622. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  27623. if (!BABYLON.PickingInfo) {
  27624. return null;
  27625. }
  27626. var pickingInfo = null;
  27627. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27628. var mesh = this.meshes[meshIndex];
  27629. if (predicate) {
  27630. if (!predicate(mesh)) {
  27631. continue;
  27632. }
  27633. }
  27634. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27635. continue;
  27636. }
  27637. var world = mesh.getWorldMatrix();
  27638. var ray = rayFunction(world);
  27639. var result = mesh.intersects(ray, fastCheck);
  27640. if (!result || !result.hit)
  27641. continue;
  27642. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27643. continue;
  27644. pickingInfo = result;
  27645. if (fastCheck) {
  27646. break;
  27647. }
  27648. }
  27649. return pickingInfo || new BABYLON.PickingInfo();
  27650. };
  27651. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  27652. if (!BABYLON.PickingInfo) {
  27653. return null;
  27654. }
  27655. var pickingInfos = new Array();
  27656. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27657. var mesh = this.meshes[meshIndex];
  27658. if (predicate) {
  27659. if (!predicate(mesh)) {
  27660. continue;
  27661. }
  27662. }
  27663. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27664. continue;
  27665. }
  27666. var world = mesh.getWorldMatrix();
  27667. var ray = rayFunction(world);
  27668. var result = mesh.intersects(ray, false);
  27669. if (!result || !result.hit)
  27670. continue;
  27671. pickingInfos.push(result);
  27672. }
  27673. return pickingInfos;
  27674. };
  27675. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  27676. if (!BABYLON.PickingInfo) {
  27677. return null;
  27678. }
  27679. var pickingInfo = null;
  27680. if (!camera) {
  27681. if (!this.activeCamera) {
  27682. return null;
  27683. }
  27684. camera = this.activeCamera;
  27685. }
  27686. if (this.spriteManagers.length > 0) {
  27687. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  27688. var spriteManager = this.spriteManagers[spriteIndex];
  27689. if (!spriteManager.isPickable) {
  27690. continue;
  27691. }
  27692. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  27693. if (!result || !result.hit)
  27694. continue;
  27695. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27696. continue;
  27697. pickingInfo = result;
  27698. if (fastCheck) {
  27699. break;
  27700. }
  27701. }
  27702. }
  27703. return pickingInfo || new BABYLON.PickingInfo();
  27704. };
  27705. /** Launch a ray to try to pick a mesh in the scene
  27706. * @param x position on screen
  27707. * @param y position on screen
  27708. * @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
  27709. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27710. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27711. * @returns a PickingInfo
  27712. */
  27713. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  27714. var _this = this;
  27715. if (!BABYLON.PickingInfo) {
  27716. return null;
  27717. }
  27718. return this._internalPick(function (world) {
  27719. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  27720. return _this._tempPickingRay;
  27721. }, predicate, fastCheck);
  27722. };
  27723. /** Launch a ray to try to pick a sprite in the scene
  27724. * @param x position on screen
  27725. * @param y position on screen
  27726. * @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
  27727. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27728. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27729. * @returns a PickingInfo
  27730. */
  27731. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  27732. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  27733. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  27734. };
  27735. /** Use the given ray to pick a mesh in the scene
  27736. * @param ray The ray to use to pick meshes
  27737. * @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
  27738. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  27739. * @returns a PickingInfo
  27740. */
  27741. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  27742. var _this = this;
  27743. return this._internalPick(function (world) {
  27744. if (!_this._pickWithRayInverseMatrix) {
  27745. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27746. }
  27747. world.invertToRef(_this._pickWithRayInverseMatrix);
  27748. if (!_this._cachedRayForTransform) {
  27749. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27750. }
  27751. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27752. return _this._cachedRayForTransform;
  27753. }, predicate, fastCheck);
  27754. };
  27755. /**
  27756. * Launch a ray to try to pick a mesh in the scene
  27757. * @param x X position on screen
  27758. * @param y Y position on screen
  27759. * @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
  27760. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27761. * @returns an array of PickingInfo
  27762. */
  27763. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  27764. var _this = this;
  27765. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  27766. };
  27767. /**
  27768. * Launch a ray to try to pick a mesh in the scene
  27769. * @param ray Ray to use
  27770. * @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
  27771. * @returns an array of PickingInfo
  27772. */
  27773. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  27774. var _this = this;
  27775. return this._internalMultiPick(function (world) {
  27776. if (!_this._pickWithRayInverseMatrix) {
  27777. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27778. }
  27779. world.invertToRef(_this._pickWithRayInverseMatrix);
  27780. if (!_this._cachedRayForTransform) {
  27781. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27782. }
  27783. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27784. return _this._cachedRayForTransform;
  27785. }, predicate);
  27786. };
  27787. /**
  27788. * Force the value of meshUnderPointer
  27789. * @param mesh defines the mesh to use
  27790. */
  27791. Scene.prototype.setPointerOverMesh = function (mesh) {
  27792. if (this._pointerOverMesh === mesh) {
  27793. return;
  27794. }
  27795. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27796. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27797. }
  27798. this._pointerOverMesh = mesh;
  27799. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27800. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27801. }
  27802. };
  27803. /**
  27804. * Gets the mesh under the pointer
  27805. * @returns a Mesh or null if no mesh is under the pointer
  27806. */
  27807. Scene.prototype.getPointerOverMesh = function () {
  27808. return this._pointerOverMesh;
  27809. };
  27810. /**
  27811. * Force the sprite under the pointer
  27812. * @param sprite defines the sprite to use
  27813. */
  27814. Scene.prototype.setPointerOverSprite = function (sprite) {
  27815. if (this._pointerOverSprite === sprite) {
  27816. return;
  27817. }
  27818. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  27819. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  27820. }
  27821. this._pointerOverSprite = sprite;
  27822. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  27823. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  27824. }
  27825. };
  27826. /**
  27827. * Gets the sprite under the pointer
  27828. * @returns a Sprite or null if no sprite is under the pointer
  27829. */
  27830. Scene.prototype.getPointerOverSprite = function () {
  27831. return this._pointerOverSprite;
  27832. };
  27833. // Physics
  27834. /**
  27835. * Gets the current physics engine
  27836. * @returns a PhysicsEngine or null if none attached
  27837. */
  27838. Scene.prototype.getPhysicsEngine = function () {
  27839. return this._physicsEngine;
  27840. };
  27841. /**
  27842. * Enables physics to the current scene
  27843. * @param gravity defines the scene's gravity for the physics engine
  27844. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  27845. * @return a boolean indicating if the physics engine was initialized
  27846. */
  27847. Scene.prototype.enablePhysics = function (gravity, plugin) {
  27848. if (gravity === void 0) { gravity = null; }
  27849. if (this._physicsEngine) {
  27850. return true;
  27851. }
  27852. try {
  27853. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  27854. return true;
  27855. }
  27856. catch (e) {
  27857. BABYLON.Tools.Error(e.message);
  27858. return false;
  27859. }
  27860. };
  27861. /**
  27862. * Disables and disposes the physics engine associated with the scene
  27863. */
  27864. Scene.prototype.disablePhysicsEngine = function () {
  27865. if (!this._physicsEngine) {
  27866. return;
  27867. }
  27868. this._physicsEngine.dispose();
  27869. this._physicsEngine = null;
  27870. };
  27871. /**
  27872. * Gets a boolean indicating if there is an active physics engine
  27873. * @returns a boolean indicating if there is an active physics engine
  27874. */
  27875. Scene.prototype.isPhysicsEnabled = function () {
  27876. return this._physicsEngine !== undefined;
  27877. };
  27878. /**
  27879. * Deletes a physics compound impostor
  27880. * @param compound defines the compound to delete
  27881. */
  27882. Scene.prototype.deleteCompoundImpostor = function (compound) {
  27883. var mesh = compound.parts[0].mesh;
  27884. if (mesh.physicsImpostor) {
  27885. mesh.physicsImpostor.dispose();
  27886. mesh.physicsImpostor = null;
  27887. }
  27888. };
  27889. // Misc.
  27890. /** @ignore */
  27891. Scene.prototype._rebuildGeometries = function () {
  27892. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  27893. var geometry = _a[_i];
  27894. geometry._rebuild();
  27895. }
  27896. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  27897. var mesh = _c[_b];
  27898. mesh._rebuild();
  27899. }
  27900. if (this.postProcessManager) {
  27901. this.postProcessManager._rebuild();
  27902. }
  27903. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  27904. var layer = _e[_d];
  27905. layer._rebuild();
  27906. }
  27907. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  27908. var effectLayer = _g[_f];
  27909. effectLayer._rebuild();
  27910. }
  27911. if (this._boundingBoxRenderer) {
  27912. this._boundingBoxRenderer._rebuild();
  27913. }
  27914. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  27915. var system = _j[_h];
  27916. system.rebuild();
  27917. }
  27918. if (this._postProcessRenderPipelineManager) {
  27919. this._postProcessRenderPipelineManager._rebuild();
  27920. }
  27921. };
  27922. /** @ignore */
  27923. Scene.prototype._rebuildTextures = function () {
  27924. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  27925. var texture = _a[_i];
  27926. texture._rebuild();
  27927. }
  27928. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27929. };
  27930. /**
  27931. * Creates a default light for the scene.
  27932. * @param replace Whether to replace the existing lights in the scene.
  27933. */
  27934. Scene.prototype.createDefaultLight = function (replace) {
  27935. if (replace === void 0) { replace = false; }
  27936. // Dispose existing light in replace mode.
  27937. if (replace) {
  27938. if (this.lights) {
  27939. for (var i = 0; i < this.lights.length; i++) {
  27940. this.lights[i].dispose();
  27941. }
  27942. }
  27943. }
  27944. // Light
  27945. if (this.lights.length === 0) {
  27946. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  27947. }
  27948. };
  27949. /**
  27950. * Creates a default camera for the scene.
  27951. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  27952. * @param replace Whether to replace the existing active camera in the scene.
  27953. * @param attachCameraControls Whether to attach camera controls to the canvas.
  27954. */
  27955. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  27956. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  27957. if (replace === void 0) { replace = false; }
  27958. if (attachCameraControls === void 0) { attachCameraControls = false; }
  27959. // Dispose existing camera in replace mode.
  27960. if (replace) {
  27961. if (this.activeCamera) {
  27962. this.activeCamera.dispose();
  27963. this.activeCamera = null;
  27964. }
  27965. }
  27966. // Camera
  27967. if (!this.activeCamera) {
  27968. var worldExtends = this.getWorldExtends();
  27969. var worldSize = worldExtends.max.subtract(worldExtends.min);
  27970. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  27971. var camera;
  27972. var radius = worldSize.length() * 1.5;
  27973. // empty scene scenario!
  27974. if (!isFinite(radius)) {
  27975. radius = 1;
  27976. worldCenter.copyFromFloats(0, 0, 0);
  27977. }
  27978. if (createArcRotateCamera) {
  27979. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  27980. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  27981. arcRotateCamera.wheelPrecision = 100 / radius;
  27982. camera = arcRotateCamera;
  27983. }
  27984. else {
  27985. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  27986. freeCamera.setTarget(worldCenter);
  27987. camera = freeCamera;
  27988. }
  27989. camera.minZ = radius * 0.01;
  27990. camera.maxZ = radius * 1000;
  27991. camera.speed = radius * 0.2;
  27992. this.activeCamera = camera;
  27993. var canvas = this.getEngine().getRenderingCanvas();
  27994. if (attachCameraControls && canvas) {
  27995. camera.attachControl(canvas);
  27996. }
  27997. }
  27998. };
  27999. /**
  28000. * Creates a default camera and a default light
  28001. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28002. * @param replace defines if the camera and/or light will replace the existing ones
  28003. * @param attachCameraControls defines if attachControl will be called on the new camera
  28004. */
  28005. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28006. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28007. if (replace === void 0) { replace = false; }
  28008. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28009. this.createDefaultLight(replace);
  28010. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28011. };
  28012. /**
  28013. * Creates a new sky box
  28014. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28015. * @param environmentTexture defines the texture to use as environment texture
  28016. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28017. * @param scale defines the overall scale of the skybox
  28018. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28019. * @returns a new mesh holding the sky box
  28020. */
  28021. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  28022. if (pbr === void 0) { pbr = false; }
  28023. if (scale === void 0) { scale = 1000; }
  28024. if (blur === void 0) { blur = 0; }
  28025. if (environmentTexture) {
  28026. this.environmentTexture = environmentTexture;
  28027. }
  28028. if (!this.environmentTexture) {
  28029. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28030. return null;
  28031. }
  28032. // Skybox
  28033. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28034. if (pbr) {
  28035. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28036. hdrSkyboxMaterial.backFaceCulling = false;
  28037. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  28038. if (hdrSkyboxMaterial.reflectionTexture) {
  28039. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28040. }
  28041. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28042. hdrSkyboxMaterial.disableLighting = true;
  28043. hdrSkyboxMaterial.twoSidedLighting = true;
  28044. hdrSkybox.infiniteDistance = true;
  28045. hdrSkybox.material = hdrSkyboxMaterial;
  28046. }
  28047. else {
  28048. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28049. skyboxMaterial.backFaceCulling = false;
  28050. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  28051. if (skyboxMaterial.reflectionTexture) {
  28052. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28053. }
  28054. skyboxMaterial.disableLighting = true;
  28055. hdrSkybox.infiniteDistance = true;
  28056. hdrSkybox.material = skyboxMaterial;
  28057. }
  28058. return hdrSkybox;
  28059. };
  28060. /**
  28061. * Creates a new environment
  28062. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28063. * @param options defines the options you can use to configure the environment
  28064. * @returns the new EnvironmentHelper
  28065. */
  28066. Scene.prototype.createDefaultEnvironment = function (options) {
  28067. if (BABYLON.EnvironmentHelper) {
  28068. return new BABYLON.EnvironmentHelper(options, this);
  28069. }
  28070. return null;
  28071. };
  28072. /**
  28073. * Creates a new VREXperienceHelper
  28074. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28075. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28076. * @returns a new VREXperienceHelper
  28077. */
  28078. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28079. if (webVROptions === void 0) { webVROptions = {}; }
  28080. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28081. };
  28082. // Tags
  28083. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28084. if (tagsQuery === undefined) {
  28085. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28086. return list;
  28087. }
  28088. var listByTags = [];
  28089. forEach = forEach || (function (item) { return; });
  28090. for (var i in list) {
  28091. var item = list[i];
  28092. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28093. listByTags.push(item);
  28094. forEach(item);
  28095. }
  28096. }
  28097. return listByTags;
  28098. };
  28099. /**
  28100. * Get a list of meshes by tags
  28101. * @param tagsQuery defines the tags query to use
  28102. * @param forEach defines a predicate used to filter results
  28103. * @returns an array of Mesh
  28104. */
  28105. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28106. return this._getByTags(this.meshes, tagsQuery, forEach);
  28107. };
  28108. /**
  28109. * Get a list of cameras by tags
  28110. * @param tagsQuery defines the tags query to use
  28111. * @param forEach defines a predicate used to filter results
  28112. * @returns an array of Camera
  28113. */
  28114. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28115. return this._getByTags(this.cameras, tagsQuery, forEach);
  28116. };
  28117. /**
  28118. * Get a list of lights by tags
  28119. * @param tagsQuery defines the tags query to use
  28120. * @param forEach defines a predicate used to filter results
  28121. * @returns an array of Light
  28122. */
  28123. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28124. return this._getByTags(this.lights, tagsQuery, forEach);
  28125. };
  28126. /**
  28127. * Get a list of materials by tags
  28128. * @param tagsQuery defines the tags query to use
  28129. * @param forEach defines a predicate used to filter results
  28130. * @returns an array of Material
  28131. */
  28132. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28133. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28134. };
  28135. /**
  28136. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28137. * This allowed control for front to back rendering or reversly depending of the special needs.
  28138. *
  28139. * @param renderingGroupId The rendering group id corresponding to its index
  28140. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28141. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28142. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28143. */
  28144. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28145. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28146. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28147. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28148. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28149. };
  28150. /**
  28151. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28152. *
  28153. * @param renderingGroupId The rendering group id corresponding to its index
  28154. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28155. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28156. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28157. */
  28158. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28159. if (depth === void 0) { depth = true; }
  28160. if (stencil === void 0) { stencil = true; }
  28161. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28162. };
  28163. /**
  28164. * Will flag all materials as dirty to trigger new shader compilation
  28165. * @param flag defines the flag used to specify which material part must be marked as dirty
  28166. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28167. */
  28168. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28169. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28170. var material = _a[_i];
  28171. if (predicate && !predicate(material)) {
  28172. continue;
  28173. }
  28174. material.markAsDirty(flag);
  28175. }
  28176. };
  28177. /** @ignore */
  28178. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28179. var _this = this;
  28180. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28181. this._activeRequests.push(request);
  28182. request.onCompleteObservable.add(function (request) {
  28183. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28184. });
  28185. return request;
  28186. };
  28187. /** @ignore */
  28188. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28189. var _this = this;
  28190. return new Promise(function (resolve, reject) {
  28191. _this._loadFile(url, function (data) {
  28192. resolve(data);
  28193. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28194. reject(exception);
  28195. });
  28196. });
  28197. };
  28198. // Statics
  28199. Scene._FOGMODE_NONE = 0;
  28200. Scene._FOGMODE_EXP = 1;
  28201. Scene._FOGMODE_EXP2 = 2;
  28202. Scene._FOGMODE_LINEAR = 3;
  28203. Scene._uniqueIdCounter = 0;
  28204. /**
  28205. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28206. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28207. */
  28208. Scene.MinDeltaTime = 1.0;
  28209. /**
  28210. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28211. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28212. */
  28213. Scene.MaxDeltaTime = 1000.0;
  28214. /** The distance in pixel that you have to move to prevent some events */
  28215. Scene.DragMovementThreshold = 10; // in pixels
  28216. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28217. Scene.LongPressDelay = 500; // in milliseconds
  28218. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28219. Scene.DoubleClickDelay = 300; // in milliseconds
  28220. /** If you need to check double click without raising a single click at first click, enable this flag */
  28221. Scene.ExclusiveDoubleClickMode = false;
  28222. return Scene;
  28223. }());
  28224. BABYLON.Scene = Scene;
  28225. })(BABYLON || (BABYLON = {}));
  28226. //# sourceMappingURL=babylon.scene.js.map
  28227. "use strict";
  28228. var BABYLON;
  28229. (function (BABYLON) {
  28230. /**
  28231. * Set of assets to keep when moving a scene into an asset container.
  28232. */
  28233. var KeepAssets = /** @class */ (function () {
  28234. function KeepAssets() {
  28235. /**
  28236. * Cameras to keep.
  28237. */
  28238. this.cameras = new Array();
  28239. /**
  28240. * Lights to keep.
  28241. */
  28242. this.lights = new Array();
  28243. /**
  28244. * Meshes to keep.
  28245. */
  28246. this.meshes = new Array();
  28247. /**
  28248. * Skeletons to keep.
  28249. */
  28250. this.skeletons = new Array();
  28251. /**
  28252. * ParticleSystems to keep.
  28253. */
  28254. this.particleSystems = new Array();
  28255. /**
  28256. * Animations to keep.
  28257. */
  28258. this.animations = new Array();
  28259. /**
  28260. * AnimationGroups to keep.
  28261. */
  28262. this.animationGroups = new Array();
  28263. /**
  28264. * MultiMaterials to keep.
  28265. */
  28266. this.multiMaterials = new Array();
  28267. /**
  28268. * Materials to keep.
  28269. */
  28270. this.materials = new Array();
  28271. /**
  28272. * MorphTargetManagers to keep.
  28273. */
  28274. this.morphTargetManagers = new Array();
  28275. /**
  28276. * Geometries to keep.
  28277. */
  28278. this.geometries = new Array();
  28279. /**
  28280. * TransformNodes to keep.
  28281. */
  28282. this.transformNodes = new Array();
  28283. /**
  28284. * LensFlareSystems to keep.
  28285. */
  28286. this.lensFlareSystems = new Array();
  28287. /**
  28288. * ShadowGenerators to keep.
  28289. */
  28290. this.shadowGenerators = new Array();
  28291. /**
  28292. * ActionManagers to keep.
  28293. */
  28294. this.actionManagers = new Array();
  28295. /**
  28296. * Sounds to keep.
  28297. */
  28298. this.sounds = new Array();
  28299. /**
  28300. * Textures to keep.
  28301. */
  28302. this.textures = new Array();
  28303. /**
  28304. * Effect layers to keep.
  28305. */
  28306. this.effectLayers = new Array();
  28307. }
  28308. return KeepAssets;
  28309. }());
  28310. BABYLON.KeepAssets = KeepAssets;
  28311. /**
  28312. * Container with a set of assets that can be added or removed from a scene.
  28313. */
  28314. var AssetContainer = /** @class */ (function () {
  28315. /**
  28316. * Instantiates an AssetContainer.
  28317. * @param scene The scene the AssetContainer belongs to.
  28318. */
  28319. function AssetContainer(scene) {
  28320. // Objects
  28321. /**
  28322. * Cameras populated in the container.
  28323. */
  28324. this.cameras = new Array();
  28325. /**
  28326. * Lights populated in the container.
  28327. */
  28328. this.lights = new Array();
  28329. /**
  28330. * Meshes populated in the container.
  28331. */
  28332. this.meshes = new Array();
  28333. /**
  28334. * Skeletons populated in the container.
  28335. */
  28336. this.skeletons = new Array();
  28337. /**
  28338. * ParticleSystems populated in the container.
  28339. */
  28340. this.particleSystems = new Array();
  28341. /**
  28342. * Animations populated in the container.
  28343. */
  28344. this.animations = new Array();
  28345. /**
  28346. * AnimationGroups populated in the container.
  28347. */
  28348. this.animationGroups = new Array();
  28349. /**
  28350. * MultiMaterials populated in the container.
  28351. */
  28352. this.multiMaterials = new Array();
  28353. /**
  28354. * Materials populated in the container.
  28355. */
  28356. this.materials = new Array();
  28357. /**
  28358. * MorphTargetManagers populated in the container.
  28359. */
  28360. this.morphTargetManagers = new Array();
  28361. /**
  28362. * Geometries populated in the container.
  28363. */
  28364. this.geometries = new Array();
  28365. /**
  28366. * TransformNodes populated in the container.
  28367. */
  28368. this.transformNodes = new Array();
  28369. /**
  28370. * LensFlareSystems populated in the container.
  28371. */
  28372. this.lensFlareSystems = new Array();
  28373. /**
  28374. * ShadowGenerators populated in the container.
  28375. */
  28376. this.shadowGenerators = new Array();
  28377. /**
  28378. * ActionManagers populated in the container.
  28379. */
  28380. this.actionManagers = new Array();
  28381. /**
  28382. * Sounds populated in the container.
  28383. */
  28384. this.sounds = new Array();
  28385. /**
  28386. * Textures populated in the container.
  28387. */
  28388. this.textures = new Array();
  28389. /**
  28390. * Effect layers populated in the container.
  28391. */
  28392. this.effectLayers = new Array();
  28393. this.scene = scene;
  28394. }
  28395. /**
  28396. * Adds all the assets from the container to the scene.
  28397. */
  28398. AssetContainer.prototype.addAllToScene = function () {
  28399. var _this = this;
  28400. this.cameras.forEach(function (o) {
  28401. _this.scene.addCamera(o);
  28402. });
  28403. this.lights.forEach(function (o) {
  28404. _this.scene.addLight(o);
  28405. });
  28406. this.meshes.forEach(function (o) {
  28407. _this.scene.addMesh(o);
  28408. });
  28409. this.skeletons.forEach(function (o) {
  28410. _this.scene.addSkeleton(o);
  28411. });
  28412. this.particleSystems.forEach(function (o) {
  28413. _this.scene.addParticleSystem(o);
  28414. });
  28415. this.animations.forEach(function (o) {
  28416. _this.scene.addAnimation(o);
  28417. });
  28418. this.animationGroups.forEach(function (o) {
  28419. _this.scene.addAnimationGroup(o);
  28420. });
  28421. this.multiMaterials.forEach(function (o) {
  28422. _this.scene.addMultiMaterial(o);
  28423. });
  28424. this.materials.forEach(function (o) {
  28425. _this.scene.addMaterial(o);
  28426. });
  28427. this.morphTargetManagers.forEach(function (o) {
  28428. _this.scene.addMorphTargetManager(o);
  28429. });
  28430. this.geometries.forEach(function (o) {
  28431. _this.scene.addGeometry(o);
  28432. });
  28433. this.transformNodes.forEach(function (o) {
  28434. _this.scene.addTransformNode(o);
  28435. });
  28436. this.lensFlareSystems.forEach(function (o) {
  28437. _this.scene.addLensFlareSystem(o);
  28438. });
  28439. this.actionManagers.forEach(function (o) {
  28440. _this.scene.addActionManager(o);
  28441. });
  28442. this.sounds.forEach(function (o) {
  28443. o.play();
  28444. o.autoplay = true;
  28445. _this.scene.mainSoundTrack.AddSound(o);
  28446. });
  28447. this.textures.forEach(function (o) {
  28448. _this.scene.addTexture(o);
  28449. });
  28450. this.effectLayers.forEach(function (o) {
  28451. _this.scene.addEffectLayer(o);
  28452. });
  28453. };
  28454. /**
  28455. * Removes all the assets in the container from the scene
  28456. */
  28457. AssetContainer.prototype.removeAllFromScene = function () {
  28458. var _this = this;
  28459. this.cameras.forEach(function (o) {
  28460. _this.scene.removeCamera(o);
  28461. });
  28462. this.lights.forEach(function (o) {
  28463. _this.scene.removeLight(o);
  28464. });
  28465. this.meshes.forEach(function (o) {
  28466. _this.scene.removeMesh(o);
  28467. });
  28468. this.skeletons.forEach(function (o) {
  28469. _this.scene.removeSkeleton(o);
  28470. });
  28471. this.particleSystems.forEach(function (o) {
  28472. _this.scene.removeParticleSystem(o);
  28473. });
  28474. this.animations.forEach(function (o) {
  28475. _this.scene.removeAnimation(o);
  28476. });
  28477. this.animationGroups.forEach(function (o) {
  28478. _this.scene.removeAnimationGroup(o);
  28479. });
  28480. this.multiMaterials.forEach(function (o) {
  28481. _this.scene.removeMultiMaterial(o);
  28482. });
  28483. this.materials.forEach(function (o) {
  28484. _this.scene.removeMaterial(o);
  28485. });
  28486. this.morphTargetManagers.forEach(function (o) {
  28487. _this.scene.removeMorphTargetManager(o);
  28488. });
  28489. this.geometries.forEach(function (o) {
  28490. _this.scene.removeGeometry(o);
  28491. });
  28492. this.transformNodes.forEach(function (o) {
  28493. _this.scene.removeTransformNode(o);
  28494. });
  28495. this.lensFlareSystems.forEach(function (o) {
  28496. _this.scene.removeLensFlareSystem(o);
  28497. });
  28498. this.actionManagers.forEach(function (o) {
  28499. _this.scene.removeActionManager(o);
  28500. });
  28501. this.sounds.forEach(function (o) {
  28502. o.stop();
  28503. o.autoplay = false;
  28504. _this.scene.mainSoundTrack.RemoveSound(o);
  28505. });
  28506. this.textures.forEach(function (o) {
  28507. _this.scene.removeTexture(o);
  28508. });
  28509. this.effectLayers.forEach(function (o) {
  28510. _this.scene.removeEffectLayer(o);
  28511. });
  28512. };
  28513. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28514. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28515. var asset = sourceAssets_1[_i];
  28516. var move = true;
  28517. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28518. var keepAsset = keepAssets_1[_a];
  28519. if (asset === keepAsset) {
  28520. move = false;
  28521. break;
  28522. }
  28523. }
  28524. if (move) {
  28525. targetAssets.push(asset);
  28526. }
  28527. }
  28528. };
  28529. /**
  28530. * Removes all the assets contained in the scene and adds them to the container.
  28531. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28532. */
  28533. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28534. if (keepAssets === undefined) {
  28535. keepAssets = new KeepAssets();
  28536. }
  28537. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  28538. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  28539. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  28540. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  28541. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  28542. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  28543. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  28544. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  28545. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  28546. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  28547. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  28548. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  28549. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  28550. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  28551. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  28552. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  28553. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  28554. this.removeAllFromScene();
  28555. };
  28556. return AssetContainer;
  28557. }());
  28558. BABYLON.AssetContainer = AssetContainer;
  28559. })(BABYLON || (BABYLON = {}));
  28560. //# sourceMappingURL=babylon.assetContainer.js.map
  28561. "use strict";
  28562. var BABYLON;
  28563. (function (BABYLON) {
  28564. var Buffer = /** @class */ (function () {
  28565. /**
  28566. * Constructor
  28567. * @param engine the engine
  28568. * @param data the data to use for this buffer
  28569. * @param updatable whether the data is updatable
  28570. * @param stride the stride (optional)
  28571. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28572. * @param instanced whether the buffer is instanced (optional)
  28573. * @param useBytes set to true if the stride in in bytes (optional)
  28574. */
  28575. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28576. if (stride === void 0) { stride = 0; }
  28577. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28578. if (instanced === void 0) { instanced = false; }
  28579. if (useBytes === void 0) { useBytes = false; }
  28580. if (engine instanceof BABYLON.Mesh) {
  28581. this._engine = engine.getScene().getEngine();
  28582. }
  28583. else {
  28584. this._engine = engine;
  28585. }
  28586. this._updatable = updatable;
  28587. this._instanced = instanced;
  28588. this._data = data;
  28589. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28590. if (!postponeInternalCreation) {
  28591. this.create();
  28592. }
  28593. }
  28594. /**
  28595. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28596. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28597. * @param offset defines offset in the buffer (0 by default)
  28598. * @param size defines the size in floats of attributes (position is 3 for instance)
  28599. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28600. * @param instanced defines if the vertex buffer contains indexed data
  28601. * @param useBytes defines if the offset and stride are in bytes
  28602. * @returns the new vertex buffer
  28603. */
  28604. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28605. if (useBytes === void 0) { useBytes = false; }
  28606. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28607. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28608. // a lot of these parameters are ignored as they are overriden by the buffer
  28609. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28610. };
  28611. // Properties
  28612. Buffer.prototype.isUpdatable = function () {
  28613. return this._updatable;
  28614. };
  28615. Buffer.prototype.getData = function () {
  28616. return this._data;
  28617. };
  28618. Buffer.prototype.getBuffer = function () {
  28619. return this._buffer;
  28620. };
  28621. /**
  28622. * Gets the stride in float32 units (i.e. byte stride / 4).
  28623. * May not be an integer if the byte stride is not divisible by 4.
  28624. * DEPRECATED. Use byteStride instead.
  28625. * @returns the stride in float32 units
  28626. */
  28627. Buffer.prototype.getStrideSize = function () {
  28628. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28629. };
  28630. // Methods
  28631. Buffer.prototype.create = function (data) {
  28632. if (data === void 0) { data = null; }
  28633. if (!data && this._buffer) {
  28634. return; // nothing to do
  28635. }
  28636. data = data || this._data;
  28637. if (!data) {
  28638. return;
  28639. }
  28640. if (!this._buffer) {
  28641. if (this._updatable) {
  28642. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28643. this._data = data;
  28644. }
  28645. else {
  28646. this._buffer = this._engine.createVertexBuffer(data);
  28647. }
  28648. }
  28649. else if (this._updatable) {
  28650. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28651. this._data = data;
  28652. }
  28653. };
  28654. Buffer.prototype._rebuild = function () {
  28655. this._buffer = null;
  28656. this.create(this._data);
  28657. };
  28658. Buffer.prototype.update = function (data) {
  28659. this.create(data);
  28660. };
  28661. /**
  28662. * Updates the data directly.
  28663. * @param data the new data
  28664. * @param offset the new offset
  28665. * @param vertexCount the vertex count (optional)
  28666. * @param useBytes set to true if the offset is in bytes
  28667. */
  28668. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28669. if (useBytes === void 0) { useBytes = false; }
  28670. if (!this._buffer) {
  28671. return;
  28672. }
  28673. if (this._updatable) {
  28674. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  28675. this._data = null;
  28676. }
  28677. };
  28678. Buffer.prototype.dispose = function () {
  28679. if (!this._buffer) {
  28680. return;
  28681. }
  28682. if (this._engine._releaseBuffer(this._buffer)) {
  28683. this._buffer = null;
  28684. }
  28685. };
  28686. return Buffer;
  28687. }());
  28688. BABYLON.Buffer = Buffer;
  28689. })(BABYLON || (BABYLON = {}));
  28690. //# sourceMappingURL=babylon.buffer.js.map
  28691. "use strict";
  28692. var BABYLON;
  28693. (function (BABYLON) {
  28694. var VertexBuffer = /** @class */ (function () {
  28695. /**
  28696. * Constructor
  28697. * @param engine the engine
  28698. * @param data the data to use for this vertex buffer
  28699. * @param kind the vertex buffer kind
  28700. * @param updatable whether the data is updatable
  28701. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28702. * @param stride the stride (optional)
  28703. * @param instanced whether the buffer is instanced (optional)
  28704. * @param offset the offset of the data (optional)
  28705. * @param size the number of components (optional)
  28706. * @param type the type of the component (optional)
  28707. * @param normalized whether the data contains normalized data (optional)
  28708. * @param useBytes set to true if stride and offset are in bytes (optional)
  28709. */
  28710. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  28711. if (normalized === void 0) { normalized = false; }
  28712. if (useBytes === void 0) { useBytes = false; }
  28713. if (data instanceof BABYLON.Buffer) {
  28714. this._buffer = data;
  28715. this._ownsBuffer = false;
  28716. }
  28717. else {
  28718. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  28719. this._ownsBuffer = true;
  28720. }
  28721. this._kind = kind;
  28722. if (type == undefined) {
  28723. var data_1 = this.getData();
  28724. this.type = VertexBuffer.FLOAT;
  28725. if (data_1 instanceof Int8Array)
  28726. this.type = VertexBuffer.BYTE;
  28727. else if (data_1 instanceof Uint8Array)
  28728. this.type = VertexBuffer.UNSIGNED_BYTE;
  28729. else if (data_1 instanceof Int16Array)
  28730. this.type = VertexBuffer.SHORT;
  28731. else if (data_1 instanceof Uint16Array)
  28732. this.type = VertexBuffer.UNSIGNED_SHORT;
  28733. else if (data_1 instanceof Int32Array)
  28734. this.type = VertexBuffer.INT;
  28735. else if (data_1 instanceof Uint32Array)
  28736. this.type = VertexBuffer.UNSIGNED_INT;
  28737. }
  28738. else {
  28739. this.type = type;
  28740. }
  28741. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  28742. if (useBytes) {
  28743. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  28744. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  28745. this.byteOffset = offset || 0;
  28746. }
  28747. else {
  28748. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  28749. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  28750. this.byteOffset = (offset || 0) * typeByteLength;
  28751. }
  28752. this.normalized = normalized;
  28753. this._instanced = instanced !== undefined ? instanced : false;
  28754. this._instanceDivisor = instanced ? 1 : 0;
  28755. }
  28756. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  28757. /**
  28758. * Gets or sets the instance divisor when in instanced mode
  28759. */
  28760. get: function () {
  28761. return this._instanceDivisor;
  28762. },
  28763. set: function (value) {
  28764. this._instanceDivisor = value;
  28765. if (value == 0) {
  28766. this._instanced = false;
  28767. }
  28768. else {
  28769. this._instanced = true;
  28770. }
  28771. },
  28772. enumerable: true,
  28773. configurable: true
  28774. });
  28775. VertexBuffer.prototype._rebuild = function () {
  28776. if (!this._buffer) {
  28777. return;
  28778. }
  28779. this._buffer._rebuild();
  28780. };
  28781. /**
  28782. * Returns the kind of the VertexBuffer (string).
  28783. */
  28784. VertexBuffer.prototype.getKind = function () {
  28785. return this._kind;
  28786. };
  28787. // Properties
  28788. /**
  28789. * Boolean : is the VertexBuffer updatable ?
  28790. */
  28791. VertexBuffer.prototype.isUpdatable = function () {
  28792. return this._buffer.isUpdatable();
  28793. };
  28794. /**
  28795. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  28796. */
  28797. VertexBuffer.prototype.getData = function () {
  28798. return this._buffer.getData();
  28799. };
  28800. /**
  28801. * Returns the WebGLBuffer associated to the VertexBuffer.
  28802. */
  28803. VertexBuffer.prototype.getBuffer = function () {
  28804. return this._buffer.getBuffer();
  28805. };
  28806. /**
  28807. * Returns the stride as a multiple of the type byte length.
  28808. * DEPRECATED. Use byteStride instead.
  28809. */
  28810. VertexBuffer.prototype.getStrideSize = function () {
  28811. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  28812. };
  28813. /**
  28814. * Returns the offset as a multiple of the type byte length.
  28815. * DEPRECATED. Use byteOffset instead.
  28816. */
  28817. VertexBuffer.prototype.getOffset = function () {
  28818. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  28819. };
  28820. /**
  28821. * Returns the number of components per vertex attribute (integer).
  28822. */
  28823. VertexBuffer.prototype.getSize = function () {
  28824. return this._size;
  28825. };
  28826. /**
  28827. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  28828. */
  28829. VertexBuffer.prototype.getIsInstanced = function () {
  28830. return this._instanced;
  28831. };
  28832. /**
  28833. * Returns the instancing divisor, zero for non-instanced (integer).
  28834. */
  28835. VertexBuffer.prototype.getInstanceDivisor = function () {
  28836. return this._instanceDivisor;
  28837. };
  28838. // Methods
  28839. /**
  28840. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  28841. * Returns the created WebGLBuffer.
  28842. */
  28843. VertexBuffer.prototype.create = function (data) {
  28844. return this._buffer.create(data);
  28845. };
  28846. /**
  28847. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28848. * This function will create a new buffer if the current one is not updatable
  28849. * Returns the updated WebGLBuffer.
  28850. */
  28851. VertexBuffer.prototype.update = function (data) {
  28852. return this._buffer.update(data);
  28853. };
  28854. /**
  28855. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28856. * Returns the directly updated WebGLBuffer.
  28857. * @param data the new data
  28858. * @param offset the new offset
  28859. * @param useBytes set to true if the offset is in bytes
  28860. */
  28861. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  28862. if (useBytes === void 0) { useBytes = false; }
  28863. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  28864. };
  28865. /**
  28866. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  28867. */
  28868. VertexBuffer.prototype.dispose = function () {
  28869. if (this._ownsBuffer) {
  28870. this._buffer.dispose();
  28871. }
  28872. };
  28873. /**
  28874. * Enumerates each value of this vertex buffer as numbers.
  28875. * @param count the number of values to enumerate
  28876. * @param callback the callback function called for each value
  28877. */
  28878. VertexBuffer.prototype.forEach = function (count, callback) {
  28879. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  28880. };
  28881. Object.defineProperty(VertexBuffer, "PositionKind", {
  28882. get: function () {
  28883. return VertexBuffer._PositionKind;
  28884. },
  28885. enumerable: true,
  28886. configurable: true
  28887. });
  28888. Object.defineProperty(VertexBuffer, "NormalKind", {
  28889. get: function () {
  28890. return VertexBuffer._NormalKind;
  28891. },
  28892. enumerable: true,
  28893. configurable: true
  28894. });
  28895. Object.defineProperty(VertexBuffer, "TangentKind", {
  28896. get: function () {
  28897. return VertexBuffer._TangentKind;
  28898. },
  28899. enumerable: true,
  28900. configurable: true
  28901. });
  28902. Object.defineProperty(VertexBuffer, "UVKind", {
  28903. get: function () {
  28904. return VertexBuffer._UVKind;
  28905. },
  28906. enumerable: true,
  28907. configurable: true
  28908. });
  28909. Object.defineProperty(VertexBuffer, "UV2Kind", {
  28910. get: function () {
  28911. return VertexBuffer._UV2Kind;
  28912. },
  28913. enumerable: true,
  28914. configurable: true
  28915. });
  28916. Object.defineProperty(VertexBuffer, "UV3Kind", {
  28917. get: function () {
  28918. return VertexBuffer._UV3Kind;
  28919. },
  28920. enumerable: true,
  28921. configurable: true
  28922. });
  28923. Object.defineProperty(VertexBuffer, "UV4Kind", {
  28924. get: function () {
  28925. return VertexBuffer._UV4Kind;
  28926. },
  28927. enumerable: true,
  28928. configurable: true
  28929. });
  28930. Object.defineProperty(VertexBuffer, "UV5Kind", {
  28931. get: function () {
  28932. return VertexBuffer._UV5Kind;
  28933. },
  28934. enumerable: true,
  28935. configurable: true
  28936. });
  28937. Object.defineProperty(VertexBuffer, "UV6Kind", {
  28938. get: function () {
  28939. return VertexBuffer._UV6Kind;
  28940. },
  28941. enumerable: true,
  28942. configurable: true
  28943. });
  28944. Object.defineProperty(VertexBuffer, "ColorKind", {
  28945. get: function () {
  28946. return VertexBuffer._ColorKind;
  28947. },
  28948. enumerable: true,
  28949. configurable: true
  28950. });
  28951. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  28952. get: function () {
  28953. return VertexBuffer._MatricesIndicesKind;
  28954. },
  28955. enumerable: true,
  28956. configurable: true
  28957. });
  28958. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  28959. get: function () {
  28960. return VertexBuffer._MatricesWeightsKind;
  28961. },
  28962. enumerable: true,
  28963. configurable: true
  28964. });
  28965. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  28966. get: function () {
  28967. return VertexBuffer._MatricesIndicesExtraKind;
  28968. },
  28969. enumerable: true,
  28970. configurable: true
  28971. });
  28972. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  28973. get: function () {
  28974. return VertexBuffer._MatricesWeightsExtraKind;
  28975. },
  28976. enumerable: true,
  28977. configurable: true
  28978. });
  28979. /**
  28980. * Deduces the stride given a kind.
  28981. * @param kind The kind string to deduce
  28982. * @returns The deduced stride
  28983. */
  28984. VertexBuffer.DeduceStride = function (kind) {
  28985. switch (kind) {
  28986. case VertexBuffer.UVKind:
  28987. case VertexBuffer.UV2Kind:
  28988. case VertexBuffer.UV3Kind:
  28989. case VertexBuffer.UV4Kind:
  28990. case VertexBuffer.UV5Kind:
  28991. case VertexBuffer.UV6Kind:
  28992. return 2;
  28993. case VertexBuffer.NormalKind:
  28994. case VertexBuffer.PositionKind:
  28995. return 3;
  28996. case VertexBuffer.ColorKind:
  28997. case VertexBuffer.MatricesIndicesKind:
  28998. case VertexBuffer.MatricesIndicesExtraKind:
  28999. case VertexBuffer.MatricesWeightsKind:
  29000. case VertexBuffer.MatricesWeightsExtraKind:
  29001. case VertexBuffer.TangentKind:
  29002. return 4;
  29003. default:
  29004. throw new Error("Invalid kind '" + kind + "'");
  29005. }
  29006. };
  29007. /**
  29008. * Gets the byte length of the given type.
  29009. * @param type the type
  29010. * @returns the number of bytes
  29011. */
  29012. VertexBuffer.GetTypeByteLength = function (type) {
  29013. switch (type) {
  29014. case VertexBuffer.BYTE:
  29015. case VertexBuffer.UNSIGNED_BYTE:
  29016. return 1;
  29017. case VertexBuffer.SHORT:
  29018. case VertexBuffer.UNSIGNED_SHORT:
  29019. return 2;
  29020. case VertexBuffer.INT:
  29021. case VertexBuffer.FLOAT:
  29022. return 4;
  29023. default:
  29024. throw new Error("Invalid type '" + type + "'");
  29025. }
  29026. };
  29027. /**
  29028. * Enumerates each value of the given parameters as numbers.
  29029. * @param data the data to enumerate
  29030. * @param byteOffset the byte offset of the data
  29031. * @param byteStride the byte stride of the data
  29032. * @param componentCount the number of components per element
  29033. * @param componentType the type of the component
  29034. * @param count the total number of components
  29035. * @param normalized whether the data is normalized
  29036. * @param callback the callback function called for each value
  29037. */
  29038. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29039. if (data instanceof Array) {
  29040. var offset = byteOffset / 4;
  29041. var stride = byteStride / 4;
  29042. for (var index = 0; index < count; index += componentCount) {
  29043. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29044. callback(data[offset + componentIndex], index + componentIndex);
  29045. }
  29046. offset += stride;
  29047. }
  29048. }
  29049. else {
  29050. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29051. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29052. for (var index = 0; index < count; index += componentCount) {
  29053. var componentByteOffset = byteOffset;
  29054. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29055. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29056. callback(value, index + componentIndex);
  29057. componentByteOffset += componentByteLength;
  29058. }
  29059. byteOffset += byteStride;
  29060. }
  29061. }
  29062. };
  29063. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29064. switch (type) {
  29065. case VertexBuffer.BYTE: {
  29066. var value = dataView.getInt8(byteOffset);
  29067. if (normalized) {
  29068. value = (value + 0.5) / 127.5;
  29069. }
  29070. return value;
  29071. }
  29072. case VertexBuffer.UNSIGNED_BYTE: {
  29073. var value = dataView.getUint8(byteOffset);
  29074. if (normalized) {
  29075. value = value / 255;
  29076. }
  29077. return value;
  29078. }
  29079. case VertexBuffer.SHORT: {
  29080. var value = dataView.getInt16(byteOffset, true);
  29081. if (normalized) {
  29082. value = (value + 0.5) / 16383.5;
  29083. }
  29084. return value;
  29085. }
  29086. case VertexBuffer.UNSIGNED_SHORT: {
  29087. var value = dataView.getUint16(byteOffset, true);
  29088. if (normalized) {
  29089. value = value / 65535;
  29090. }
  29091. return value;
  29092. }
  29093. case VertexBuffer.FLOAT: {
  29094. return dataView.getFloat32(byteOffset, true);
  29095. }
  29096. default: {
  29097. throw new Error("Invalid component type " + type);
  29098. }
  29099. }
  29100. };
  29101. /**
  29102. * The byte type.
  29103. */
  29104. VertexBuffer.BYTE = 5120;
  29105. /**
  29106. * The unsigned byte type.
  29107. */
  29108. VertexBuffer.UNSIGNED_BYTE = 5121;
  29109. /**
  29110. * The short type.
  29111. */
  29112. VertexBuffer.SHORT = 5122;
  29113. /**
  29114. * The unsigned short type.
  29115. */
  29116. VertexBuffer.UNSIGNED_SHORT = 5123;
  29117. /**
  29118. * The integer type.
  29119. */
  29120. VertexBuffer.INT = 5124;
  29121. /**
  29122. * The unsigned integer type.
  29123. */
  29124. VertexBuffer.UNSIGNED_INT = 5125;
  29125. /**
  29126. * The float type.
  29127. */
  29128. VertexBuffer.FLOAT = 5126;
  29129. // Enums
  29130. VertexBuffer._PositionKind = "position";
  29131. VertexBuffer._NormalKind = "normal";
  29132. VertexBuffer._TangentKind = "tangent";
  29133. VertexBuffer._UVKind = "uv";
  29134. VertexBuffer._UV2Kind = "uv2";
  29135. VertexBuffer._UV3Kind = "uv3";
  29136. VertexBuffer._UV4Kind = "uv4";
  29137. VertexBuffer._UV5Kind = "uv5";
  29138. VertexBuffer._UV6Kind = "uv6";
  29139. VertexBuffer._ColorKind = "color";
  29140. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29141. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29142. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29143. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29144. return VertexBuffer;
  29145. }());
  29146. BABYLON.VertexBuffer = VertexBuffer;
  29147. })(BABYLON || (BABYLON = {}));
  29148. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29149. "use strict";
  29150. var BABYLON;
  29151. (function (BABYLON) {
  29152. /**
  29153. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29154. */
  29155. var DummyInternalTextureTracker = /** @class */ (function () {
  29156. function DummyInternalTextureTracker() {
  29157. /**
  29158. * Gets or set the previous tracker in the list
  29159. */
  29160. this.previous = null;
  29161. /**
  29162. * Gets or set the next tracker in the list
  29163. */
  29164. this.next = null;
  29165. }
  29166. return DummyInternalTextureTracker;
  29167. }());
  29168. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29169. })(BABYLON || (BABYLON = {}));
  29170. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29171. "use strict";
  29172. var BABYLON;
  29173. (function (BABYLON) {
  29174. /**
  29175. * Class used to store data associated with WebGL texture data for the engine
  29176. * This class should not be used directly
  29177. */
  29178. var InternalTexture = /** @class */ (function () {
  29179. /**
  29180. * Creates a new InternalTexture
  29181. * @param engine defines the engine to use
  29182. * @param dataSource defines the type of data that will be used
  29183. */
  29184. function InternalTexture(engine, dataSource) {
  29185. /**
  29186. * Observable called when the texture is loaded
  29187. */
  29188. this.onLoadedObservable = new BABYLON.Observable();
  29189. /**
  29190. * Gets or set the previous tracker in the list
  29191. */
  29192. this.previous = null;
  29193. /**
  29194. * Gets or set the next tracker in the list
  29195. */
  29196. this.next = null;
  29197. // Private
  29198. /** @ignore */
  29199. this._initialSlot = -1;
  29200. /** @ignore */
  29201. this._designatedSlot = -1;
  29202. /** @ignore */
  29203. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29204. /** @ignore */
  29205. this._comparisonFunction = 0;
  29206. /** @ignore */
  29207. this._references = 1;
  29208. this._engine = engine;
  29209. this._dataSource = dataSource;
  29210. this._webGLTexture = engine._createTexture();
  29211. }
  29212. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29213. /**
  29214. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29215. */
  29216. get: function () {
  29217. return this._dataSource;
  29218. },
  29219. enumerable: true,
  29220. configurable: true
  29221. });
  29222. /**
  29223. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29224. */
  29225. InternalTexture.prototype.incrementReferences = function () {
  29226. this._references++;
  29227. };
  29228. /**
  29229. * Change the size of the texture (not the size of the content)
  29230. * @param width defines the new width
  29231. * @param height defines the new height
  29232. * @param depth defines the new depth (1 by default)
  29233. */
  29234. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29235. if (depth === void 0) { depth = 1; }
  29236. this.width = width;
  29237. this.height = height;
  29238. this.depth = depth;
  29239. this.baseWidth = width;
  29240. this.baseHeight = height;
  29241. this.baseDepth = depth;
  29242. this._size = width * height * depth;
  29243. };
  29244. /** @ignore */
  29245. InternalTexture.prototype._rebuild = function () {
  29246. var _this = this;
  29247. var proxy;
  29248. this.isReady = false;
  29249. this._cachedCoordinatesMode = null;
  29250. this._cachedWrapU = null;
  29251. this._cachedWrapV = null;
  29252. this._cachedAnisotropicFilteringLevel = null;
  29253. switch (this._dataSource) {
  29254. case InternalTexture.DATASOURCE_TEMP:
  29255. return;
  29256. case InternalTexture.DATASOURCE_URL:
  29257. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29258. _this.isReady = true;
  29259. }, null, this._buffer, undefined, this.format);
  29260. proxy._swapAndDie(this);
  29261. return;
  29262. case InternalTexture.DATASOURCE_RAW:
  29263. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29264. proxy._swapAndDie(this);
  29265. this.isReady = true;
  29266. return;
  29267. case InternalTexture.DATASOURCE_RAW3D:
  29268. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29269. proxy._swapAndDie(this);
  29270. this.isReady = true;
  29271. return;
  29272. case InternalTexture.DATASOURCE_DYNAMIC:
  29273. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29274. proxy._swapAndDie(this);
  29275. // The engine will make sure to update content so no need to flag it as isReady = true
  29276. return;
  29277. case InternalTexture.DATASOURCE_RENDERTARGET:
  29278. var options = new BABYLON.RenderTargetCreationOptions();
  29279. options.generateDepthBuffer = this._generateDepthBuffer;
  29280. options.generateMipMaps = this.generateMipMaps;
  29281. options.generateStencilBuffer = this._generateStencilBuffer;
  29282. options.samplingMode = this.samplingMode;
  29283. options.type = this.type;
  29284. if (this.isCube) {
  29285. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29286. }
  29287. else {
  29288. var size = {
  29289. width: this.width,
  29290. height: this.height
  29291. };
  29292. proxy = this._engine.createRenderTargetTexture(size, options);
  29293. }
  29294. proxy._swapAndDie(this);
  29295. this.isReady = true;
  29296. return;
  29297. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29298. var depthTextureOptions = {
  29299. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29300. comparisonFunction: this._comparisonFunction,
  29301. generateStencil: this._generateStencilBuffer,
  29302. isCube: this.isCube
  29303. };
  29304. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29305. proxy._swapAndDie(this);
  29306. this.isReady = true;
  29307. return;
  29308. case InternalTexture.DATASOURCE_CUBE:
  29309. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29310. _this.isReady = true;
  29311. }, null, this.format, this._extension);
  29312. proxy._swapAndDie(this);
  29313. return;
  29314. case InternalTexture.DATASOURCE_CUBERAW:
  29315. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29316. proxy._swapAndDie(this);
  29317. this.isReady = true;
  29318. return;
  29319. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29320. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29321. if (proxy) {
  29322. proxy._swapAndDie(_this);
  29323. }
  29324. _this.isReady = true;
  29325. }, null, this.format, this._extension);
  29326. return;
  29327. }
  29328. };
  29329. InternalTexture.prototype._swapAndDie = function (target) {
  29330. target._webGLTexture = this._webGLTexture;
  29331. if (this._framebuffer) {
  29332. target._framebuffer = this._framebuffer;
  29333. }
  29334. if (this._depthStencilBuffer) {
  29335. target._depthStencilBuffer = this._depthStencilBuffer;
  29336. }
  29337. if (this._lodTextureHigh) {
  29338. if (target._lodTextureHigh) {
  29339. target._lodTextureHigh.dispose();
  29340. }
  29341. target._lodTextureHigh = this._lodTextureHigh;
  29342. }
  29343. if (this._lodTextureMid) {
  29344. if (target._lodTextureMid) {
  29345. target._lodTextureMid.dispose();
  29346. }
  29347. target._lodTextureMid = this._lodTextureMid;
  29348. }
  29349. if (this._lodTextureLow) {
  29350. if (target._lodTextureLow) {
  29351. target._lodTextureLow.dispose();
  29352. }
  29353. target._lodTextureLow = this._lodTextureLow;
  29354. }
  29355. var cache = this._engine.getLoadedTexturesCache();
  29356. var index = cache.indexOf(this);
  29357. if (index !== -1) {
  29358. cache.splice(index, 1);
  29359. }
  29360. };
  29361. /**
  29362. * Dispose the current allocated resources
  29363. */
  29364. InternalTexture.prototype.dispose = function () {
  29365. if (!this._webGLTexture) {
  29366. return;
  29367. }
  29368. this._references--;
  29369. if (this._references === 0) {
  29370. this._engine._releaseTexture(this);
  29371. this._webGLTexture = null;
  29372. this.previous = null;
  29373. this.next = null;
  29374. }
  29375. };
  29376. /**
  29377. * The source of the texture data is unknown
  29378. */
  29379. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29380. /**
  29381. * Texture data comes from an URL
  29382. */
  29383. InternalTexture.DATASOURCE_URL = 1;
  29384. /**
  29385. * Texture data is only used for temporary storage
  29386. */
  29387. InternalTexture.DATASOURCE_TEMP = 2;
  29388. /**
  29389. * Texture data comes from raw data (ArrayBuffer)
  29390. */
  29391. InternalTexture.DATASOURCE_RAW = 3;
  29392. /**
  29393. * Texture content is dynamic (video or dynamic texture)
  29394. */
  29395. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29396. /**
  29397. * Texture content is generated by rendering to it
  29398. */
  29399. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29400. /**
  29401. * Texture content is part of a multi render target process
  29402. */
  29403. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29404. /**
  29405. * Texture data comes from a cube data file
  29406. */
  29407. InternalTexture.DATASOURCE_CUBE = 7;
  29408. /**
  29409. * Texture data comes from a raw cube data
  29410. */
  29411. InternalTexture.DATASOURCE_CUBERAW = 8;
  29412. /**
  29413. * Texture data come from a prefiltered cube data file
  29414. */
  29415. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29416. /**
  29417. * Texture content is raw 3D data
  29418. */
  29419. InternalTexture.DATASOURCE_RAW3D = 10;
  29420. /**
  29421. * Texture content is a depth texture
  29422. */
  29423. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29424. return InternalTexture;
  29425. }());
  29426. BABYLON.InternalTexture = InternalTexture;
  29427. })(BABYLON || (BABYLON = {}));
  29428. //# sourceMappingURL=babylon.internalTexture.js.map
  29429. "use strict";
  29430. var BABYLON;
  29431. (function (BABYLON) {
  29432. var BaseTexture = /** @class */ (function () {
  29433. function BaseTexture(scene) {
  29434. this._hasAlpha = false;
  29435. this.getAlphaFromRGB = false;
  29436. this.level = 1;
  29437. this.coordinatesIndex = 0;
  29438. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29439. /**
  29440. * | Value | Type | Description |
  29441. * | ----- | ------------------ | ----------- |
  29442. * | 0 | CLAMP_ADDRESSMODE | |
  29443. * | 1 | WRAP_ADDRESSMODE | |
  29444. * | 2 | MIRROR_ADDRESSMODE | |
  29445. */
  29446. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29447. /**
  29448. * | Value | Type | Description |
  29449. * | ----- | ------------------ | ----------- |
  29450. * | 0 | CLAMP_ADDRESSMODE | |
  29451. * | 1 | WRAP_ADDRESSMODE | |
  29452. * | 2 | MIRROR_ADDRESSMODE | |
  29453. */
  29454. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29455. /**
  29456. * | Value | Type | Description |
  29457. * | ----- | ------------------ | ----------- |
  29458. * | 0 | CLAMP_ADDRESSMODE | |
  29459. * | 1 | WRAP_ADDRESSMODE | |
  29460. * | 2 | MIRROR_ADDRESSMODE | |
  29461. */
  29462. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29463. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29464. this.isCube = false;
  29465. this.is3D = false;
  29466. this.gammaSpace = true;
  29467. this.invertZ = false;
  29468. this.lodLevelInAlpha = false;
  29469. this.lodGenerationOffset = 0.0;
  29470. this.lodGenerationScale = 0.8;
  29471. this.isRenderTarget = false;
  29472. this.animations = new Array();
  29473. /**
  29474. * An event triggered when the texture is disposed.
  29475. */
  29476. this.onDisposeObservable = new BABYLON.Observable();
  29477. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29478. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29479. if (this._scene) {
  29480. this._scene.textures.push(this);
  29481. }
  29482. this._uid = null;
  29483. }
  29484. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29485. get: function () {
  29486. return this._hasAlpha;
  29487. },
  29488. set: function (value) {
  29489. if (this._hasAlpha === value) {
  29490. return;
  29491. }
  29492. this._hasAlpha = value;
  29493. if (this._scene) {
  29494. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29495. }
  29496. },
  29497. enumerable: true,
  29498. configurable: true
  29499. });
  29500. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29501. get: function () {
  29502. return this._coordinatesMode;
  29503. },
  29504. /**
  29505. * How a texture is mapped.
  29506. *
  29507. * | Value | Type | Description |
  29508. * | ----- | ----------------------------------- | ----------- |
  29509. * | 0 | EXPLICIT_MODE | |
  29510. * | 1 | SPHERICAL_MODE | |
  29511. * | 2 | PLANAR_MODE | |
  29512. * | 3 | CUBIC_MODE | |
  29513. * | 4 | PROJECTION_MODE | |
  29514. * | 5 | SKYBOX_MODE | |
  29515. * | 6 | INVCUBIC_MODE | |
  29516. * | 7 | EQUIRECTANGULAR_MODE | |
  29517. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29518. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29519. */
  29520. set: function (value) {
  29521. if (this._coordinatesMode === value) {
  29522. return;
  29523. }
  29524. this._coordinatesMode = value;
  29525. if (this._scene) {
  29526. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29527. }
  29528. },
  29529. enumerable: true,
  29530. configurable: true
  29531. });
  29532. Object.defineProperty(BaseTexture.prototype, "uid", {
  29533. get: function () {
  29534. if (!this._uid) {
  29535. this._uid = BABYLON.Tools.RandomId();
  29536. }
  29537. return this._uid;
  29538. },
  29539. enumerable: true,
  29540. configurable: true
  29541. });
  29542. BaseTexture.prototype.toString = function () {
  29543. return this.name;
  29544. };
  29545. BaseTexture.prototype.getClassName = function () {
  29546. return "BaseTexture";
  29547. };
  29548. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29549. set: function (callback) {
  29550. if (this._onDisposeObserver) {
  29551. this.onDisposeObservable.remove(this._onDisposeObserver);
  29552. }
  29553. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29554. },
  29555. enumerable: true,
  29556. configurable: true
  29557. });
  29558. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29559. get: function () {
  29560. return true;
  29561. },
  29562. enumerable: true,
  29563. configurable: true
  29564. });
  29565. BaseTexture.prototype.getScene = function () {
  29566. return this._scene;
  29567. };
  29568. BaseTexture.prototype.getTextureMatrix = function () {
  29569. return BABYLON.Matrix.IdentityReadOnly;
  29570. };
  29571. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29572. return BABYLON.Matrix.IdentityReadOnly;
  29573. };
  29574. BaseTexture.prototype.getInternalTexture = function () {
  29575. return this._texture;
  29576. };
  29577. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29578. return !this.isBlocking || this.isReady();
  29579. };
  29580. BaseTexture.prototype.isReady = function () {
  29581. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29582. this.delayLoad();
  29583. return false;
  29584. }
  29585. if (this._texture) {
  29586. return this._texture.isReady;
  29587. }
  29588. return false;
  29589. };
  29590. BaseTexture.prototype.getSize = function () {
  29591. if (this._texture && this._texture.width) {
  29592. return new BABYLON.Size(this._texture.width, this._texture.height);
  29593. }
  29594. if (this._texture && this._texture._size) {
  29595. return new BABYLON.Size(this._texture._size, this._texture._size);
  29596. }
  29597. return BABYLON.Size.Zero();
  29598. };
  29599. BaseTexture.prototype.getBaseSize = function () {
  29600. if (!this.isReady() || !this._texture)
  29601. return BABYLON.Size.Zero();
  29602. if (this._texture._size) {
  29603. return new BABYLON.Size(this._texture._size, this._texture._size);
  29604. }
  29605. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29606. };
  29607. BaseTexture.prototype.scale = function (ratio) {
  29608. };
  29609. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29610. get: function () {
  29611. return false;
  29612. },
  29613. enumerable: true,
  29614. configurable: true
  29615. });
  29616. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29617. if (!this._scene) {
  29618. return null;
  29619. }
  29620. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29621. for (var index = 0; index < texturesCache.length; index++) {
  29622. var texturesCacheEntry = texturesCache[index];
  29623. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29624. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29625. texturesCacheEntry.incrementReferences();
  29626. return texturesCacheEntry;
  29627. }
  29628. }
  29629. }
  29630. return null;
  29631. };
  29632. BaseTexture.prototype._rebuild = function () {
  29633. };
  29634. BaseTexture.prototype.delayLoad = function () {
  29635. };
  29636. BaseTexture.prototype.clone = function () {
  29637. return null;
  29638. };
  29639. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29640. get: function () {
  29641. if (!this._texture) {
  29642. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29643. }
  29644. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29645. },
  29646. enumerable: true,
  29647. configurable: true
  29648. });
  29649. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29650. get: function () {
  29651. if (!this._texture) {
  29652. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29653. }
  29654. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29655. },
  29656. enumerable: true,
  29657. configurable: true
  29658. });
  29659. BaseTexture.prototype.readPixels = function (faceIndex) {
  29660. if (faceIndex === void 0) { faceIndex = 0; }
  29661. if (!this._texture) {
  29662. return null;
  29663. }
  29664. var size = this.getSize();
  29665. var scene = this.getScene();
  29666. if (!scene) {
  29667. return null;
  29668. }
  29669. var engine = scene.getEngine();
  29670. if (this._texture.isCube) {
  29671. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  29672. }
  29673. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  29674. };
  29675. BaseTexture.prototype.releaseInternalTexture = function () {
  29676. if (this._texture) {
  29677. this._texture.dispose();
  29678. this._texture = null;
  29679. }
  29680. };
  29681. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  29682. get: function () {
  29683. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  29684. return null;
  29685. }
  29686. if (!this._texture._sphericalPolynomial) {
  29687. this._texture._sphericalPolynomial =
  29688. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  29689. }
  29690. return this._texture._sphericalPolynomial;
  29691. },
  29692. set: function (value) {
  29693. if (this._texture) {
  29694. this._texture._sphericalPolynomial = value;
  29695. }
  29696. },
  29697. enumerable: true,
  29698. configurable: true
  29699. });
  29700. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  29701. get: function () {
  29702. if (this._texture) {
  29703. return this._texture._lodTextureHigh;
  29704. }
  29705. return null;
  29706. },
  29707. enumerable: true,
  29708. configurable: true
  29709. });
  29710. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  29711. get: function () {
  29712. if (this._texture) {
  29713. return this._texture._lodTextureMid;
  29714. }
  29715. return null;
  29716. },
  29717. enumerable: true,
  29718. configurable: true
  29719. });
  29720. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  29721. get: function () {
  29722. if (this._texture) {
  29723. return this._texture._lodTextureLow;
  29724. }
  29725. return null;
  29726. },
  29727. enumerable: true,
  29728. configurable: true
  29729. });
  29730. BaseTexture.prototype.dispose = function () {
  29731. if (!this._scene) {
  29732. return;
  29733. }
  29734. // Animations
  29735. this._scene.stopAnimation(this);
  29736. // Remove from scene
  29737. this._scene._removePendingData(this);
  29738. var index = this._scene.textures.indexOf(this);
  29739. if (index >= 0) {
  29740. this._scene.textures.splice(index, 1);
  29741. }
  29742. if (this._texture === undefined) {
  29743. return;
  29744. }
  29745. // Release
  29746. this.releaseInternalTexture();
  29747. // Callback
  29748. this.onDisposeObservable.notifyObservers(this);
  29749. this.onDisposeObservable.clear();
  29750. };
  29751. BaseTexture.prototype.serialize = function () {
  29752. if (!this.name) {
  29753. return null;
  29754. }
  29755. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29756. // Animations
  29757. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29758. return serializationObject;
  29759. };
  29760. BaseTexture.WhenAllReady = function (textures, callback) {
  29761. var numRemaining = textures.length;
  29762. if (numRemaining === 0) {
  29763. callback();
  29764. return;
  29765. }
  29766. var _loop_1 = function () {
  29767. texture = textures[i];
  29768. if (texture.isReady()) {
  29769. if (--numRemaining === 0) {
  29770. callback();
  29771. }
  29772. }
  29773. else {
  29774. onLoadObservable = texture.onLoadObservable;
  29775. var onLoadCallback_1 = function () {
  29776. onLoadObservable.removeCallback(onLoadCallback_1);
  29777. if (--numRemaining === 0) {
  29778. callback();
  29779. }
  29780. };
  29781. onLoadObservable.add(onLoadCallback_1);
  29782. }
  29783. };
  29784. var texture, onLoadObservable;
  29785. for (var i = 0; i < textures.length; i++) {
  29786. _loop_1();
  29787. }
  29788. };
  29789. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  29790. __decorate([
  29791. BABYLON.serialize()
  29792. ], BaseTexture.prototype, "name", void 0);
  29793. __decorate([
  29794. BABYLON.serialize("hasAlpha")
  29795. ], BaseTexture.prototype, "_hasAlpha", void 0);
  29796. __decorate([
  29797. BABYLON.serialize()
  29798. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  29799. __decorate([
  29800. BABYLON.serialize()
  29801. ], BaseTexture.prototype, "level", void 0);
  29802. __decorate([
  29803. BABYLON.serialize()
  29804. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  29805. __decorate([
  29806. BABYLON.serialize("coordinatesMode")
  29807. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  29808. __decorate([
  29809. BABYLON.serialize()
  29810. ], BaseTexture.prototype, "wrapU", void 0);
  29811. __decorate([
  29812. BABYLON.serialize()
  29813. ], BaseTexture.prototype, "wrapV", void 0);
  29814. __decorate([
  29815. BABYLON.serialize()
  29816. ], BaseTexture.prototype, "wrapR", void 0);
  29817. __decorate([
  29818. BABYLON.serialize()
  29819. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  29820. __decorate([
  29821. BABYLON.serialize()
  29822. ], BaseTexture.prototype, "isCube", void 0);
  29823. __decorate([
  29824. BABYLON.serialize()
  29825. ], BaseTexture.prototype, "is3D", void 0);
  29826. __decorate([
  29827. BABYLON.serialize()
  29828. ], BaseTexture.prototype, "gammaSpace", void 0);
  29829. __decorate([
  29830. BABYLON.serialize()
  29831. ], BaseTexture.prototype, "invertZ", void 0);
  29832. __decorate([
  29833. BABYLON.serialize()
  29834. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  29835. __decorate([
  29836. BABYLON.serialize()
  29837. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  29838. __decorate([
  29839. BABYLON.serialize()
  29840. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  29841. __decorate([
  29842. BABYLON.serialize()
  29843. ], BaseTexture.prototype, "isRenderTarget", void 0);
  29844. return BaseTexture;
  29845. }());
  29846. BABYLON.BaseTexture = BaseTexture;
  29847. })(BABYLON || (BABYLON = {}));
  29848. //# sourceMappingURL=babylon.baseTexture.js.map
  29849. "use strict";
  29850. var BABYLON;
  29851. (function (BABYLON) {
  29852. var Texture = /** @class */ (function (_super) {
  29853. __extends(Texture, _super);
  29854. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  29855. if (noMipmap === void 0) { noMipmap = false; }
  29856. if (invertY === void 0) { invertY = true; }
  29857. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  29858. if (onLoad === void 0) { onLoad = null; }
  29859. if (onError === void 0) { onError = null; }
  29860. if (buffer === void 0) { buffer = null; }
  29861. if (deleteBuffer === void 0) { deleteBuffer = false; }
  29862. var _this = _super.call(this, scene) || this;
  29863. _this.uOffset = 0;
  29864. _this.vOffset = 0;
  29865. _this.uScale = 1.0;
  29866. _this.vScale = 1.0;
  29867. _this.uAng = 0;
  29868. _this.vAng = 0;
  29869. _this.wAng = 0;
  29870. _this._isBlocking = true;
  29871. _this.name = url || "";
  29872. _this.url = url;
  29873. _this._noMipmap = noMipmap;
  29874. _this._invertY = invertY;
  29875. _this._samplingMode = samplingMode;
  29876. _this._buffer = buffer;
  29877. _this._deleteBuffer = deleteBuffer;
  29878. if (format) {
  29879. _this._format = format;
  29880. }
  29881. scene = _this.getScene();
  29882. if (!scene) {
  29883. return _this;
  29884. }
  29885. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  29886. var load = function () {
  29887. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  29888. _this.onLoadObservable.notifyObservers(_this);
  29889. }
  29890. if (onLoad) {
  29891. onLoad();
  29892. }
  29893. if (!_this.isBlocking && scene) {
  29894. scene.resetCachedMaterial();
  29895. }
  29896. };
  29897. if (!_this.url) {
  29898. _this._delayedOnLoad = load;
  29899. _this._delayedOnError = onError;
  29900. return _this;
  29901. }
  29902. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  29903. if (!_this._texture) {
  29904. if (!scene.useDelayedTextureLoading) {
  29905. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  29906. if (deleteBuffer) {
  29907. delete _this._buffer;
  29908. }
  29909. }
  29910. else {
  29911. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29912. _this._delayedOnLoad = load;
  29913. _this._delayedOnError = onError;
  29914. }
  29915. }
  29916. else {
  29917. if (_this._texture.isReady) {
  29918. BABYLON.Tools.SetImmediate(function () { return load(); });
  29919. }
  29920. else {
  29921. _this._texture.onLoadedObservable.add(load);
  29922. }
  29923. }
  29924. return _this;
  29925. }
  29926. Object.defineProperty(Texture.prototype, "noMipmap", {
  29927. get: function () {
  29928. return this._noMipmap;
  29929. },
  29930. enumerable: true,
  29931. configurable: true
  29932. });
  29933. Object.defineProperty(Texture.prototype, "isBlocking", {
  29934. get: function () {
  29935. return this._isBlocking;
  29936. },
  29937. set: function (value) {
  29938. this._isBlocking = value;
  29939. },
  29940. enumerable: true,
  29941. configurable: true
  29942. });
  29943. Object.defineProperty(Texture.prototype, "samplingMode", {
  29944. get: function () {
  29945. return this._samplingMode;
  29946. },
  29947. enumerable: true,
  29948. configurable: true
  29949. });
  29950. Texture.prototype.updateURL = function (url) {
  29951. this.url = url;
  29952. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29953. this.delayLoad();
  29954. };
  29955. Texture.prototype.delayLoad = function () {
  29956. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29957. return;
  29958. }
  29959. var scene = this.getScene();
  29960. if (!scene) {
  29961. return;
  29962. }
  29963. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29964. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  29965. if (!this._texture) {
  29966. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  29967. if (this._deleteBuffer) {
  29968. delete this._buffer;
  29969. }
  29970. }
  29971. else {
  29972. if (this._delayedOnLoad) {
  29973. if (this._texture.isReady) {
  29974. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  29975. }
  29976. else {
  29977. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  29978. }
  29979. }
  29980. }
  29981. this._delayedOnLoad = null;
  29982. this._delayedOnError = null;
  29983. };
  29984. Texture.prototype.updateSamplingMode = function (samplingMode) {
  29985. if (!this._texture) {
  29986. return;
  29987. }
  29988. var scene = this.getScene();
  29989. if (!scene) {
  29990. return;
  29991. }
  29992. this._samplingMode = samplingMode;
  29993. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  29994. };
  29995. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  29996. x *= this.uScale;
  29997. y *= this.vScale;
  29998. x -= 0.5 * this.uScale;
  29999. y -= 0.5 * this.vScale;
  30000. z -= 0.5;
  30001. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30002. t.x += 0.5 * this.uScale + this.uOffset;
  30003. t.y += 0.5 * this.vScale + this.vOffset;
  30004. t.z += 0.5;
  30005. };
  30006. Texture.prototype.getTextureMatrix = function () {
  30007. var _this = this;
  30008. if (this.uOffset === this._cachedUOffset &&
  30009. this.vOffset === this._cachedVOffset &&
  30010. this.uScale === this._cachedUScale &&
  30011. this.vScale === this._cachedVScale &&
  30012. this.uAng === this._cachedUAng &&
  30013. this.vAng === this._cachedVAng &&
  30014. this.wAng === this._cachedWAng) {
  30015. return this._cachedTextureMatrix;
  30016. }
  30017. this._cachedUOffset = this.uOffset;
  30018. this._cachedVOffset = this.vOffset;
  30019. this._cachedUScale = this.uScale;
  30020. this._cachedVScale = this.vScale;
  30021. this._cachedUAng = this.uAng;
  30022. this._cachedVAng = this.vAng;
  30023. this._cachedWAng = this.wAng;
  30024. if (!this._cachedTextureMatrix) {
  30025. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30026. this._rowGenerationMatrix = new BABYLON.Matrix();
  30027. this._t0 = BABYLON.Vector3.Zero();
  30028. this._t1 = BABYLON.Vector3.Zero();
  30029. this._t2 = BABYLON.Vector3.Zero();
  30030. }
  30031. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30032. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30033. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30034. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30035. this._t1.subtractInPlace(this._t0);
  30036. this._t2.subtractInPlace(this._t0);
  30037. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30038. this._cachedTextureMatrix.m[0] = this._t1.x;
  30039. this._cachedTextureMatrix.m[1] = this._t1.y;
  30040. this._cachedTextureMatrix.m[2] = this._t1.z;
  30041. this._cachedTextureMatrix.m[4] = this._t2.x;
  30042. this._cachedTextureMatrix.m[5] = this._t2.y;
  30043. this._cachedTextureMatrix.m[6] = this._t2.z;
  30044. this._cachedTextureMatrix.m[8] = this._t0.x;
  30045. this._cachedTextureMatrix.m[9] = this._t0.y;
  30046. this._cachedTextureMatrix.m[10] = this._t0.z;
  30047. var scene = this.getScene();
  30048. if (!scene) {
  30049. return this._cachedTextureMatrix;
  30050. }
  30051. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30052. return mat.hasTexture(_this);
  30053. });
  30054. return this._cachedTextureMatrix;
  30055. };
  30056. Texture.prototype.getReflectionTextureMatrix = function () {
  30057. var _this = this;
  30058. var scene = this.getScene();
  30059. if (!scene) {
  30060. return this._cachedTextureMatrix;
  30061. }
  30062. if (this.uOffset === this._cachedUOffset &&
  30063. this.vOffset === this._cachedVOffset &&
  30064. this.uScale === this._cachedUScale &&
  30065. this.vScale === this._cachedVScale &&
  30066. this.coordinatesMode === this._cachedCoordinatesMode) {
  30067. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30068. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30069. return this._cachedTextureMatrix;
  30070. }
  30071. }
  30072. else {
  30073. return this._cachedTextureMatrix;
  30074. }
  30075. }
  30076. if (!this._cachedTextureMatrix) {
  30077. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30078. }
  30079. if (!this._projectionModeMatrix) {
  30080. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30081. }
  30082. this._cachedUOffset = this.uOffset;
  30083. this._cachedVOffset = this.vOffset;
  30084. this._cachedUScale = this.uScale;
  30085. this._cachedVScale = this.vScale;
  30086. this._cachedCoordinatesMode = this.coordinatesMode;
  30087. switch (this.coordinatesMode) {
  30088. case Texture.PLANAR_MODE:
  30089. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30090. this._cachedTextureMatrix[0] = this.uScale;
  30091. this._cachedTextureMatrix[5] = this.vScale;
  30092. this._cachedTextureMatrix[12] = this.uOffset;
  30093. this._cachedTextureMatrix[13] = this.vOffset;
  30094. break;
  30095. case Texture.PROJECTION_MODE:
  30096. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30097. this._projectionModeMatrix.m[0] = 0.5;
  30098. this._projectionModeMatrix.m[5] = -0.5;
  30099. this._projectionModeMatrix.m[10] = 0.0;
  30100. this._projectionModeMatrix.m[12] = 0.5;
  30101. this._projectionModeMatrix.m[13] = 0.5;
  30102. this._projectionModeMatrix.m[14] = 1.0;
  30103. this._projectionModeMatrix.m[15] = 1.0;
  30104. var projectionMatrix = scene.getProjectionMatrix();
  30105. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30106. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30107. break;
  30108. default:
  30109. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30110. break;
  30111. }
  30112. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30113. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30114. });
  30115. return this._cachedTextureMatrix;
  30116. };
  30117. Texture.prototype.clone = function () {
  30118. var _this = this;
  30119. return BABYLON.SerializationHelper.Clone(function () {
  30120. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30121. }, this);
  30122. };
  30123. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30124. get: function () {
  30125. if (!this._onLoadObservable) {
  30126. this._onLoadObservable = new BABYLON.Observable();
  30127. }
  30128. return this._onLoadObservable;
  30129. },
  30130. enumerable: true,
  30131. configurable: true
  30132. });
  30133. Texture.prototype.serialize = function () {
  30134. var serializationObject = _super.prototype.serialize.call(this);
  30135. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30136. serializationObject.base64String = this._buffer;
  30137. serializationObject.name = serializationObject.name.replace("data:", "");
  30138. }
  30139. serializationObject.invertY = this._invertY;
  30140. serializationObject.samplingMode = this.samplingMode;
  30141. return serializationObject;
  30142. };
  30143. Texture.prototype.getClassName = function () {
  30144. return "Texture";
  30145. };
  30146. Texture.prototype.dispose = function () {
  30147. _super.prototype.dispose.call(this);
  30148. if (this.onLoadObservable) {
  30149. this.onLoadObservable.clear();
  30150. this._onLoadObservable = null;
  30151. }
  30152. this._delayedOnLoad = null;
  30153. this._delayedOnError = null;
  30154. };
  30155. // Statics
  30156. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30157. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30158. if (onLoad === void 0) { onLoad = null; }
  30159. if (onError === void 0) { onError = null; }
  30160. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30161. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30162. };
  30163. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30164. if (parsedTexture.customType) {
  30165. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30166. // Update Sampling Mode
  30167. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30168. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30169. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30170. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30171. }
  30172. }
  30173. return parsedCustomTexture;
  30174. }
  30175. if (parsedTexture.isCube) {
  30176. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30177. }
  30178. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30179. return null;
  30180. }
  30181. var texture = BABYLON.SerializationHelper.Parse(function () {
  30182. var generateMipMaps = true;
  30183. if (parsedTexture.noMipmap) {
  30184. generateMipMaps = false;
  30185. }
  30186. if (parsedTexture.mirrorPlane) {
  30187. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30188. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30189. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30190. return mirrorTexture;
  30191. }
  30192. else if (parsedTexture.isRenderTarget) {
  30193. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30194. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30195. return renderTargetTexture;
  30196. }
  30197. else {
  30198. var texture;
  30199. if (parsedTexture.base64String) {
  30200. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30201. }
  30202. else {
  30203. var url = rootUrl + parsedTexture.name;
  30204. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30205. url = parsedTexture.url;
  30206. }
  30207. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30208. }
  30209. return texture;
  30210. }
  30211. }, parsedTexture, scene);
  30212. // Update Sampling Mode
  30213. if (parsedTexture.samplingMode) {
  30214. var sampling = parsedTexture.samplingMode;
  30215. if (texture._samplingMode !== sampling) {
  30216. texture.updateSamplingMode(sampling);
  30217. }
  30218. }
  30219. // Animations
  30220. if (parsedTexture.animations) {
  30221. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30222. var parsedAnimation = parsedTexture.animations[animationIndex];
  30223. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30224. }
  30225. }
  30226. return texture;
  30227. };
  30228. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30229. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30230. if (noMipmap === void 0) { noMipmap = false; }
  30231. if (invertY === void 0) { invertY = true; }
  30232. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30233. if (onLoad === void 0) { onLoad = null; }
  30234. if (onError === void 0) { onError = null; }
  30235. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30236. if (name.substr(0, 5) !== "data:") {
  30237. name = "data:" + name;
  30238. }
  30239. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30240. };
  30241. // Constants
  30242. Texture.NEAREST_SAMPLINGMODE = 1;
  30243. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30244. Texture.BILINEAR_SAMPLINGMODE = 2;
  30245. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30246. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30247. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30248. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30249. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30250. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30251. Texture.NEAREST_LINEAR = 7;
  30252. Texture.NEAREST_NEAREST = 8;
  30253. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30254. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30255. Texture.LINEAR_LINEAR = 11;
  30256. Texture.LINEAR_NEAREST = 12;
  30257. Texture.EXPLICIT_MODE = 0;
  30258. Texture.SPHERICAL_MODE = 1;
  30259. Texture.PLANAR_MODE = 2;
  30260. Texture.CUBIC_MODE = 3;
  30261. Texture.PROJECTION_MODE = 4;
  30262. Texture.SKYBOX_MODE = 5;
  30263. Texture.INVCUBIC_MODE = 6;
  30264. Texture.EQUIRECTANGULAR_MODE = 7;
  30265. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30266. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30267. Texture.CLAMP_ADDRESSMODE = 0;
  30268. Texture.WRAP_ADDRESSMODE = 1;
  30269. Texture.MIRROR_ADDRESSMODE = 2;
  30270. /**
  30271. * 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
  30272. */
  30273. Texture.UseSerializedUrlIfAny = false;
  30274. __decorate([
  30275. BABYLON.serialize()
  30276. ], Texture.prototype, "url", void 0);
  30277. __decorate([
  30278. BABYLON.serialize()
  30279. ], Texture.prototype, "uOffset", void 0);
  30280. __decorate([
  30281. BABYLON.serialize()
  30282. ], Texture.prototype, "vOffset", void 0);
  30283. __decorate([
  30284. BABYLON.serialize()
  30285. ], Texture.prototype, "uScale", void 0);
  30286. __decorate([
  30287. BABYLON.serialize()
  30288. ], Texture.prototype, "vScale", void 0);
  30289. __decorate([
  30290. BABYLON.serialize()
  30291. ], Texture.prototype, "uAng", void 0);
  30292. __decorate([
  30293. BABYLON.serialize()
  30294. ], Texture.prototype, "vAng", void 0);
  30295. __decorate([
  30296. BABYLON.serialize()
  30297. ], Texture.prototype, "wAng", void 0);
  30298. __decorate([
  30299. BABYLON.serialize()
  30300. ], Texture.prototype, "isBlocking", null);
  30301. return Texture;
  30302. }(BABYLON.BaseTexture));
  30303. BABYLON.Texture = Texture;
  30304. })(BABYLON || (BABYLON = {}));
  30305. //# sourceMappingURL=babylon.texture.js.map
  30306. "use strict";
  30307. var BABYLON;
  30308. (function (BABYLON) {
  30309. var _InstancesBatch = /** @class */ (function () {
  30310. function _InstancesBatch() {
  30311. this.mustReturn = false;
  30312. this.visibleInstances = new Array();
  30313. this.renderSelf = new Array();
  30314. }
  30315. return _InstancesBatch;
  30316. }());
  30317. BABYLON._InstancesBatch = _InstancesBatch;
  30318. var Mesh = /** @class */ (function (_super) {
  30319. __extends(Mesh, _super);
  30320. /**
  30321. * @constructor
  30322. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30323. * @param {Scene} scene The scene to add this mesh to.
  30324. * @param {Node} parent The parent of this mesh, if it has one
  30325. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30326. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30327. * When false, achieved by calling a clone(), also passing False.
  30328. * This will make creation of children, recursive.
  30329. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30330. */
  30331. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30332. if (scene === void 0) { scene = null; }
  30333. if (parent === void 0) { parent = null; }
  30334. if (source === void 0) { source = null; }
  30335. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30336. var _this = _super.call(this, name, scene) || this;
  30337. // Events
  30338. /**
  30339. * An event triggered before rendering the mesh
  30340. */
  30341. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30342. /**
  30343. * An event triggered after rendering the mesh
  30344. */
  30345. _this.onAfterRenderObservable = new BABYLON.Observable();
  30346. /**
  30347. * An event triggered before drawing the mesh
  30348. */
  30349. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30350. // Members
  30351. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30352. _this.instances = new Array();
  30353. _this._LODLevels = new Array();
  30354. _this._visibleInstances = {};
  30355. _this._renderIdForInstances = new Array();
  30356. _this._batchCache = new _InstancesBatch();
  30357. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30358. // Use by builder only to know what orientation were the mesh build in.
  30359. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30360. _this.overrideMaterialSideOrientation = null;
  30361. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30362. // Will be used to save a source mesh reference, If any
  30363. _this._source = null;
  30364. scene = _this.getScene();
  30365. if (source) {
  30366. // Source mesh
  30367. _this._source = source;
  30368. // Geometry
  30369. if (source._geometry) {
  30370. source._geometry.applyToMesh(_this);
  30371. }
  30372. // Deep copy
  30373. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30374. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30375. // Metadata
  30376. if (source.metadata && source.metadata.clone) {
  30377. _this.metadata = source.metadata.clone();
  30378. }
  30379. else {
  30380. _this.metadata = source.metadata;
  30381. }
  30382. // Tags
  30383. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30384. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30385. }
  30386. // Parent
  30387. _this.parent = source.parent;
  30388. // Pivot
  30389. _this.setPivotMatrix(source.getPivotMatrix());
  30390. _this.id = name + "." + source.id;
  30391. // Material
  30392. _this.material = source.material;
  30393. var index;
  30394. if (!doNotCloneChildren) {
  30395. // Children
  30396. var directDescendants = source.getDescendants(true);
  30397. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30398. var child = directDescendants[index_1];
  30399. if (child.clone) {
  30400. child.clone(name + "." + child.name, _this);
  30401. }
  30402. }
  30403. }
  30404. // Physics clone
  30405. var physicsEngine = _this.getScene().getPhysicsEngine();
  30406. if (clonePhysicsImpostor && physicsEngine) {
  30407. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30408. if (impostor) {
  30409. _this.physicsImpostor = impostor.clone(_this);
  30410. }
  30411. }
  30412. // Particles
  30413. for (index = 0; index < scene.particleSystems.length; index++) {
  30414. var system = scene.particleSystems[index];
  30415. if (system.emitter === source) {
  30416. system.clone(system.name, _this);
  30417. }
  30418. }
  30419. _this.computeWorldMatrix(true);
  30420. }
  30421. // Parent
  30422. if (parent !== null) {
  30423. _this.parent = parent;
  30424. }
  30425. return _this;
  30426. }
  30427. Object.defineProperty(Mesh, "FRONTSIDE", {
  30428. /**
  30429. * Mesh side orientation : usually the external or front surface
  30430. */
  30431. get: function () {
  30432. return Mesh._FRONTSIDE;
  30433. },
  30434. enumerable: true,
  30435. configurable: true
  30436. });
  30437. Object.defineProperty(Mesh, "BACKSIDE", {
  30438. /**
  30439. * Mesh side orientation : usually the internal or back surface
  30440. */
  30441. get: function () {
  30442. return Mesh._BACKSIDE;
  30443. },
  30444. enumerable: true,
  30445. configurable: true
  30446. });
  30447. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30448. /**
  30449. * Mesh side orientation : both internal and external or front and back surfaces
  30450. */
  30451. get: function () {
  30452. return Mesh._DOUBLESIDE;
  30453. },
  30454. enumerable: true,
  30455. configurable: true
  30456. });
  30457. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30458. /**
  30459. * Mesh side orientation : by default, `FRONTSIDE`
  30460. */
  30461. get: function () {
  30462. return Mesh._DEFAULTSIDE;
  30463. },
  30464. enumerable: true,
  30465. configurable: true
  30466. });
  30467. Object.defineProperty(Mesh, "NO_CAP", {
  30468. /**
  30469. * Mesh cap setting : no cap
  30470. */
  30471. get: function () {
  30472. return Mesh._NO_CAP;
  30473. },
  30474. enumerable: true,
  30475. configurable: true
  30476. });
  30477. Object.defineProperty(Mesh, "CAP_START", {
  30478. /**
  30479. * Mesh cap setting : one cap at the beginning of the mesh
  30480. */
  30481. get: function () {
  30482. return Mesh._CAP_START;
  30483. },
  30484. enumerable: true,
  30485. configurable: true
  30486. });
  30487. Object.defineProperty(Mesh, "CAP_END", {
  30488. /**
  30489. * Mesh cap setting : one cap at the end of the mesh
  30490. */
  30491. get: function () {
  30492. return Mesh._CAP_END;
  30493. },
  30494. enumerable: true,
  30495. configurable: true
  30496. });
  30497. Object.defineProperty(Mesh, "CAP_ALL", {
  30498. /**
  30499. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30500. */
  30501. get: function () {
  30502. return Mesh._CAP_ALL;
  30503. },
  30504. enumerable: true,
  30505. configurable: true
  30506. });
  30507. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30508. set: function (callback) {
  30509. if (this._onBeforeDrawObserver) {
  30510. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30511. }
  30512. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30513. },
  30514. enumerable: true,
  30515. configurable: true
  30516. });
  30517. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30518. get: function () {
  30519. return this._morphTargetManager;
  30520. },
  30521. set: function (value) {
  30522. if (this._morphTargetManager === value) {
  30523. return;
  30524. }
  30525. this._morphTargetManager = value;
  30526. this._syncGeometryWithMorphTargetManager();
  30527. },
  30528. enumerable: true,
  30529. configurable: true
  30530. });
  30531. Object.defineProperty(Mesh.prototype, "source", {
  30532. get: function () {
  30533. return this._source;
  30534. },
  30535. enumerable: true,
  30536. configurable: true
  30537. });
  30538. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30539. get: function () {
  30540. return this._unIndexed;
  30541. },
  30542. set: function (value) {
  30543. if (this._unIndexed !== value) {
  30544. this._unIndexed = value;
  30545. this._markSubMeshesAsAttributesDirty();
  30546. }
  30547. },
  30548. enumerable: true,
  30549. configurable: true
  30550. });
  30551. // Methods
  30552. /**
  30553. * Returns the string "Mesh".
  30554. */
  30555. Mesh.prototype.getClassName = function () {
  30556. return "Mesh";
  30557. };
  30558. /**
  30559. * Returns a string.
  30560. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30561. */
  30562. Mesh.prototype.toString = function (fullDetails) {
  30563. var ret = _super.prototype.toString.call(this, fullDetails);
  30564. ret += ", n vertices: " + this.getTotalVertices();
  30565. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30566. if (this.animations) {
  30567. for (var i = 0; i < this.animations.length; i++) {
  30568. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30569. }
  30570. }
  30571. if (fullDetails) {
  30572. if (this._geometry) {
  30573. var ib = this.getIndices();
  30574. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30575. if (vb && ib) {
  30576. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30577. }
  30578. }
  30579. else {
  30580. ret += ", flat shading: UNKNOWN";
  30581. }
  30582. }
  30583. return ret;
  30584. };
  30585. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  30586. /**
  30587. * True if the mesh has some Levels Of Details (LOD).
  30588. * Returns a boolean.
  30589. */
  30590. get: function () {
  30591. return this._LODLevels.length > 0;
  30592. },
  30593. enumerable: true,
  30594. configurable: true
  30595. });
  30596. /**
  30597. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  30598. * @returns an array of {BABYLON.MeshLODLevel}
  30599. */
  30600. Mesh.prototype.getLODLevels = function () {
  30601. return this._LODLevels;
  30602. };
  30603. Mesh.prototype._sortLODLevels = function () {
  30604. this._LODLevels.sort(function (a, b) {
  30605. if (a.distance < b.distance) {
  30606. return 1;
  30607. }
  30608. if (a.distance > b.distance) {
  30609. return -1;
  30610. }
  30611. return 0;
  30612. });
  30613. };
  30614. /**
  30615. * Add a mesh as LOD level triggered at the given distance.
  30616. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30617. * @param {number} distance The distance from the center of the object to show this level
  30618. * @param {Mesh} mesh The mesh to be added as LOD level
  30619. * @return {Mesh} This mesh (for chaining)
  30620. */
  30621. Mesh.prototype.addLODLevel = function (distance, mesh) {
  30622. if (mesh && mesh._masterMesh) {
  30623. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  30624. return this;
  30625. }
  30626. var level = new BABYLON.MeshLODLevel(distance, mesh);
  30627. this._LODLevels.push(level);
  30628. if (mesh) {
  30629. mesh._masterMesh = this;
  30630. }
  30631. this._sortLODLevels();
  30632. return this;
  30633. };
  30634. /**
  30635. * Returns the LOD level mesh at the passed distance or null if not found.
  30636. * It is related to the method `addLODLevel(distance, mesh)`.
  30637. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30638. * Returns an object Mesh or `null`.
  30639. */
  30640. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  30641. for (var index = 0; index < this._LODLevels.length; index++) {
  30642. var level = this._LODLevels[index];
  30643. if (level.distance === distance) {
  30644. return level.mesh;
  30645. }
  30646. }
  30647. return null;
  30648. };
  30649. /**
  30650. * Remove a mesh from the LOD array
  30651. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30652. * @param {Mesh} mesh The mesh to be removed.
  30653. * @return {Mesh} This mesh (for chaining)
  30654. */
  30655. Mesh.prototype.removeLODLevel = function (mesh) {
  30656. for (var index = 0; index < this._LODLevels.length; index++) {
  30657. if (this._LODLevels[index].mesh === mesh) {
  30658. this._LODLevels.splice(index, 1);
  30659. if (mesh) {
  30660. mesh._masterMesh = null;
  30661. }
  30662. }
  30663. }
  30664. this._sortLODLevels();
  30665. return this;
  30666. };
  30667. /**
  30668. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  30669. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30670. */
  30671. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  30672. if (!this._LODLevels || this._LODLevels.length === 0) {
  30673. return this;
  30674. }
  30675. var bSphere;
  30676. if (boundingSphere) {
  30677. bSphere = boundingSphere;
  30678. }
  30679. else {
  30680. var boundingInfo = this.getBoundingInfo();
  30681. bSphere = boundingInfo.boundingSphere;
  30682. }
  30683. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  30684. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  30685. if (this.onLODLevelSelection) {
  30686. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  30687. }
  30688. return this;
  30689. }
  30690. for (var index = 0; index < this._LODLevels.length; index++) {
  30691. var level = this._LODLevels[index];
  30692. if (level.distance < distanceToCamera) {
  30693. if (level.mesh) {
  30694. level.mesh._preActivate();
  30695. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  30696. }
  30697. if (this.onLODLevelSelection) {
  30698. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  30699. }
  30700. return level.mesh;
  30701. }
  30702. }
  30703. if (this.onLODLevelSelection) {
  30704. this.onLODLevelSelection(distanceToCamera, this, this);
  30705. }
  30706. return this;
  30707. };
  30708. Object.defineProperty(Mesh.prototype, "geometry", {
  30709. /**
  30710. * Returns the mesh internal Geometry object.
  30711. */
  30712. get: function () {
  30713. return this._geometry;
  30714. },
  30715. enumerable: true,
  30716. configurable: true
  30717. });
  30718. /**
  30719. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  30720. */
  30721. Mesh.prototype.getTotalVertices = function () {
  30722. if (this._geometry === null || this._geometry === undefined) {
  30723. return 0;
  30724. }
  30725. return this._geometry.getTotalVertices();
  30726. };
  30727. /**
  30728. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  30729. * 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.
  30730. * You can force the copy with forceCopy === true
  30731. * Returns null if the mesh has no geometry or no vertex buffer.
  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.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30747. if (!this._geometry) {
  30748. return null;
  30749. }
  30750. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  30751. };
  30752. /**
  30753. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  30754. * Returns `null` if the mesh has no geometry.
  30755. * Possible `kind` values :
  30756. * - BABYLON.VertexBuffer.PositionKind
  30757. * - BABYLON.VertexBuffer.UVKind
  30758. * - BABYLON.VertexBuffer.UV2Kind
  30759. * - BABYLON.VertexBuffer.UV3Kind
  30760. * - BABYLON.VertexBuffer.UV4Kind
  30761. * - BABYLON.VertexBuffer.UV5Kind
  30762. * - BABYLON.VertexBuffer.UV6Kind
  30763. * - BABYLON.VertexBuffer.ColorKind
  30764. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30765. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30766. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30767. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30768. */
  30769. Mesh.prototype.getVertexBuffer = function (kind) {
  30770. if (!this._geometry) {
  30771. return null;
  30772. }
  30773. return this._geometry.getVertexBuffer(kind);
  30774. };
  30775. /**
  30776. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  30777. * Possible `kind` values :
  30778. * - BABYLON.VertexBuffer.PositionKind
  30779. * - BABYLON.VertexBuffer.UVKind
  30780. * - BABYLON.VertexBuffer.UV2Kind
  30781. * - BABYLON.VertexBuffer.UV3Kind
  30782. * - BABYLON.VertexBuffer.UV4Kind
  30783. * - BABYLON.VertexBuffer.UV5Kind
  30784. * - BABYLON.VertexBuffer.UV6Kind
  30785. * - BABYLON.VertexBuffer.ColorKind
  30786. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30787. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30788. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30789. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30790. */
  30791. Mesh.prototype.isVerticesDataPresent = function (kind) {
  30792. if (!this._geometry) {
  30793. if (this._delayInfo) {
  30794. return this._delayInfo.indexOf(kind) !== -1;
  30795. }
  30796. return false;
  30797. }
  30798. return this._geometry.isVerticesDataPresent(kind);
  30799. };
  30800. /**
  30801. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30802. * Possible `kind` values :
  30803. * - BABYLON.VertexBuffer.PositionKind
  30804. * - BABYLON.VertexBuffer.UVKind
  30805. * - BABYLON.VertexBuffer.UV2Kind
  30806. * - BABYLON.VertexBuffer.UV3Kind
  30807. * - BABYLON.VertexBuffer.UV4Kind
  30808. * - BABYLON.VertexBuffer.UV5Kind
  30809. * - BABYLON.VertexBuffer.UV6Kind
  30810. * - BABYLON.VertexBuffer.ColorKind
  30811. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30812. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30813. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30814. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30815. */
  30816. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  30817. if (!this._geometry) {
  30818. if (this._delayInfo) {
  30819. return this._delayInfo.indexOf(kind) !== -1;
  30820. }
  30821. return false;
  30822. }
  30823. return this._geometry.isVertexBufferUpdatable(kind);
  30824. };
  30825. /**
  30826. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  30827. * Possible `kind` values :
  30828. * - BABYLON.VertexBuffer.PositionKind
  30829. * - BABYLON.VertexBuffer.UVKind
  30830. * - BABYLON.VertexBuffer.UV2Kind
  30831. * - BABYLON.VertexBuffer.UV3Kind
  30832. * - BABYLON.VertexBuffer.UV4Kind
  30833. * - BABYLON.VertexBuffer.UV5Kind
  30834. * - BABYLON.VertexBuffer.UV6Kind
  30835. * - BABYLON.VertexBuffer.ColorKind
  30836. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30837. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30838. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30839. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30840. */
  30841. Mesh.prototype.getVerticesDataKinds = function () {
  30842. if (!this._geometry) {
  30843. var result = new Array();
  30844. if (this._delayInfo) {
  30845. this._delayInfo.forEach(function (kind, index, array) {
  30846. result.push(kind);
  30847. });
  30848. }
  30849. return result;
  30850. }
  30851. return this._geometry.getVerticesDataKinds();
  30852. };
  30853. /**
  30854. * Returns a positive integer : the total number of indices in this mesh geometry.
  30855. * Returns zero if the mesh has no geometry.
  30856. */
  30857. Mesh.prototype.getTotalIndices = function () {
  30858. if (!this._geometry) {
  30859. return 0;
  30860. }
  30861. return this._geometry.getTotalIndices();
  30862. };
  30863. /**
  30864. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  30865. * 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.
  30866. * Returns an empty array if the mesh has no geometry.
  30867. */
  30868. Mesh.prototype.getIndices = function (copyWhenShared) {
  30869. if (!this._geometry) {
  30870. return [];
  30871. }
  30872. return this._geometry.getIndices(copyWhenShared);
  30873. };
  30874. Object.defineProperty(Mesh.prototype, "isBlocked", {
  30875. get: function () {
  30876. return this._masterMesh !== null && this._masterMesh !== undefined;
  30877. },
  30878. enumerable: true,
  30879. configurable: true
  30880. });
  30881. /**
  30882. * Determine if the current mesh is ready to be rendered
  30883. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  30884. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  30885. * @returns true if all associated assets are ready (material, textures, shaders)
  30886. */
  30887. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  30888. if (completeCheck === void 0) { completeCheck = false; }
  30889. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  30890. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30891. return false;
  30892. }
  30893. if (!_super.prototype.isReady.call(this, completeCheck)) {
  30894. return false;
  30895. }
  30896. if (!this.subMeshes || this.subMeshes.length === 0) {
  30897. return true;
  30898. }
  30899. if (!completeCheck) {
  30900. return true;
  30901. }
  30902. var engine = this.getEngine();
  30903. var scene = this.getScene();
  30904. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  30905. this.computeWorldMatrix();
  30906. var mat = this.material || scene.defaultMaterial;
  30907. if (mat) {
  30908. if (mat.storeEffectOnSubMeshes) {
  30909. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  30910. var subMesh = _a[_i];
  30911. var effectiveMaterial = subMesh.getMaterial();
  30912. if (effectiveMaterial) {
  30913. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  30914. return false;
  30915. }
  30916. }
  30917. }
  30918. }
  30919. else {
  30920. if (!mat.isReady(this, hardwareInstancedRendering)) {
  30921. return false;
  30922. }
  30923. }
  30924. }
  30925. // Shadows
  30926. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  30927. var light = _c[_b];
  30928. var generator = light.getShadowGenerator();
  30929. if (generator) {
  30930. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  30931. var subMesh = _e[_d];
  30932. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  30933. return false;
  30934. }
  30935. }
  30936. }
  30937. }
  30938. // LOD
  30939. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  30940. var lod = _g[_f];
  30941. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  30942. return false;
  30943. }
  30944. }
  30945. return true;
  30946. };
  30947. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  30948. /**
  30949. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  30950. * This property is pertinent only for updatable parametric shapes.
  30951. */
  30952. get: function () {
  30953. return this._areNormalsFrozen;
  30954. },
  30955. enumerable: true,
  30956. configurable: true
  30957. });
  30958. /**
  30959. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  30960. * It has no effect at all on other shapes.
  30961. * It prevents the mesh normals from being recomputed on next `positions` array update.
  30962. * Returns the Mesh.
  30963. */
  30964. Mesh.prototype.freezeNormals = function () {
  30965. this._areNormalsFrozen = true;
  30966. return this;
  30967. };
  30968. /**
  30969. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  30970. * It has no effect at all on other shapes.
  30971. * It reactivates the mesh normals computation if it was previously frozen.
  30972. * Returns the Mesh.
  30973. */
  30974. Mesh.prototype.unfreezeNormals = function () {
  30975. this._areNormalsFrozen = false;
  30976. return this;
  30977. };
  30978. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  30979. /**
  30980. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  30981. */
  30982. set: function (count) {
  30983. this._overridenInstanceCount = count;
  30984. },
  30985. enumerable: true,
  30986. configurable: true
  30987. });
  30988. // Methods
  30989. Mesh.prototype._preActivate = function () {
  30990. var sceneRenderId = this.getScene().getRenderId();
  30991. if (this._preActivateId === sceneRenderId) {
  30992. return this;
  30993. }
  30994. this._preActivateId = sceneRenderId;
  30995. this._visibleInstances = null;
  30996. return this;
  30997. };
  30998. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  30999. if (this._visibleInstances) {
  31000. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31001. }
  31002. return this;
  31003. };
  31004. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31005. if (!this._visibleInstances) {
  31006. this._visibleInstances = {};
  31007. this._visibleInstances.defaultRenderId = renderId;
  31008. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31009. }
  31010. if (!this._visibleInstances[renderId]) {
  31011. this._visibleInstances[renderId] = new Array();
  31012. }
  31013. this._visibleInstances[renderId].push(instance);
  31014. return this;
  31015. };
  31016. /**
  31017. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31018. * This means the mesh underlying bounding box and sphere are recomputed.
  31019. * Returns the Mesh.
  31020. */
  31021. Mesh.prototype.refreshBoundingInfo = function () {
  31022. return this._refreshBoundingInfo(false);
  31023. };
  31024. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31025. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31026. return this;
  31027. }
  31028. var data = this._getPositionData(applySkeleton);
  31029. if (data) {
  31030. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31031. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31032. }
  31033. if (this.subMeshes) {
  31034. for (var index = 0; index < this.subMeshes.length; index++) {
  31035. this.subMeshes[index].refreshBoundingInfo();
  31036. }
  31037. }
  31038. this._updateBoundingInfo();
  31039. return this;
  31040. };
  31041. Mesh.prototype._getPositionData = function (applySkeleton) {
  31042. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31043. if (data && applySkeleton && this.skeleton) {
  31044. data = BABYLON.Tools.Slice(data);
  31045. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31046. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31047. if (matricesWeightsData && matricesIndicesData) {
  31048. var needExtras = this.numBoneInfluencers > 4;
  31049. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31050. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31051. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31052. var tempVector = BABYLON.Tmp.Vector3[0];
  31053. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31054. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31055. var matWeightIdx = 0;
  31056. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31057. finalMatrix.reset();
  31058. var inf;
  31059. var weight;
  31060. for (inf = 0; inf < 4; inf++) {
  31061. weight = matricesWeightsData[matWeightIdx + inf];
  31062. if (weight <= 0)
  31063. break;
  31064. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31065. finalMatrix.addToSelf(tempMatrix);
  31066. }
  31067. if (needExtras) {
  31068. for (inf = 0; inf < 4; inf++) {
  31069. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31070. if (weight <= 0)
  31071. break;
  31072. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31073. finalMatrix.addToSelf(tempMatrix);
  31074. }
  31075. }
  31076. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31077. tempVector.toArray(data, index);
  31078. }
  31079. }
  31080. }
  31081. return data;
  31082. };
  31083. Mesh.prototype._createGlobalSubMesh = function (force) {
  31084. var totalVertices = this.getTotalVertices();
  31085. if (!totalVertices || !this.getIndices()) {
  31086. return null;
  31087. }
  31088. // Check if we need to recreate the submeshes
  31089. if (this.subMeshes && this.subMeshes.length > 0) {
  31090. var ib = this.getIndices();
  31091. if (!ib) {
  31092. return null;
  31093. }
  31094. var totalIndices = ib.length;
  31095. var needToRecreate = false;
  31096. if (force) {
  31097. needToRecreate = true;
  31098. }
  31099. else {
  31100. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31101. var submesh = _a[_i];
  31102. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31103. needToRecreate = true;
  31104. break;
  31105. }
  31106. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31107. needToRecreate = true;
  31108. break;
  31109. }
  31110. }
  31111. }
  31112. if (!needToRecreate) {
  31113. return this.subMeshes[0];
  31114. }
  31115. }
  31116. this.releaseSubMeshes();
  31117. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31118. };
  31119. Mesh.prototype.subdivide = function (count) {
  31120. if (count < 1) {
  31121. return;
  31122. }
  31123. var totalIndices = this.getTotalIndices();
  31124. var subdivisionSize = (totalIndices / count) | 0;
  31125. var offset = 0;
  31126. // Ensure that subdivisionSize is a multiple of 3
  31127. while (subdivisionSize % 3 !== 0) {
  31128. subdivisionSize++;
  31129. }
  31130. this.releaseSubMeshes();
  31131. for (var index = 0; index < count; index++) {
  31132. if (offset >= totalIndices) {
  31133. break;
  31134. }
  31135. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31136. offset += subdivisionSize;
  31137. }
  31138. this.synchronizeInstances();
  31139. };
  31140. /**
  31141. * Sets the vertex data of the mesh geometry for the requested `kind`.
  31142. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  31143. * The `data` are either a numeric array either a Float32Array.
  31144. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  31145. * 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).
  31146. * Note that a new underlying VertexBuffer object is created each call.
  31147. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  31148. *
  31149. * Possible `kind` values :
  31150. * - BABYLON.VertexBuffer.PositionKind
  31151. * - BABYLON.VertexBuffer.UVKind
  31152. * - BABYLON.VertexBuffer.UV2Kind
  31153. * - BABYLON.VertexBuffer.UV3Kind
  31154. * - BABYLON.VertexBuffer.UV4Kind
  31155. * - BABYLON.VertexBuffer.UV5Kind
  31156. * - BABYLON.VertexBuffer.UV6Kind
  31157. * - BABYLON.VertexBuffer.ColorKind
  31158. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31159. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31160. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31161. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31162. *
  31163. * Returns the Mesh.
  31164. */
  31165. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31166. if (updatable === void 0) { updatable = false; }
  31167. if (!this._geometry) {
  31168. var vertexData = new BABYLON.VertexData();
  31169. vertexData.set(data, kind);
  31170. var scene = this.getScene();
  31171. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31172. }
  31173. else {
  31174. this._geometry.setVerticesData(kind, data, updatable, stride);
  31175. }
  31176. return this;
  31177. };
  31178. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31179. if (updatable === void 0) { updatable = true; }
  31180. var vb = this.getVertexBuffer(kind);
  31181. if (!vb || vb.isUpdatable() === updatable) {
  31182. return;
  31183. }
  31184. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31185. };
  31186. /**
  31187. * Sets the mesh VertexBuffer.
  31188. * Returns the Mesh.
  31189. */
  31190. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31191. if (!this._geometry) {
  31192. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31193. }
  31194. this._geometry.setVerticesBuffer(buffer);
  31195. return this;
  31196. };
  31197. /**
  31198. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  31199. * If the mesh has no geometry, it is simply returned as it is.
  31200. * The `data` are either a numeric array either a Float32Array.
  31201. * No new underlying VertexBuffer object is created.
  31202. * 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.
  31203. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  31204. *
  31205. * Possible `kind` values :
  31206. * - BABYLON.VertexBuffer.PositionKind
  31207. * - BABYLON.VertexBuffer.UVKind
  31208. * - BABYLON.VertexBuffer.UV2Kind
  31209. * - BABYLON.VertexBuffer.UV3Kind
  31210. * - BABYLON.VertexBuffer.UV4Kind
  31211. * - BABYLON.VertexBuffer.UV5Kind
  31212. * - BABYLON.VertexBuffer.UV6Kind
  31213. * - BABYLON.VertexBuffer.ColorKind
  31214. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31215. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31216. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31217. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31218. *
  31219. * Returns the Mesh.
  31220. */
  31221. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31222. if (!this._geometry) {
  31223. return this;
  31224. }
  31225. if (!makeItUnique) {
  31226. this._geometry.updateVerticesData(kind, data, updateExtends);
  31227. }
  31228. else {
  31229. this.makeGeometryUnique();
  31230. this.updateVerticesData(kind, data, updateExtends, false);
  31231. }
  31232. return this;
  31233. };
  31234. /**
  31235. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31236. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31237. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31238. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31239. * Returns the Mesh.
  31240. */
  31241. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31242. if (computeNormals === void 0) { computeNormals = true; }
  31243. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31244. if (!positions) {
  31245. return this;
  31246. }
  31247. positionFunction(positions);
  31248. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31249. if (computeNormals) {
  31250. var indices = this.getIndices();
  31251. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31252. if (!normals) {
  31253. return this;
  31254. }
  31255. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31256. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31257. }
  31258. return this;
  31259. };
  31260. /**
  31261. * Creates a un-shared specific occurence of the geometry for the mesh.
  31262. * Returns the Mesh.
  31263. */
  31264. Mesh.prototype.makeGeometryUnique = function () {
  31265. if (!this._geometry) {
  31266. return this;
  31267. }
  31268. var oldGeometry = this._geometry;
  31269. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31270. oldGeometry.releaseForMesh(this, true);
  31271. geometry.applyToMesh(this);
  31272. return this;
  31273. };
  31274. /**
  31275. * Sets the mesh indices.
  31276. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  31277. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  31278. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  31279. * This method creates a new index buffer each call.
  31280. * Returns the Mesh.
  31281. */
  31282. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31283. if (totalVertices === void 0) { totalVertices = null; }
  31284. if (updatable === void 0) { updatable = false; }
  31285. if (!this._geometry) {
  31286. var vertexData = new BABYLON.VertexData();
  31287. vertexData.indices = indices;
  31288. var scene = this.getScene();
  31289. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31290. }
  31291. else {
  31292. this._geometry.setIndices(indices, totalVertices, updatable);
  31293. }
  31294. return this;
  31295. };
  31296. /**
  31297. * Update the current index buffer
  31298. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31299. * Returns the Mesh.
  31300. */
  31301. Mesh.prototype.updateIndices = function (indices, offset) {
  31302. if (!this._geometry) {
  31303. return this;
  31304. }
  31305. this._geometry.updateIndices(indices, offset);
  31306. return this;
  31307. };
  31308. /**
  31309. * Invert the geometry to move from a right handed system to a left handed one.
  31310. * Returns the Mesh.
  31311. */
  31312. Mesh.prototype.toLeftHanded = function () {
  31313. if (!this._geometry) {
  31314. return this;
  31315. }
  31316. this._geometry.toLeftHanded();
  31317. return this;
  31318. };
  31319. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31320. if (!this._geometry) {
  31321. return this;
  31322. }
  31323. var engine = this.getScene().getEngine();
  31324. // Wireframe
  31325. var indexToBind;
  31326. if (this._unIndexed) {
  31327. indexToBind = null;
  31328. }
  31329. else {
  31330. switch (fillMode) {
  31331. case BABYLON.Material.PointFillMode:
  31332. indexToBind = null;
  31333. break;
  31334. case BABYLON.Material.WireFrameFillMode:
  31335. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31336. break;
  31337. default:
  31338. case BABYLON.Material.TriangleFillMode:
  31339. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31340. break;
  31341. }
  31342. }
  31343. // VBOs
  31344. this._geometry._bind(effect, indexToBind);
  31345. return this;
  31346. };
  31347. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31348. if (alternate === void 0) { alternate = false; }
  31349. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31350. return this;
  31351. }
  31352. this.onBeforeDrawObservable.notifyObservers(this);
  31353. var scene = this.getScene();
  31354. var engine = scene.getEngine();
  31355. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31356. // or triangles as points
  31357. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31358. }
  31359. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31360. // Triangles as wireframe
  31361. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31362. }
  31363. else {
  31364. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31365. }
  31366. if (scene._isAlternateRenderingEnabled && !alternate) {
  31367. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31368. if (!effect || !scene.activeCamera) {
  31369. return this;
  31370. }
  31371. scene._switchToAlternateCameraConfiguration(true);
  31372. this._effectiveMaterial.bindView(effect);
  31373. this._effectiveMaterial.bindViewProjection(effect);
  31374. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31375. this._draw(subMesh, fillMode, instancesCount, true);
  31376. engine.setViewport(scene.activeCamera.viewport);
  31377. scene._switchToAlternateCameraConfiguration(false);
  31378. this._effectiveMaterial.bindView(effect);
  31379. this._effectiveMaterial.bindViewProjection(effect);
  31380. }
  31381. return this;
  31382. };
  31383. /**
  31384. * Registers for this mesh a javascript function called just before the rendering process.
  31385. * This function is passed the current mesh.
  31386. * Return the Mesh.
  31387. */
  31388. Mesh.prototype.registerBeforeRender = function (func) {
  31389. this.onBeforeRenderObservable.add(func);
  31390. return this;
  31391. };
  31392. /**
  31393. * Disposes a previously registered javascript function called before the rendering.
  31394. * This function is passed the current mesh.
  31395. * Returns the Mesh.
  31396. */
  31397. Mesh.prototype.unregisterBeforeRender = function (func) {
  31398. this.onBeforeRenderObservable.removeCallback(func);
  31399. return this;
  31400. };
  31401. /**
  31402. * Registers for this mesh a javascript function called just after the rendering is complete.
  31403. * This function is passed the current mesh.
  31404. * Returns the Mesh.
  31405. */
  31406. Mesh.prototype.registerAfterRender = function (func) {
  31407. this.onAfterRenderObservable.add(func);
  31408. return this;
  31409. };
  31410. /**
  31411. * Disposes a previously registered javascript function called after the rendering.
  31412. * This function is passed the current mesh.
  31413. * Return the Mesh.
  31414. */
  31415. Mesh.prototype.unregisterAfterRender = function (func) {
  31416. this.onAfterRenderObservable.removeCallback(func);
  31417. return this;
  31418. };
  31419. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31420. var scene = this.getScene();
  31421. this._batchCache.mustReturn = false;
  31422. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31423. this._batchCache.visibleInstances[subMeshId] = null;
  31424. if (this._visibleInstances) {
  31425. var currentRenderId = scene.getRenderId();
  31426. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31427. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31428. var selfRenderId = this._renderId;
  31429. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31430. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31431. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31432. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31433. }
  31434. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31435. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31436. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31437. this._batchCache.mustReturn = true;
  31438. return this._batchCache;
  31439. }
  31440. if (currentRenderId !== selfRenderId) {
  31441. this._batchCache.renderSelf[subMeshId] = false;
  31442. }
  31443. }
  31444. this._renderIdForInstances[subMeshId] = currentRenderId;
  31445. }
  31446. return this._batchCache;
  31447. };
  31448. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31449. var visibleInstances = batch.visibleInstances[subMesh._id];
  31450. if (!visibleInstances) {
  31451. return this;
  31452. }
  31453. var matricesCount = visibleInstances.length + 1;
  31454. var bufferSize = matricesCount * 16 * 4;
  31455. var currentInstancesBufferSize = this._instancesBufferSize;
  31456. var instancesBuffer = this._instancesBuffer;
  31457. while (this._instancesBufferSize < bufferSize) {
  31458. this._instancesBufferSize *= 2;
  31459. }
  31460. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31461. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31462. }
  31463. var offset = 0;
  31464. var instancesCount = 0;
  31465. var world = this.getWorldMatrix();
  31466. if (batch.renderSelf[subMesh._id]) {
  31467. world.copyToArray(this._instancesData, offset);
  31468. offset += 16;
  31469. instancesCount++;
  31470. }
  31471. if (visibleInstances) {
  31472. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31473. var instance = visibleInstances[instanceIndex];
  31474. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31475. offset += 16;
  31476. instancesCount++;
  31477. }
  31478. }
  31479. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31480. if (instancesBuffer) {
  31481. instancesBuffer.dispose();
  31482. }
  31483. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31484. this._instancesBuffer = instancesBuffer;
  31485. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31486. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31487. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31488. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31489. }
  31490. else {
  31491. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31492. }
  31493. this._bind(subMesh, effect, fillMode);
  31494. this._draw(subMesh, fillMode, instancesCount);
  31495. engine.unbindInstanceAttributes();
  31496. return this;
  31497. };
  31498. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31499. var scene = this.getScene();
  31500. var engine = scene.getEngine();
  31501. if (hardwareInstancedRendering) {
  31502. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31503. }
  31504. else {
  31505. if (batch.renderSelf[subMesh._id]) {
  31506. // Draw
  31507. if (onBeforeDraw) {
  31508. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31509. }
  31510. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31511. }
  31512. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31513. if (visibleInstancesForSubMesh) {
  31514. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31515. var instance = visibleInstancesForSubMesh[instanceIndex];
  31516. // World
  31517. var world = instance.getWorldMatrix();
  31518. if (onBeforeDraw) {
  31519. onBeforeDraw(true, world, effectiveMaterial);
  31520. }
  31521. // Draw
  31522. this._draw(subMesh, fillMode);
  31523. }
  31524. }
  31525. }
  31526. return this;
  31527. };
  31528. /**
  31529. * Triggers the draw call for the mesh.
  31530. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  31531. * Returns the Mesh.
  31532. */
  31533. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31534. this.checkOcclusionQuery();
  31535. if (this._isOccluded) {
  31536. return this;
  31537. }
  31538. var scene = this.getScene();
  31539. // Managing instances
  31540. var batch = this._getInstancesRenderList(subMesh._id);
  31541. if (batch.mustReturn) {
  31542. return this;
  31543. }
  31544. // Checking geometry state
  31545. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31546. return this;
  31547. }
  31548. this.onBeforeRenderObservable.notifyObservers(this);
  31549. var engine = scene.getEngine();
  31550. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31551. // Material
  31552. var material = subMesh.getMaterial();
  31553. if (!material) {
  31554. return this;
  31555. }
  31556. this._effectiveMaterial = material;
  31557. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31558. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31559. return this;
  31560. }
  31561. }
  31562. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31563. return this;
  31564. }
  31565. // Alpha mode
  31566. if (enableAlphaMode) {
  31567. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31568. }
  31569. // Outline - step 1
  31570. var savedDepthWrite = engine.getDepthWrite();
  31571. if (this.renderOutline) {
  31572. engine.setDepthWrite(false);
  31573. scene.getOutlineRenderer().render(subMesh, batch);
  31574. engine.setDepthWrite(savedDepthWrite);
  31575. }
  31576. var effect;
  31577. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31578. effect = subMesh.effect;
  31579. }
  31580. else {
  31581. effect = this._effectiveMaterial.getEffect();
  31582. }
  31583. if (!effect) {
  31584. return this;
  31585. }
  31586. var sideOrientation = this.overrideMaterialSideOrientation;
  31587. if (sideOrientation == null) {
  31588. sideOrientation = this._effectiveMaterial.sideOrientation;
  31589. if (this._getWorldMatrixDeterminant() < 0) {
  31590. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  31591. }
  31592. }
  31593. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  31594. if (this._effectiveMaterial.forceDepthWrite) {
  31595. engine.setDepthWrite(true);
  31596. }
  31597. // Bind
  31598. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  31599. if (!hardwareInstancedRendering) {
  31600. this._bind(subMesh, effect, fillMode);
  31601. }
  31602. var world = this.getWorldMatrix();
  31603. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31604. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  31605. }
  31606. else {
  31607. this._effectiveMaterial.bind(world, this);
  31608. }
  31609. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  31610. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  31611. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31612. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  31613. }
  31614. // Draw
  31615. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31616. // Unbind
  31617. this._effectiveMaterial.unbind();
  31618. // Outline - step 2
  31619. if (this.renderOutline && savedDepthWrite) {
  31620. engine.setDepthWrite(true);
  31621. engine.setColorWrite(false);
  31622. scene.getOutlineRenderer().render(subMesh, batch);
  31623. engine.setColorWrite(true);
  31624. }
  31625. // Overlay
  31626. if (this.renderOverlay) {
  31627. var currentMode = engine.getAlphaMode();
  31628. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31629. scene.getOutlineRenderer().render(subMesh, batch, true);
  31630. engine.setAlphaMode(currentMode);
  31631. }
  31632. this.onAfterRenderObservable.notifyObservers(this);
  31633. return this;
  31634. };
  31635. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  31636. if (isInstance && effectiveMaterial) {
  31637. effectiveMaterial.bindOnlyWorldMatrix(world);
  31638. }
  31639. };
  31640. /**
  31641. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  31642. */
  31643. Mesh.prototype.getEmittedParticleSystems = function () {
  31644. var results = new Array();
  31645. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31646. var particleSystem = this.getScene().particleSystems[index];
  31647. if (particleSystem.emitter === this) {
  31648. results.push(particleSystem);
  31649. }
  31650. }
  31651. return results;
  31652. };
  31653. /**
  31654. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  31655. */
  31656. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  31657. var results = new Array();
  31658. var descendants = this.getDescendants();
  31659. descendants.push(this);
  31660. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31661. var particleSystem = this.getScene().particleSystems[index];
  31662. var emitter = particleSystem.emitter;
  31663. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  31664. results.push(particleSystem);
  31665. }
  31666. }
  31667. return results;
  31668. };
  31669. Mesh.prototype._checkDelayState = function () {
  31670. var scene = this.getScene();
  31671. if (this._geometry) {
  31672. this._geometry.load(scene);
  31673. }
  31674. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31675. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31676. this._queueLoad(scene);
  31677. }
  31678. return this;
  31679. };
  31680. Mesh.prototype._queueLoad = function (scene) {
  31681. var _this = this;
  31682. scene._addPendingData(this);
  31683. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  31684. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31685. if (data instanceof ArrayBuffer) {
  31686. _this._delayLoadingFunction(data, _this);
  31687. }
  31688. else {
  31689. _this._delayLoadingFunction(JSON.parse(data), _this);
  31690. }
  31691. _this.instances.forEach(function (instance) {
  31692. instance._syncSubMeshes();
  31693. });
  31694. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31695. scene._removePendingData(_this);
  31696. }, function () { }, scene.database, getBinaryData);
  31697. return this;
  31698. };
  31699. /**
  31700. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  31701. */
  31702. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  31703. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31704. return false;
  31705. }
  31706. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  31707. return false;
  31708. }
  31709. this._checkDelayState();
  31710. return true;
  31711. };
  31712. /**
  31713. * Sets the mesh material by the material or multiMaterial `id` property.
  31714. * The material `id` is a string identifying the material or the multiMaterial.
  31715. * This method returns the Mesh.
  31716. */
  31717. Mesh.prototype.setMaterialByID = function (id) {
  31718. var materials = this.getScene().materials;
  31719. var index;
  31720. for (index = materials.length - 1; index > -1; index--) {
  31721. if (materials[index].id === id) {
  31722. this.material = materials[index];
  31723. return this;
  31724. }
  31725. }
  31726. // Multi
  31727. var multiMaterials = this.getScene().multiMaterials;
  31728. for (index = multiMaterials.length - 1; index > -1; index--) {
  31729. if (multiMaterials[index].id === id) {
  31730. this.material = multiMaterials[index];
  31731. return this;
  31732. }
  31733. }
  31734. return this;
  31735. };
  31736. /**
  31737. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  31738. */
  31739. Mesh.prototype.getAnimatables = function () {
  31740. var results = new Array();
  31741. if (this.material) {
  31742. results.push(this.material);
  31743. }
  31744. if (this.skeleton) {
  31745. results.push(this.skeleton);
  31746. }
  31747. return results;
  31748. };
  31749. /**
  31750. * Modifies the mesh geometry according to the passed transformation matrix.
  31751. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  31752. * The mesh normals are modified accordingly the same transformation.
  31753. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  31754. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31755. * Returns the Mesh.
  31756. */
  31757. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  31758. // Position
  31759. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31760. return this;
  31761. }
  31762. var submeshes = this.subMeshes.splice(0);
  31763. this._resetPointsArrayCache();
  31764. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31765. var temp = new Array();
  31766. var index;
  31767. for (index = 0; index < data.length; index += 3) {
  31768. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  31769. }
  31770. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  31771. // Normals
  31772. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31773. return this;
  31774. }
  31775. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31776. temp = [];
  31777. for (index = 0; index < data.length; index += 3) {
  31778. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  31779. }
  31780. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  31781. // flip faces?
  31782. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  31783. this.flipFaces();
  31784. }
  31785. // Restore submeshes
  31786. this.releaseSubMeshes();
  31787. this.subMeshes = submeshes;
  31788. return this;
  31789. };
  31790. /**
  31791. * Modifies the mesh geometry according to its own current World Matrix.
  31792. * The mesh World Matrix is then reset.
  31793. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  31794. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  31795. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31796. * Returns the Mesh.
  31797. */
  31798. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  31799. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  31800. this.scaling.copyFromFloats(1, 1, 1);
  31801. this.position.copyFromFloats(0, 0, 0);
  31802. this.rotation.copyFromFloats(0, 0, 0);
  31803. //only if quaternion is already set
  31804. if (this.rotationQuaternion) {
  31805. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  31806. }
  31807. this._worldMatrix = BABYLON.Matrix.Identity();
  31808. return this;
  31809. };
  31810. Object.defineProperty(Mesh.prototype, "_positions", {
  31811. // Cache
  31812. get: function () {
  31813. if (this._geometry) {
  31814. return this._geometry._positions;
  31815. }
  31816. return null;
  31817. },
  31818. enumerable: true,
  31819. configurable: true
  31820. });
  31821. Mesh.prototype._resetPointsArrayCache = function () {
  31822. if (this._geometry) {
  31823. this._geometry._resetPointsArrayCache();
  31824. }
  31825. return this;
  31826. };
  31827. Mesh.prototype._generatePointsArray = function () {
  31828. if (this._geometry) {
  31829. return this._geometry._generatePointsArray();
  31830. }
  31831. return false;
  31832. };
  31833. /**
  31834. * Returns a new Mesh object generated from the current mesh properties.
  31835. * This method must not get confused with createInstance().
  31836. * The parameter `name` is a string, the name given to the new mesh.
  31837. * The optional parameter `newParent` can be any Node object (default `null`).
  31838. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  31839. * 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.
  31840. */
  31841. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  31842. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31843. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  31844. };
  31845. /**
  31846. * Releases resources associated with this mesh.
  31847. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  31848. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  31849. */
  31850. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  31851. var _this = this;
  31852. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  31853. this.morphTargetManager = null;
  31854. if (this._geometry) {
  31855. this._geometry.releaseForMesh(this, true);
  31856. }
  31857. // Sources
  31858. var meshes = this.getScene().meshes;
  31859. meshes.forEach(function (abstractMesh) {
  31860. var mesh = abstractMesh;
  31861. if (mesh._source && mesh._source === _this) {
  31862. mesh._source = null;
  31863. }
  31864. });
  31865. this._source = null;
  31866. // Instances
  31867. if (this._instancesBuffer) {
  31868. this._instancesBuffer.dispose();
  31869. this._instancesBuffer = null;
  31870. }
  31871. while (this.instances.length) {
  31872. this.instances[0].dispose();
  31873. }
  31874. // Effect layers.
  31875. var effectLayers = this.getScene().effectLayers;
  31876. for (var i = 0; i < effectLayers.length; i++) {
  31877. var effectLayer = effectLayers[i];
  31878. if (effectLayer) {
  31879. effectLayer._disposeMesh(this);
  31880. }
  31881. }
  31882. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  31883. };
  31884. /**
  31885. * Modifies the mesh geometry according to a displacement map.
  31886. * 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.
  31887. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  31888. * This method returns nothing.
  31889. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  31890. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  31891. * 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.
  31892. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  31893. * The parameter `uvScale` is an optional vector2 used to scale UV.
  31894. *
  31895. * Returns the Mesh.
  31896. */
  31897. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  31898. var _this = this;
  31899. var scene = this.getScene();
  31900. var onload = function (img) {
  31901. // Getting height map data
  31902. var canvas = document.createElement("canvas");
  31903. var context = canvas.getContext("2d");
  31904. var heightMapWidth = img.width;
  31905. var heightMapHeight = img.height;
  31906. canvas.width = heightMapWidth;
  31907. canvas.height = heightMapHeight;
  31908. context.drawImage(img, 0, 0);
  31909. // Create VertexData from map data
  31910. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  31911. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  31912. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  31913. //execute success callback, if set
  31914. if (onSuccess) {
  31915. onSuccess(_this);
  31916. }
  31917. };
  31918. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  31919. return this;
  31920. };
  31921. /**
  31922. * Modifies the mesh geometry according to a displacementMap buffer.
  31923. * 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.
  31924. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  31925. * This method returns nothing.
  31926. * 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.
  31927. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  31928. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  31929. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  31930. * The parameter `uvScale` is an optional vector2 used to scale UV.
  31931. *
  31932. * Returns the Mesh.
  31933. */
  31934. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  31935. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  31936. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  31937. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31938. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  31939. return this;
  31940. }
  31941. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31942. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31943. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31944. var position = BABYLON.Vector3.Zero();
  31945. var normal = BABYLON.Vector3.Zero();
  31946. var uv = BABYLON.Vector2.Zero();
  31947. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  31948. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  31949. for (var index = 0; index < positions.length; index += 3) {
  31950. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  31951. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  31952. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  31953. // Compute height
  31954. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  31955. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  31956. var pos = (u + v * heightMapWidth) * 4;
  31957. var r = buffer[pos] / 255.0;
  31958. var g = buffer[pos + 1] / 255.0;
  31959. var b = buffer[pos + 2] / 255.0;
  31960. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  31961. normal.normalize();
  31962. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  31963. position = position.add(normal);
  31964. position.toArray(positions, index);
  31965. }
  31966. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  31967. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  31968. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  31969. return this;
  31970. };
  31971. /**
  31972. * Modify the mesh to get a flat shading rendering.
  31973. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  31974. * This method returns the Mesh.
  31975. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  31976. */
  31977. Mesh.prototype.convertToFlatShadedMesh = function () {
  31978. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  31979. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  31980. var kinds = this.getVerticesDataKinds();
  31981. var vbs = {};
  31982. var data = {};
  31983. var newdata = {};
  31984. var updatableNormals = false;
  31985. var kindIndex;
  31986. var kind;
  31987. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31988. kind = kinds[kindIndex];
  31989. var vertexBuffer = this.getVertexBuffer(kind);
  31990. if (kind === BABYLON.VertexBuffer.NormalKind) {
  31991. updatableNormals = vertexBuffer.isUpdatable();
  31992. kinds.splice(kindIndex, 1);
  31993. kindIndex--;
  31994. continue;
  31995. }
  31996. vbs[kind] = vertexBuffer;
  31997. data[kind] = vbs[kind].getData();
  31998. newdata[kind] = [];
  31999. }
  32000. // Save previous submeshes
  32001. var previousSubmeshes = this.subMeshes.slice(0);
  32002. var indices = this.getIndices();
  32003. var totalIndices = this.getTotalIndices();
  32004. // Generating unique vertices per face
  32005. var index;
  32006. for (index = 0; index < totalIndices; index++) {
  32007. var vertexIndex = indices[index];
  32008. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32009. kind = kinds[kindIndex];
  32010. var stride = vbs[kind].getStrideSize();
  32011. for (var offset = 0; offset < stride; offset++) {
  32012. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32013. }
  32014. }
  32015. }
  32016. // Updating faces & normal
  32017. var normals = [];
  32018. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32019. for (index = 0; index < totalIndices; index += 3) {
  32020. indices[index] = index;
  32021. indices[index + 1] = index + 1;
  32022. indices[index + 2] = index + 2;
  32023. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32024. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32025. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32026. var p1p2 = p1.subtract(p2);
  32027. var p3p2 = p3.subtract(p2);
  32028. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32029. // Store same normals for every vertex
  32030. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32031. normals.push(normal.x);
  32032. normals.push(normal.y);
  32033. normals.push(normal.z);
  32034. }
  32035. }
  32036. this.setIndices(indices);
  32037. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32038. // Updating vertex buffers
  32039. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32040. kind = kinds[kindIndex];
  32041. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32042. }
  32043. // Updating submeshes
  32044. this.releaseSubMeshes();
  32045. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32046. var previousOne = previousSubmeshes[submeshIndex];
  32047. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32048. }
  32049. this.synchronizeInstances();
  32050. return this;
  32051. };
  32052. /**
  32053. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32054. * In other words, more vertices, no more indices and a single bigger VBO.
  32055. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32056. * Returns the Mesh.
  32057. */
  32058. Mesh.prototype.convertToUnIndexedMesh = function () {
  32059. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32060. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32061. var kinds = this.getVerticesDataKinds();
  32062. var vbs = {};
  32063. var data = {};
  32064. var newdata = {};
  32065. var kindIndex;
  32066. var kind;
  32067. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32068. kind = kinds[kindIndex];
  32069. var vertexBuffer = this.getVertexBuffer(kind);
  32070. vbs[kind] = vertexBuffer;
  32071. data[kind] = vbs[kind].getData();
  32072. newdata[kind] = [];
  32073. }
  32074. // Save previous submeshes
  32075. var previousSubmeshes = this.subMeshes.slice(0);
  32076. var indices = this.getIndices();
  32077. var totalIndices = this.getTotalIndices();
  32078. // Generating unique vertices per face
  32079. var index;
  32080. for (index = 0; index < totalIndices; index++) {
  32081. var vertexIndex = indices[index];
  32082. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32083. kind = kinds[kindIndex];
  32084. var stride = vbs[kind].getStrideSize();
  32085. for (var offset = 0; offset < stride; offset++) {
  32086. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32087. }
  32088. }
  32089. }
  32090. // Updating indices
  32091. for (index = 0; index < totalIndices; index += 3) {
  32092. indices[index] = index;
  32093. indices[index + 1] = index + 1;
  32094. indices[index + 2] = index + 2;
  32095. }
  32096. this.setIndices(indices);
  32097. // Updating vertex buffers
  32098. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32099. kind = kinds[kindIndex];
  32100. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32101. }
  32102. // Updating submeshes
  32103. this.releaseSubMeshes();
  32104. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32105. var previousOne = previousSubmeshes[submeshIndex];
  32106. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32107. }
  32108. this._unIndexed = true;
  32109. this.synchronizeInstances();
  32110. return this;
  32111. };
  32112. /**
  32113. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32114. * This method returns the Mesh.
  32115. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32116. */
  32117. Mesh.prototype.flipFaces = function (flipNormals) {
  32118. if (flipNormals === void 0) { flipNormals = false; }
  32119. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32120. var i;
  32121. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32122. for (i = 0; i < vertex_data.normals.length; i++) {
  32123. vertex_data.normals[i] *= -1;
  32124. }
  32125. }
  32126. if (vertex_data.indices) {
  32127. var temp;
  32128. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32129. // reassign indices
  32130. temp = vertex_data.indices[i + 1];
  32131. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32132. vertex_data.indices[i + 2] = temp;
  32133. }
  32134. }
  32135. vertex_data.applyToMesh(this);
  32136. return this;
  32137. };
  32138. // Instances
  32139. /**
  32140. * Creates a new InstancedMesh object from the mesh model.
  32141. * An instance shares the same properties and the same material than its model.
  32142. * Only these properties of each instance can then be set individually :
  32143. * - position
  32144. * - rotation
  32145. * - rotationQuaternion
  32146. * - setPivotMatrix
  32147. * - scaling
  32148. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32149. * Warning : this method is not supported for Line mesh and LineSystem
  32150. */
  32151. Mesh.prototype.createInstance = function (name) {
  32152. return new BABYLON.InstancedMesh(name, this);
  32153. };
  32154. /**
  32155. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32156. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32157. * This method returns the Mesh.
  32158. */
  32159. Mesh.prototype.synchronizeInstances = function () {
  32160. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32161. var instance = this.instances[instanceIndex];
  32162. instance._syncSubMeshes();
  32163. }
  32164. return this;
  32165. };
  32166. /**
  32167. * Simplify the mesh according to the given array of settings.
  32168. * Function will return immediately and will simplify async. It returns the Mesh.
  32169. * @param settings a collection of simplification settings.
  32170. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32171. * @param type the type of simplification to run.
  32172. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32173. */
  32174. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32175. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32176. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32177. this.getScene().simplificationQueue.addTask({
  32178. settings: settings,
  32179. parallelProcessing: parallelProcessing,
  32180. mesh: this,
  32181. simplificationType: simplificationType,
  32182. successCallback: successCallback
  32183. });
  32184. return this;
  32185. };
  32186. /**
  32187. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32188. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32189. * This should be used together with the simplification to avoid disappearing triangles.
  32190. * Returns the Mesh.
  32191. * @param successCallback an optional success callback to be called after the optimization finished.
  32192. */
  32193. Mesh.prototype.optimizeIndices = function (successCallback) {
  32194. var _this = this;
  32195. var indices = this.getIndices();
  32196. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32197. if (!positions || !indices) {
  32198. return this;
  32199. }
  32200. var vectorPositions = new Array();
  32201. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32202. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32203. }
  32204. var dupes = new Array();
  32205. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32206. var realPos = vectorPositions.length - 1 - iteration;
  32207. var testedPosition = vectorPositions[realPos];
  32208. for (var j = 0; j < realPos; ++j) {
  32209. var againstPosition = vectorPositions[j];
  32210. if (testedPosition.equals(againstPosition)) {
  32211. dupes[realPos] = j;
  32212. break;
  32213. }
  32214. }
  32215. }, function () {
  32216. for (var i = 0; i < indices.length; ++i) {
  32217. indices[i] = dupes[indices[i]] || indices[i];
  32218. }
  32219. //indices are now reordered
  32220. var originalSubMeshes = _this.subMeshes.slice(0);
  32221. _this.setIndices(indices);
  32222. _this.subMeshes = originalSubMeshes;
  32223. if (successCallback) {
  32224. successCallback(_this);
  32225. }
  32226. });
  32227. return this;
  32228. };
  32229. Mesh.prototype.serialize = function (serializationObject) {
  32230. serializationObject.name = this.name;
  32231. serializationObject.id = this.id;
  32232. serializationObject.type = this.getClassName();
  32233. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32234. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32235. }
  32236. serializationObject.position = this.position.asArray();
  32237. if (this.rotationQuaternion) {
  32238. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32239. }
  32240. else if (this.rotation) {
  32241. serializationObject.rotation = this.rotation.asArray();
  32242. }
  32243. serializationObject.scaling = this.scaling.asArray();
  32244. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32245. serializationObject.isEnabled = this.isEnabled(false);
  32246. serializationObject.isVisible = this.isVisible;
  32247. serializationObject.infiniteDistance = this.infiniteDistance;
  32248. serializationObject.pickable = this.isPickable;
  32249. serializationObject.receiveShadows = this.receiveShadows;
  32250. serializationObject.billboardMode = this.billboardMode;
  32251. serializationObject.visibility = this.visibility;
  32252. serializationObject.checkCollisions = this.checkCollisions;
  32253. serializationObject.isBlocker = this.isBlocker;
  32254. // Parent
  32255. if (this.parent) {
  32256. serializationObject.parentId = this.parent.id;
  32257. }
  32258. // Geometry
  32259. serializationObject.isUnIndexed = this.isUnIndexed;
  32260. var geometry = this._geometry;
  32261. if (geometry) {
  32262. var geometryId = geometry.id;
  32263. serializationObject.geometryId = geometryId;
  32264. // SubMeshes
  32265. serializationObject.subMeshes = [];
  32266. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32267. var subMesh = this.subMeshes[subIndex];
  32268. serializationObject.subMeshes.push({
  32269. materialIndex: subMesh.materialIndex,
  32270. verticesStart: subMesh.verticesStart,
  32271. verticesCount: subMesh.verticesCount,
  32272. indexStart: subMesh.indexStart,
  32273. indexCount: subMesh.indexCount
  32274. });
  32275. }
  32276. }
  32277. // Material
  32278. if (this.material) {
  32279. serializationObject.materialId = this.material.id;
  32280. }
  32281. else {
  32282. this.material = null;
  32283. }
  32284. // Morph targets
  32285. if (this.morphTargetManager) {
  32286. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32287. }
  32288. // Skeleton
  32289. if (this.skeleton) {
  32290. serializationObject.skeletonId = this.skeleton.id;
  32291. }
  32292. // Physics
  32293. //TODO implement correct serialization for physics impostors.
  32294. var impostor = this.getPhysicsImpostor();
  32295. if (impostor) {
  32296. serializationObject.physicsMass = impostor.getParam("mass");
  32297. serializationObject.physicsFriction = impostor.getParam("friction");
  32298. serializationObject.physicsRestitution = impostor.getParam("mass");
  32299. serializationObject.physicsImpostor = impostor.type;
  32300. }
  32301. // Metadata
  32302. if (this.metadata) {
  32303. serializationObject.metadata = this.metadata;
  32304. }
  32305. // Instances
  32306. serializationObject.instances = [];
  32307. for (var index = 0; index < this.instances.length; index++) {
  32308. var instance = this.instances[index];
  32309. var serializationInstance = {
  32310. name: instance.name,
  32311. id: instance.id,
  32312. position: instance.position.asArray(),
  32313. scaling: instance.scaling.asArray()
  32314. };
  32315. if (instance.rotationQuaternion) {
  32316. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32317. }
  32318. else if (instance.rotation) {
  32319. serializationInstance.rotation = instance.rotation.asArray();
  32320. }
  32321. serializationObject.instances.push(serializationInstance);
  32322. // Animations
  32323. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32324. serializationInstance.ranges = instance.serializeAnimationRanges();
  32325. }
  32326. //
  32327. // Animations
  32328. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32329. serializationObject.ranges = this.serializeAnimationRanges();
  32330. // Layer mask
  32331. serializationObject.layerMask = this.layerMask;
  32332. // Alpha
  32333. serializationObject.alphaIndex = this.alphaIndex;
  32334. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32335. // Overlay
  32336. serializationObject.overlayAlpha = this.overlayAlpha;
  32337. serializationObject.overlayColor = this.overlayColor.asArray();
  32338. serializationObject.renderOverlay = this.renderOverlay;
  32339. // Fog
  32340. serializationObject.applyFog = this.applyFog;
  32341. // Action Manager
  32342. if (this.actionManager) {
  32343. serializationObject.actions = this.actionManager.serialize(this.name);
  32344. }
  32345. };
  32346. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32347. if (!this.geometry) {
  32348. return;
  32349. }
  32350. this._markSubMeshesAsAttributesDirty();
  32351. var morphTargetManager = this._morphTargetManager;
  32352. if (morphTargetManager && morphTargetManager.vertexCount) {
  32353. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32354. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32355. this.morphTargetManager = null;
  32356. return;
  32357. }
  32358. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32359. var morphTarget = morphTargetManager.getActiveTarget(index);
  32360. var positions = morphTarget.getPositions();
  32361. if (!positions) {
  32362. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32363. return;
  32364. }
  32365. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32366. var normals = morphTarget.getNormals();
  32367. if (normals) {
  32368. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32369. }
  32370. var tangents = morphTarget.getTangents();
  32371. if (tangents) {
  32372. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32373. }
  32374. }
  32375. }
  32376. else {
  32377. var index = 0;
  32378. // Positions
  32379. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32380. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32381. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32382. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32383. }
  32384. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32385. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32386. }
  32387. index++;
  32388. }
  32389. }
  32390. };
  32391. // Statics
  32392. /**
  32393. * Returns a new Mesh object parsed from the source provided.
  32394. * The parameter `parsedMesh` is the source.
  32395. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32396. */
  32397. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32398. var mesh;
  32399. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32400. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32401. }
  32402. else {
  32403. mesh = new Mesh(parsedMesh.name, scene);
  32404. }
  32405. mesh.id = parsedMesh.id;
  32406. if (BABYLON.Tags) {
  32407. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32408. }
  32409. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32410. if (parsedMesh.metadata !== undefined) {
  32411. mesh.metadata = parsedMesh.metadata;
  32412. }
  32413. if (parsedMesh.rotationQuaternion) {
  32414. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32415. }
  32416. else if (parsedMesh.rotation) {
  32417. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32418. }
  32419. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32420. if (parsedMesh.localMatrix) {
  32421. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32422. }
  32423. else if (parsedMesh.pivotMatrix) {
  32424. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32425. }
  32426. mesh.setEnabled(parsedMesh.isEnabled);
  32427. mesh.isVisible = parsedMesh.isVisible;
  32428. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32429. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32430. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32431. if (parsedMesh.applyFog !== undefined) {
  32432. mesh.applyFog = parsedMesh.applyFog;
  32433. }
  32434. if (parsedMesh.pickable !== undefined) {
  32435. mesh.isPickable = parsedMesh.pickable;
  32436. }
  32437. if (parsedMesh.alphaIndex !== undefined) {
  32438. mesh.alphaIndex = parsedMesh.alphaIndex;
  32439. }
  32440. mesh.receiveShadows = parsedMesh.receiveShadows;
  32441. mesh.billboardMode = parsedMesh.billboardMode;
  32442. if (parsedMesh.visibility !== undefined) {
  32443. mesh.visibility = parsedMesh.visibility;
  32444. }
  32445. mesh.checkCollisions = parsedMesh.checkCollisions;
  32446. if (parsedMesh.isBlocker !== undefined) {
  32447. mesh.isBlocker = parsedMesh.isBlocker;
  32448. }
  32449. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32450. // freezeWorldMatrix
  32451. if (parsedMesh.freezeWorldMatrix) {
  32452. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32453. }
  32454. // Parent
  32455. if (parsedMesh.parentId) {
  32456. mesh._waitingParentId = parsedMesh.parentId;
  32457. }
  32458. // Actions
  32459. if (parsedMesh.actions !== undefined) {
  32460. mesh._waitingActions = parsedMesh.actions;
  32461. }
  32462. // Overlay
  32463. if (parsedMesh.overlayAlpha !== undefined) {
  32464. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32465. }
  32466. if (parsedMesh.overlayColor !== undefined) {
  32467. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32468. }
  32469. if (parsedMesh.renderOverlay !== undefined) {
  32470. mesh.renderOverlay = parsedMesh.renderOverlay;
  32471. }
  32472. // Geometry
  32473. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32474. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32475. if (parsedMesh.delayLoadingFile) {
  32476. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32477. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32478. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32479. if (parsedMesh._binaryInfo) {
  32480. mesh._binaryInfo = parsedMesh._binaryInfo;
  32481. }
  32482. mesh._delayInfo = [];
  32483. if (parsedMesh.hasUVs) {
  32484. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32485. }
  32486. if (parsedMesh.hasUVs2) {
  32487. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32488. }
  32489. if (parsedMesh.hasUVs3) {
  32490. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32491. }
  32492. if (parsedMesh.hasUVs4) {
  32493. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32494. }
  32495. if (parsedMesh.hasUVs5) {
  32496. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32497. }
  32498. if (parsedMesh.hasUVs6) {
  32499. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32500. }
  32501. if (parsedMesh.hasColors) {
  32502. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32503. }
  32504. if (parsedMesh.hasMatricesIndices) {
  32505. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32506. }
  32507. if (parsedMesh.hasMatricesWeights) {
  32508. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32509. }
  32510. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32511. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32512. mesh._checkDelayState();
  32513. }
  32514. }
  32515. else {
  32516. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32517. }
  32518. // Material
  32519. if (parsedMesh.materialId) {
  32520. mesh.setMaterialByID(parsedMesh.materialId);
  32521. }
  32522. else {
  32523. mesh.material = null;
  32524. }
  32525. // Morph targets
  32526. if (parsedMesh.morphTargetManagerId > -1) {
  32527. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32528. }
  32529. // Skeleton
  32530. if (parsedMesh.skeletonId > -1) {
  32531. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32532. if (parsedMesh.numBoneInfluencers) {
  32533. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32534. }
  32535. }
  32536. // Animations
  32537. if (parsedMesh.animations) {
  32538. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32539. var parsedAnimation = parsedMesh.animations[animationIndex];
  32540. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32541. }
  32542. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32543. }
  32544. if (parsedMesh.autoAnimate) {
  32545. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32546. }
  32547. // Layer Mask
  32548. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32549. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32550. }
  32551. else {
  32552. mesh.layerMask = 0x0FFFFFFF;
  32553. }
  32554. // Physics
  32555. if (parsedMesh.physicsImpostor) {
  32556. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32557. mass: parsedMesh.physicsMass,
  32558. friction: parsedMesh.physicsFriction,
  32559. restitution: parsedMesh.physicsRestitution
  32560. }, scene);
  32561. }
  32562. // Instances
  32563. if (parsedMesh.instances) {
  32564. for (var index = 0; index < parsedMesh.instances.length; index++) {
  32565. var parsedInstance = parsedMesh.instances[index];
  32566. var instance = mesh.createInstance(parsedInstance.name);
  32567. if (parsedInstance.id) {
  32568. instance.id = parsedInstance.id;
  32569. }
  32570. if (BABYLON.Tags) {
  32571. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  32572. }
  32573. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  32574. if (parsedInstance.parentId) {
  32575. instance._waitingParentId = parsedInstance.parentId;
  32576. }
  32577. if (parsedInstance.rotationQuaternion) {
  32578. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  32579. }
  32580. else if (parsedInstance.rotation) {
  32581. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  32582. }
  32583. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  32584. instance.checkCollisions = mesh.checkCollisions;
  32585. if (parsedMesh.animations) {
  32586. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32587. parsedAnimation = parsedMesh.animations[animationIndex];
  32588. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32589. }
  32590. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  32591. }
  32592. }
  32593. }
  32594. return mesh;
  32595. };
  32596. /**
  32597. * Creates a ribbon mesh.
  32598. * Please consider using the same method from the MeshBuilder class instead.
  32599. * 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.
  32600. *
  32601. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  32602. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  32603. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  32604. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  32605. * 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.
  32606. * 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.
  32607. * 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
  32608. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32609. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32610. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32611. */
  32612. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  32613. if (closeArray === void 0) { closeArray = false; }
  32614. if (updatable === void 0) { updatable = false; }
  32615. return BABYLON.MeshBuilder.CreateRibbon(name, {
  32616. pathArray: pathArray,
  32617. closeArray: closeArray,
  32618. closePath: closePath,
  32619. offset: offset,
  32620. updatable: updatable,
  32621. sideOrientation: sideOrientation,
  32622. instance: instance
  32623. }, scene);
  32624. };
  32625. /**
  32626. * Creates a plane polygonal mesh. By default, this is a disc.
  32627. * Please consider using the same method from the MeshBuilder class instead.
  32628. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  32629. * 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.
  32630. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32631. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32632. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32633. */
  32634. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  32635. if (scene === void 0) { scene = null; }
  32636. var options = {
  32637. radius: radius,
  32638. tessellation: tessellation,
  32639. sideOrientation: sideOrientation,
  32640. updatable: updatable
  32641. };
  32642. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  32643. };
  32644. /**
  32645. * Creates a box mesh.
  32646. * Please consider using the same method from the MeshBuilder class instead.
  32647. * The parameter `size` sets the size (float) of each box side (default 1).
  32648. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32649. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32650. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32651. */
  32652. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  32653. if (scene === void 0) { scene = null; }
  32654. var options = {
  32655. size: size,
  32656. sideOrientation: sideOrientation,
  32657. updatable: updatable
  32658. };
  32659. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  32660. };
  32661. /**
  32662. * Creates a sphere mesh.
  32663. * Please consider using the same method from the MeshBuilder class instead.
  32664. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  32665. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  32666. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32667. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32668. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32669. */
  32670. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  32671. var options = {
  32672. segments: segments,
  32673. diameterX: diameter,
  32674. diameterY: diameter,
  32675. diameterZ: diameter,
  32676. sideOrientation: sideOrientation,
  32677. updatable: updatable
  32678. };
  32679. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  32680. };
  32681. /**
  32682. * Creates a cylinder or a cone mesh.
  32683. * Please consider using the same method from the MeshBuilder class instead.
  32684. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  32685. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  32686. * 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.
  32687. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  32688. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  32689. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32690. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32691. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32692. */
  32693. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  32694. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  32695. if (scene !== undefined) {
  32696. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  32697. updatable = scene;
  32698. }
  32699. scene = subdivisions;
  32700. subdivisions = 1;
  32701. }
  32702. var options = {
  32703. height: height,
  32704. diameterTop: diameterTop,
  32705. diameterBottom: diameterBottom,
  32706. tessellation: tessellation,
  32707. subdivisions: subdivisions,
  32708. sideOrientation: sideOrientation,
  32709. updatable: updatable
  32710. };
  32711. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  32712. };
  32713. // Torus (Code from SharpDX.org)
  32714. /**
  32715. * Creates a torus mesh.
  32716. * Please consider using the same method from the MeshBuilder class instead.
  32717. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  32718. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  32719. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  32720. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32721. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32722. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32723. */
  32724. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  32725. var options = {
  32726. diameter: diameter,
  32727. thickness: thickness,
  32728. tessellation: tessellation,
  32729. sideOrientation: sideOrientation,
  32730. updatable: updatable
  32731. };
  32732. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  32733. };
  32734. /**
  32735. * Creates a torus knot mesh.
  32736. * Please consider using the same method from the MeshBuilder class instead.
  32737. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  32738. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  32739. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  32740. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  32741. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32742. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32743. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32744. */
  32745. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  32746. var options = {
  32747. radius: radius,
  32748. tube: tube,
  32749. radialSegments: radialSegments,
  32750. tubularSegments: tubularSegments,
  32751. p: p,
  32752. q: q,
  32753. sideOrientation: sideOrientation,
  32754. updatable: updatable
  32755. };
  32756. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  32757. };
  32758. /**
  32759. * Creates a line mesh.
  32760. * Please consider using the same method from the MeshBuilder class instead.
  32761. * 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.
  32762. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32763. * The parameter `points` is an array successive Vector3.
  32764. * 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
  32765. * When updating an instance, remember that only point positions can change, not the number of points.
  32766. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32767. */
  32768. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  32769. if (scene === void 0) { scene = null; }
  32770. if (updatable === void 0) { updatable = false; }
  32771. if (instance === void 0) { instance = null; }
  32772. var options = {
  32773. points: points,
  32774. updatable: updatable,
  32775. instance: instance
  32776. };
  32777. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  32778. };
  32779. /**
  32780. * Creates a dashed line mesh.
  32781. * Please consider using the same method from the MeshBuilder class instead.
  32782. * 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.
  32783. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32784. * The parameter `points` is an array successive Vector3.
  32785. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  32786. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  32787. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  32788. * 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
  32789. * When updating an instance, remember that only point positions can change, not the number of points.
  32790. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32791. */
  32792. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  32793. if (scene === void 0) { scene = null; }
  32794. var options = {
  32795. points: points,
  32796. dashSize: dashSize,
  32797. gapSize: gapSize,
  32798. dashNb: dashNb,
  32799. updatable: updatable,
  32800. instance: instance
  32801. };
  32802. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  32803. };
  32804. /**
  32805. * Creates a polygon mesh.
  32806. * Please consider using the same method from the MeshBuilder class instead.
  32807. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  32808. * 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.
  32809. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32810. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32811. * Remember you can only change the shape positions, not their number when updating a polygon.
  32812. */
  32813. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  32814. var options = {
  32815. shape: shape,
  32816. holes: holes,
  32817. updatable: updatable,
  32818. sideOrientation: sideOrientation
  32819. };
  32820. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  32821. };
  32822. /**
  32823. * Creates an extruded polygon mesh, with depth in the Y direction.
  32824. * Please consider using the same method from the MeshBuilder class instead.
  32825. */
  32826. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  32827. var options = {
  32828. shape: shape,
  32829. holes: holes,
  32830. depth: depth,
  32831. updatable: updatable,
  32832. sideOrientation: sideOrientation
  32833. };
  32834. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  32835. };
  32836. /**
  32837. * Creates an extruded shape mesh.
  32838. * 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.
  32839. * Please consider using the same method from the MeshBuilder class instead.
  32840. *
  32841. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  32842. * 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
  32843. * extruded along the Z axis.
  32844. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  32845. * 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.
  32846. * The parameter `scale` (float, default 1) is the value to scale the shape.
  32847. * 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
  32848. * 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
  32849. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  32850. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32851. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32852. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32853. */
  32854. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  32855. if (scene === void 0) { scene = null; }
  32856. var options = {
  32857. shape: shape,
  32858. path: path,
  32859. scale: scale,
  32860. rotation: rotation,
  32861. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  32862. sideOrientation: sideOrientation,
  32863. instance: instance,
  32864. updatable: updatable
  32865. };
  32866. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  32867. };
  32868. /**
  32869. * Creates an custom extruded shape mesh.
  32870. * 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.
  32871. * Please consider using the same method from the MeshBuilder class instead.
  32872. *
  32873. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  32874. * 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
  32875. * extruded along the Z axis.
  32876. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  32877. * 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
  32878. * and the distance of this point from the begining of the path :
  32879. * ```javascript
  32880. * var rotationFunction = function(i, distance) {
  32881. * // do things
  32882. * return rotationValue; }
  32883. * ```
  32884. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  32885. * 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
  32886. * and the distance of this point from the begining of the path :
  32887. * ```javascript
  32888. * var scaleFunction = function(i, distance) {
  32889. * // do things
  32890. * return scaleValue;}
  32891. * ```
  32892. * It must returns a float value that will be the scale value applied to the shape on each path point.
  32893. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  32894. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  32895. * 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
  32896. * 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
  32897. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  32898. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32899. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32900. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32901. */
  32902. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  32903. var options = {
  32904. shape: shape,
  32905. path: path,
  32906. scaleFunction: scaleFunction,
  32907. rotationFunction: rotationFunction,
  32908. ribbonCloseArray: ribbonCloseArray,
  32909. ribbonClosePath: ribbonClosePath,
  32910. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  32911. sideOrientation: sideOrientation,
  32912. instance: instance,
  32913. updatable: updatable
  32914. };
  32915. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  32916. };
  32917. /**
  32918. * Creates lathe mesh.
  32919. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  32920. * Please consider using the same method from the MeshBuilder class instead.
  32921. * 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
  32922. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  32923. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  32924. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  32925. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32926. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32927. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32928. */
  32929. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  32930. var options = {
  32931. shape: shape,
  32932. radius: radius,
  32933. tessellation: tessellation,
  32934. sideOrientation: sideOrientation,
  32935. updatable: updatable
  32936. };
  32937. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  32938. };
  32939. /**
  32940. * Creates a plane mesh.
  32941. * Please consider using the same method from the MeshBuilder class instead.
  32942. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  32943. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32944. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32945. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32946. */
  32947. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  32948. var options = {
  32949. size: size,
  32950. width: size,
  32951. height: size,
  32952. sideOrientation: sideOrientation,
  32953. updatable: updatable
  32954. };
  32955. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  32956. };
  32957. /**
  32958. * Creates a ground mesh.
  32959. * Please consider using the same method from the MeshBuilder class instead.
  32960. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  32961. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  32962. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32963. */
  32964. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  32965. var options = {
  32966. width: width,
  32967. height: height,
  32968. subdivisions: subdivisions,
  32969. updatable: updatable
  32970. };
  32971. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  32972. };
  32973. /**
  32974. * Creates a tiled ground mesh.
  32975. * Please consider using the same method from the MeshBuilder class instead.
  32976. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  32977. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  32978. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  32979. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  32980. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  32981. * numbers of subdivisions on the ground width and height of each tile.
  32982. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32983. */
  32984. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  32985. var options = {
  32986. xmin: xmin,
  32987. zmin: zmin,
  32988. xmax: xmax,
  32989. zmax: zmax,
  32990. subdivisions: subdivisions,
  32991. precision: precision,
  32992. updatable: updatable
  32993. };
  32994. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  32995. };
  32996. /**
  32997. * Creates a ground mesh from a height map.
  32998. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  32999. * Please consider using the same method from the MeshBuilder class instead.
  33000. * The parameter `url` sets the URL of the height map image resource.
  33001. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33002. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33003. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33004. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33005. * 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).
  33006. * This function is passed the newly built mesh :
  33007. * ```javascript
  33008. * function(mesh) { // do things
  33009. * return; }
  33010. * ```
  33011. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33012. */
  33013. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33014. var options = {
  33015. width: width,
  33016. height: height,
  33017. subdivisions: subdivisions,
  33018. minHeight: minHeight,
  33019. maxHeight: maxHeight,
  33020. updatable: updatable,
  33021. onReady: onReady
  33022. };
  33023. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33024. };
  33025. /**
  33026. * Creates a tube mesh.
  33027. * 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.
  33028. * Please consider using the same method from the MeshBuilder class instead.
  33029. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33030. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33031. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33032. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33033. * 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.
  33034. * It must return a radius value (positive float) :
  33035. * ```javascript
  33036. * var radiusFunction = function(i, distance) {
  33037. * // do things
  33038. * return radius; }
  33039. * ```
  33040. * 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
  33041. * 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
  33042. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33043. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33044. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33045. */
  33046. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33047. var options = {
  33048. path: path,
  33049. radius: radius,
  33050. tessellation: tessellation,
  33051. radiusFunction: radiusFunction,
  33052. arc: 1,
  33053. cap: cap,
  33054. updatable: updatable,
  33055. sideOrientation: sideOrientation,
  33056. instance: instance
  33057. };
  33058. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33059. };
  33060. /**
  33061. * Creates a polyhedron mesh.
  33062. * Please consider using the same method from the MeshBuilder class instead.
  33063. * 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
  33064. * to choose the wanted type.
  33065. * The parameter `size` (positive float, default 1) sets the polygon size.
  33066. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33067. * 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`.
  33068. * 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
  33069. * 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)`).
  33070. * 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
  33071. * 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.
  33072. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33073. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33074. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33075. */
  33076. Mesh.CreatePolyhedron = function (name, options, scene) {
  33077. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33078. };
  33079. /**
  33080. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33081. * Please consider using the same method from the MeshBuilder class instead.
  33082. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33083. * 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`).
  33084. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33085. * 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.
  33086. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33087. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33088. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33089. */
  33090. Mesh.CreateIcoSphere = function (name, options, scene) {
  33091. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33092. };
  33093. /**
  33094. * Creates a decal mesh.
  33095. * Please consider using the same method from the MeshBuilder class instead.
  33096. * 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.
  33097. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33098. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33099. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33100. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33101. */
  33102. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33103. var options = {
  33104. position: position,
  33105. normal: normal,
  33106. size: size,
  33107. angle: angle
  33108. };
  33109. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33110. };
  33111. // Skeletons
  33112. /**
  33113. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33114. */
  33115. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33116. if (!this._sourcePositions) {
  33117. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33118. if (!source) {
  33119. return this._sourcePositions;
  33120. }
  33121. this._sourcePositions = new Float32Array(source);
  33122. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33123. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33124. }
  33125. }
  33126. return this._sourcePositions;
  33127. };
  33128. /**
  33129. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33130. */
  33131. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33132. if (!this._sourceNormals) {
  33133. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33134. if (!source) {
  33135. return this._sourceNormals;
  33136. }
  33137. this._sourceNormals = new Float32Array(source);
  33138. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33139. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33140. }
  33141. }
  33142. return this._sourceNormals;
  33143. };
  33144. /**
  33145. * Updates the vertex buffer by applying transformation from the bones.
  33146. * Returns the Mesh.
  33147. *
  33148. * @param {skeleton} skeleton to apply
  33149. */
  33150. Mesh.prototype.applySkeleton = function (skeleton) {
  33151. if (!this.geometry) {
  33152. return this;
  33153. }
  33154. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33155. return this;
  33156. }
  33157. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33158. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33159. return this;
  33160. }
  33161. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33162. return this;
  33163. }
  33164. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33165. return this;
  33166. }
  33167. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33168. return this;
  33169. }
  33170. if (!this._sourcePositions) {
  33171. var submeshes = this.subMeshes.slice();
  33172. this.setPositionsForCPUSkinning();
  33173. this.subMeshes = submeshes;
  33174. }
  33175. if (!this._sourceNormals) {
  33176. this.setNormalsForCPUSkinning();
  33177. }
  33178. // positionsData checks for not being Float32Array will only pass at most once
  33179. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33180. if (!positionsData) {
  33181. return this;
  33182. }
  33183. if (!(positionsData instanceof Float32Array)) {
  33184. positionsData = new Float32Array(positionsData);
  33185. }
  33186. // normalsData checks for not being Float32Array will only pass at most once
  33187. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33188. if (!normalsData) {
  33189. return this;
  33190. }
  33191. if (!(normalsData instanceof Float32Array)) {
  33192. normalsData = new Float32Array(normalsData);
  33193. }
  33194. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33195. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33196. if (!matricesWeightsData || !matricesIndicesData) {
  33197. return this;
  33198. }
  33199. var needExtras = this.numBoneInfluencers > 4;
  33200. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33201. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33202. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33203. var tempVector3 = BABYLON.Vector3.Zero();
  33204. var finalMatrix = new BABYLON.Matrix();
  33205. var tempMatrix = new BABYLON.Matrix();
  33206. var matWeightIdx = 0;
  33207. var inf;
  33208. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33209. var weight;
  33210. for (inf = 0; inf < 4; inf++) {
  33211. weight = matricesWeightsData[matWeightIdx + inf];
  33212. if (weight > 0) {
  33213. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33214. finalMatrix.addToSelf(tempMatrix);
  33215. }
  33216. else
  33217. break;
  33218. }
  33219. if (needExtras) {
  33220. for (inf = 0; inf < 4; inf++) {
  33221. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33222. if (weight > 0) {
  33223. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33224. finalMatrix.addToSelf(tempMatrix);
  33225. }
  33226. else
  33227. break;
  33228. }
  33229. }
  33230. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33231. tempVector3.toArray(positionsData, index);
  33232. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33233. tempVector3.toArray(normalsData, index);
  33234. finalMatrix.reset();
  33235. }
  33236. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33237. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33238. return this;
  33239. };
  33240. // Tools
  33241. /**
  33242. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33243. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33244. */
  33245. Mesh.MinMax = function (meshes) {
  33246. var minVector = null;
  33247. var maxVector = null;
  33248. meshes.forEach(function (mesh, index, array) {
  33249. var boundingInfo = mesh.getBoundingInfo();
  33250. var boundingBox = boundingInfo.boundingBox;
  33251. if (!minVector || !maxVector) {
  33252. minVector = boundingBox.minimumWorld;
  33253. maxVector = boundingBox.maximumWorld;
  33254. }
  33255. else {
  33256. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33257. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33258. }
  33259. });
  33260. if (!minVector || !maxVector) {
  33261. return {
  33262. min: BABYLON.Vector3.Zero(),
  33263. max: BABYLON.Vector3.Zero()
  33264. };
  33265. }
  33266. return {
  33267. min: minVector,
  33268. max: maxVector
  33269. };
  33270. };
  33271. /**
  33272. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33273. */
  33274. Mesh.Center = function (meshesOrMinMaxVector) {
  33275. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33276. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33277. };
  33278. /**
  33279. * Merge the array of meshes into a single mesh for performance reasons.
  33280. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33281. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33282. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33283. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33284. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33285. */
  33286. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33287. if (disposeSource === void 0) { disposeSource = true; }
  33288. var index;
  33289. if (!allow32BitsIndices) {
  33290. var totalVertices = 0;
  33291. // Counting vertices
  33292. for (index = 0; index < meshes.length; index++) {
  33293. if (meshes[index]) {
  33294. totalVertices += meshes[index].getTotalVertices();
  33295. if (totalVertices > 65536) {
  33296. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33297. return null;
  33298. }
  33299. }
  33300. }
  33301. }
  33302. // Merge
  33303. var vertexData = null;
  33304. var otherVertexData;
  33305. var indiceArray = new Array();
  33306. var source = null;
  33307. for (index = 0; index < meshes.length; index++) {
  33308. if (meshes[index]) {
  33309. meshes[index].computeWorldMatrix(true);
  33310. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33311. otherVertexData.transform(meshes[index].getWorldMatrix());
  33312. if (vertexData) {
  33313. vertexData.merge(otherVertexData);
  33314. }
  33315. else {
  33316. vertexData = otherVertexData;
  33317. source = meshes[index];
  33318. }
  33319. if (subdivideWithSubMeshes) {
  33320. indiceArray.push(meshes[index].getTotalIndices());
  33321. }
  33322. }
  33323. }
  33324. source = source;
  33325. if (!meshSubclass) {
  33326. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33327. }
  33328. vertexData.applyToMesh(meshSubclass);
  33329. // Setting properties
  33330. meshSubclass.material = source.material;
  33331. meshSubclass.checkCollisions = source.checkCollisions;
  33332. // Cleaning
  33333. if (disposeSource) {
  33334. for (index = 0; index < meshes.length; index++) {
  33335. if (meshes[index]) {
  33336. meshes[index].dispose();
  33337. }
  33338. }
  33339. }
  33340. // Subdivide
  33341. if (subdivideWithSubMeshes) {
  33342. //-- Suppresions du submesh global
  33343. meshSubclass.releaseSubMeshes();
  33344. index = 0;
  33345. var offset = 0;
  33346. //-- aplique la subdivision en fonction du tableau d'indices
  33347. while (index < indiceArray.length) {
  33348. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33349. offset += indiceArray[index];
  33350. index++;
  33351. }
  33352. }
  33353. return meshSubclass;
  33354. };
  33355. // Consts
  33356. Mesh._FRONTSIDE = 0;
  33357. Mesh._BACKSIDE = 1;
  33358. Mesh._DOUBLESIDE = 2;
  33359. Mesh._DEFAULTSIDE = 0;
  33360. Mesh._NO_CAP = 0;
  33361. Mesh._CAP_START = 1;
  33362. Mesh._CAP_END = 2;
  33363. Mesh._CAP_ALL = 3;
  33364. return Mesh;
  33365. }(BABYLON.AbstractMesh));
  33366. BABYLON.Mesh = Mesh;
  33367. })(BABYLON || (BABYLON = {}));
  33368. //# sourceMappingURL=babylon.mesh.js.map
  33369. "use strict";
  33370. var BABYLON;
  33371. (function (BABYLON) {
  33372. var BaseSubMesh = /** @class */ (function () {
  33373. function BaseSubMesh() {
  33374. }
  33375. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33376. get: function () {
  33377. return this._materialEffect;
  33378. },
  33379. enumerable: true,
  33380. configurable: true
  33381. });
  33382. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33383. if (defines === void 0) { defines = null; }
  33384. if (this._materialEffect === effect) {
  33385. if (!effect) {
  33386. this._materialDefines = null;
  33387. }
  33388. return;
  33389. }
  33390. this._materialDefines = defines;
  33391. this._materialEffect = effect;
  33392. };
  33393. return BaseSubMesh;
  33394. }());
  33395. BABYLON.BaseSubMesh = BaseSubMesh;
  33396. var SubMesh = /** @class */ (function (_super) {
  33397. __extends(SubMesh, _super);
  33398. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33399. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33400. var _this = _super.call(this) || this;
  33401. _this.materialIndex = materialIndex;
  33402. _this.verticesStart = verticesStart;
  33403. _this.verticesCount = verticesCount;
  33404. _this.indexStart = indexStart;
  33405. _this.indexCount = indexCount;
  33406. _this._renderId = 0;
  33407. _this._mesh = mesh;
  33408. _this._renderingMesh = renderingMesh || mesh;
  33409. mesh.subMeshes.push(_this);
  33410. _this._trianglePlanes = [];
  33411. _this._id = mesh.subMeshes.length - 1;
  33412. if (createBoundingBox) {
  33413. _this.refreshBoundingInfo();
  33414. mesh.computeWorldMatrix(true);
  33415. }
  33416. return _this;
  33417. }
  33418. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33419. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33420. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33421. };
  33422. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33423. get: function () {
  33424. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33425. },
  33426. enumerable: true,
  33427. configurable: true
  33428. });
  33429. /**
  33430. * Returns the submesh BoudingInfo object.
  33431. */
  33432. SubMesh.prototype.getBoundingInfo = function () {
  33433. if (this.IsGlobal) {
  33434. return this._mesh.getBoundingInfo();
  33435. }
  33436. return this._boundingInfo;
  33437. };
  33438. /**
  33439. * Sets the submesh BoundingInfo.
  33440. * Return the SubMesh.
  33441. */
  33442. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33443. this._boundingInfo = boundingInfo;
  33444. return this;
  33445. };
  33446. /**
  33447. * Returns the mesh of the current submesh.
  33448. */
  33449. SubMesh.prototype.getMesh = function () {
  33450. return this._mesh;
  33451. };
  33452. /**
  33453. * Returns the rendering mesh of the submesh.
  33454. */
  33455. SubMesh.prototype.getRenderingMesh = function () {
  33456. return this._renderingMesh;
  33457. };
  33458. /**
  33459. * Returns the submesh material.
  33460. */
  33461. SubMesh.prototype.getMaterial = function () {
  33462. var rootMaterial = this._renderingMesh.material;
  33463. if (rootMaterial === null || rootMaterial === undefined) {
  33464. return this._mesh.getScene().defaultMaterial;
  33465. }
  33466. else if (rootMaterial.getSubMaterial) {
  33467. var multiMaterial = rootMaterial;
  33468. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33469. if (this._currentMaterial !== effectiveMaterial) {
  33470. this._currentMaterial = effectiveMaterial;
  33471. this._materialDefines = null;
  33472. }
  33473. return effectiveMaterial;
  33474. }
  33475. return rootMaterial;
  33476. };
  33477. // Methods
  33478. /**
  33479. * Sets a new updated BoundingInfo object to the submesh.
  33480. * Returns the SubMesh.
  33481. */
  33482. SubMesh.prototype.refreshBoundingInfo = function () {
  33483. this._lastColliderWorldVertices = null;
  33484. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33485. return this;
  33486. }
  33487. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33488. if (!data) {
  33489. this._boundingInfo = this._mesh.getBoundingInfo();
  33490. return this;
  33491. }
  33492. var indices = this._renderingMesh.getIndices();
  33493. var extend;
  33494. //is this the only submesh?
  33495. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33496. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33497. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33498. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33499. }
  33500. else {
  33501. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33502. }
  33503. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33504. return this;
  33505. };
  33506. SubMesh.prototype._checkCollision = function (collider) {
  33507. var boundingInfo = this.getBoundingInfo();
  33508. return boundingInfo._checkCollision(collider);
  33509. };
  33510. /**
  33511. * Updates the submesh BoundingInfo.
  33512. * Returns the Submesh.
  33513. */
  33514. SubMesh.prototype.updateBoundingInfo = function (world) {
  33515. var boundingInfo = this.getBoundingInfo();
  33516. if (!boundingInfo) {
  33517. this.refreshBoundingInfo();
  33518. boundingInfo = this.getBoundingInfo();
  33519. }
  33520. boundingInfo.update(world);
  33521. return this;
  33522. };
  33523. /**
  33524. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33525. * Boolean returned.
  33526. */
  33527. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33528. var boundingInfo = this.getBoundingInfo();
  33529. if (!boundingInfo) {
  33530. return false;
  33531. }
  33532. return boundingInfo.isInFrustum(frustumPlanes);
  33533. };
  33534. /**
  33535. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33536. * Boolean returned.
  33537. */
  33538. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33539. var boundingInfo = this.getBoundingInfo();
  33540. if (!boundingInfo) {
  33541. return false;
  33542. }
  33543. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33544. };
  33545. /**
  33546. * Renders the submesh.
  33547. * Returns it.
  33548. */
  33549. SubMesh.prototype.render = function (enableAlphaMode) {
  33550. this._renderingMesh.render(this, enableAlphaMode);
  33551. return this;
  33552. };
  33553. /**
  33554. * Returns a new Index Buffer.
  33555. * Type returned : WebGLBuffer.
  33556. */
  33557. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33558. if (!this._linesIndexBuffer) {
  33559. var linesIndices = [];
  33560. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33561. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  33562. }
  33563. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  33564. this.linesIndexCount = linesIndices.length;
  33565. }
  33566. return this._linesIndexBuffer;
  33567. };
  33568. /**
  33569. * True is the passed Ray intersects the submesh bounding box.
  33570. * Boolean returned.
  33571. */
  33572. SubMesh.prototype.canIntersects = function (ray) {
  33573. var boundingInfo = this.getBoundingInfo();
  33574. if (!boundingInfo) {
  33575. return false;
  33576. }
  33577. return ray.intersectsBox(boundingInfo.boundingBox);
  33578. };
  33579. /**
  33580. * Returns an object IntersectionInfo.
  33581. */
  33582. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  33583. var intersectInfo = null;
  33584. var material = this.getMaterial();
  33585. if (!material) {
  33586. return null;
  33587. }
  33588. switch (material.fillMode) {
  33589. case BABYLON.Material.PointListDrawMode:
  33590. case BABYLON.Material.LineListDrawMode:
  33591. case BABYLON.Material.LineLoopDrawMode:
  33592. case BABYLON.Material.LineStripDrawMode:
  33593. case BABYLON.Material.TriangleFanDrawMode:
  33594. case BABYLON.Material.TriangleStripDrawMode:
  33595. return null;
  33596. }
  33597. // LineMesh first as it's also a Mesh...
  33598. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  33599. var lineMesh = this._mesh;
  33600. // Line test
  33601. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  33602. var p0 = positions[indices[index]];
  33603. var p1 = positions[indices[index + 1]];
  33604. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  33605. if (length < 0) {
  33606. continue;
  33607. }
  33608. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  33609. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  33610. if (fastCheck) {
  33611. break;
  33612. }
  33613. }
  33614. }
  33615. }
  33616. else {
  33617. // Triangles test
  33618. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33619. var p0 = positions[indices[index]];
  33620. var p1 = positions[indices[index + 1]];
  33621. var p2 = positions[indices[index + 2]];
  33622. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  33623. if (currentIntersectInfo) {
  33624. if (currentIntersectInfo.distance < 0) {
  33625. continue;
  33626. }
  33627. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  33628. intersectInfo = currentIntersectInfo;
  33629. intersectInfo.faceId = index / 3;
  33630. if (fastCheck) {
  33631. break;
  33632. }
  33633. }
  33634. }
  33635. }
  33636. }
  33637. return intersectInfo;
  33638. };
  33639. SubMesh.prototype._rebuild = function () {
  33640. if (this._linesIndexBuffer) {
  33641. this._linesIndexBuffer = null;
  33642. }
  33643. };
  33644. // Clone
  33645. /**
  33646. * Creates a new Submesh from the passed Mesh.
  33647. */
  33648. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  33649. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  33650. if (!this.IsGlobal) {
  33651. var boundingInfo = this.getBoundingInfo();
  33652. if (!boundingInfo) {
  33653. return result;
  33654. }
  33655. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  33656. }
  33657. return result;
  33658. };
  33659. // Dispose
  33660. /**
  33661. * Disposes the Submesh.
  33662. * Returns nothing.
  33663. */
  33664. SubMesh.prototype.dispose = function () {
  33665. if (this._linesIndexBuffer) {
  33666. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  33667. this._linesIndexBuffer = null;
  33668. }
  33669. // Remove from mesh
  33670. var index = this._mesh.subMeshes.indexOf(this);
  33671. this._mesh.subMeshes.splice(index, 1);
  33672. };
  33673. // Statics
  33674. /**
  33675. * Creates a new Submesh from the passed parameters :
  33676. * - materialIndex (integer) : the index of the main mesh material.
  33677. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  33678. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  33679. * - mesh (Mesh) : the main mesh to create the submesh from.
  33680. * - renderingMesh (optional Mesh) : rendering mesh.
  33681. */
  33682. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  33683. var minVertexIndex = Number.MAX_VALUE;
  33684. var maxVertexIndex = -Number.MAX_VALUE;
  33685. renderingMesh = (renderingMesh || mesh);
  33686. var indices = renderingMesh.getIndices();
  33687. for (var index = startIndex; index < startIndex + indexCount; index++) {
  33688. var vertexIndex = indices[index];
  33689. if (vertexIndex < minVertexIndex)
  33690. minVertexIndex = vertexIndex;
  33691. if (vertexIndex > maxVertexIndex)
  33692. maxVertexIndex = vertexIndex;
  33693. }
  33694. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  33695. };
  33696. return SubMesh;
  33697. }(BaseSubMesh));
  33698. BABYLON.SubMesh = SubMesh;
  33699. })(BABYLON || (BABYLON = {}));
  33700. //# sourceMappingURL=babylon.subMesh.js.map
  33701. "use strict";
  33702. var __assign = (this && this.__assign) || Object.assign || function(t) {
  33703. for (var s, i = 1, n = arguments.length; i < n; i++) {
  33704. s = arguments[i];
  33705. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  33706. t[p] = s[p];
  33707. }
  33708. return t;
  33709. };
  33710. var BABYLON;
  33711. (function (BABYLON) {
  33712. /**
  33713. * Manages the defines for the Material
  33714. */
  33715. var MaterialDefines = /** @class */ (function () {
  33716. function MaterialDefines() {
  33717. this._isDirty = true;
  33718. /** @ignore */
  33719. this._areLightsDirty = true;
  33720. /** @ignore */
  33721. this._areAttributesDirty = true;
  33722. /** @ignore */
  33723. this._areTexturesDirty = true;
  33724. /** @ignore */
  33725. this._areFresnelDirty = true;
  33726. /** @ignore */
  33727. this._areMiscDirty = true;
  33728. /** @ignore */
  33729. this._areImageProcessingDirty = true;
  33730. /** @ignore */
  33731. this._normals = false;
  33732. /** @ignore */
  33733. this._uvs = false;
  33734. /** @ignore */
  33735. this._needNormals = false;
  33736. /** @ignore */
  33737. this._needUVs = false;
  33738. }
  33739. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  33740. /**
  33741. * Specifies if the material needs to be re-calculated
  33742. */
  33743. get: function () {
  33744. return this._isDirty;
  33745. },
  33746. enumerable: true,
  33747. configurable: true
  33748. });
  33749. /**
  33750. * Marks the material to indicate that it has been re-calculated
  33751. */
  33752. MaterialDefines.prototype.markAsProcessed = function () {
  33753. this._isDirty = false;
  33754. this._areAttributesDirty = false;
  33755. this._areTexturesDirty = false;
  33756. this._areFresnelDirty = false;
  33757. this._areLightsDirty = false;
  33758. this._areMiscDirty = false;
  33759. this._areImageProcessingDirty = false;
  33760. };
  33761. /**
  33762. * Marks the material to indicate that it needs to be re-calculated
  33763. */
  33764. MaterialDefines.prototype.markAsUnprocessed = function () {
  33765. this._isDirty = true;
  33766. };
  33767. /**
  33768. * Marks the material to indicate all of its defines need to be re-calculated
  33769. */
  33770. MaterialDefines.prototype.markAllAsDirty = function () {
  33771. this._areTexturesDirty = true;
  33772. this._areAttributesDirty = true;
  33773. this._areLightsDirty = true;
  33774. this._areFresnelDirty = true;
  33775. this._areMiscDirty = true;
  33776. this._areImageProcessingDirty = true;
  33777. this._isDirty = true;
  33778. };
  33779. /**
  33780. * Marks the material to indicate that image processing needs to be re-calculated
  33781. */
  33782. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  33783. this._areImageProcessingDirty = true;
  33784. this._isDirty = true;
  33785. };
  33786. /**
  33787. * Marks the material to indicate the lights need to be re-calculated
  33788. */
  33789. MaterialDefines.prototype.markAsLightDirty = function () {
  33790. this._areLightsDirty = true;
  33791. this._isDirty = true;
  33792. };
  33793. /**
  33794. * Marks the attribute state as changed
  33795. */
  33796. MaterialDefines.prototype.markAsAttributesDirty = function () {
  33797. this._areAttributesDirty = true;
  33798. this._isDirty = true;
  33799. };
  33800. /**
  33801. * Marks the texture state as changed
  33802. */
  33803. MaterialDefines.prototype.markAsTexturesDirty = function () {
  33804. this._areTexturesDirty = true;
  33805. this._isDirty = true;
  33806. };
  33807. /**
  33808. * Marks the fresnel state as changed
  33809. */
  33810. MaterialDefines.prototype.markAsFresnelDirty = function () {
  33811. this._areFresnelDirty = true;
  33812. this._isDirty = true;
  33813. };
  33814. /**
  33815. * Marks the misc state as changed
  33816. */
  33817. MaterialDefines.prototype.markAsMiscDirty = function () {
  33818. this._areMiscDirty = true;
  33819. this._isDirty = true;
  33820. };
  33821. /**
  33822. * Rebuilds the material defines
  33823. */
  33824. MaterialDefines.prototype.rebuild = function () {
  33825. if (this._keys) {
  33826. delete this._keys;
  33827. }
  33828. this._keys = [];
  33829. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  33830. var key = _a[_i];
  33831. if (key[0] === "_") {
  33832. continue;
  33833. }
  33834. this._keys.push(key);
  33835. }
  33836. };
  33837. /**
  33838. * Specifies if two material defines are equal
  33839. * @param other - A material define instance to compare to
  33840. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  33841. */
  33842. MaterialDefines.prototype.isEqual = function (other) {
  33843. if (this._keys.length !== other._keys.length) {
  33844. return false;
  33845. }
  33846. for (var index = 0; index < this._keys.length; index++) {
  33847. var prop = this._keys[index];
  33848. if (this[prop] !== other[prop]) {
  33849. return false;
  33850. }
  33851. }
  33852. return true;
  33853. };
  33854. /**
  33855. * Clones this instance's defines to another instance
  33856. * @param other - material defines to clone values to
  33857. */
  33858. MaterialDefines.prototype.cloneTo = function (other) {
  33859. if (this._keys.length !== other._keys.length) {
  33860. other._keys = this._keys.slice(0);
  33861. }
  33862. for (var index = 0; index < this._keys.length; index++) {
  33863. var prop = this._keys[index];
  33864. other[prop] = this[prop];
  33865. }
  33866. };
  33867. /**
  33868. * Resets the material define values
  33869. */
  33870. MaterialDefines.prototype.reset = function () {
  33871. for (var index = 0; index < this._keys.length; index++) {
  33872. var prop = this._keys[index];
  33873. var type = typeof this[prop];
  33874. switch (type) {
  33875. case "number":
  33876. this[prop] = 0;
  33877. break;
  33878. case "string":
  33879. this[prop] = "";
  33880. break;
  33881. default:
  33882. this[prop] = false;
  33883. break;
  33884. }
  33885. }
  33886. };
  33887. /**
  33888. * Converts the material define values to a string
  33889. * @returns - String of material define information
  33890. */
  33891. MaterialDefines.prototype.toString = function () {
  33892. var result = "";
  33893. for (var index = 0; index < this._keys.length; index++) {
  33894. var prop = this._keys[index];
  33895. var value = this[prop];
  33896. var type = typeof value;
  33897. switch (type) {
  33898. case "number":
  33899. case "string":
  33900. result += "#define " + prop + " " + value + "\n";
  33901. break;
  33902. default:
  33903. if (value) {
  33904. result += "#define " + prop + "\n";
  33905. }
  33906. break;
  33907. }
  33908. }
  33909. return result;
  33910. };
  33911. return MaterialDefines;
  33912. }());
  33913. BABYLON.MaterialDefines = MaterialDefines;
  33914. /**
  33915. * Base class for the main features of a material in Babylon.js
  33916. */
  33917. var Material = /** @class */ (function () {
  33918. /**
  33919. * Creates a material instance
  33920. * @param name defines the name of the material
  33921. * @param scene defines the scene to reference
  33922. * @param doNotAdd specifies if the material should be added to the scene
  33923. */
  33924. function Material(name, scene, doNotAdd) {
  33925. /**
  33926. * Specifies if the ready state should be checked on each call
  33927. */
  33928. this.checkReadyOnEveryCall = false;
  33929. /**
  33930. * Specifies if the ready state should be checked once
  33931. */
  33932. this.checkReadyOnlyOnce = false;
  33933. /**
  33934. * The state of the material
  33935. */
  33936. this.state = "";
  33937. /**
  33938. * The alpha value of the material
  33939. */
  33940. this._alpha = 1.0;
  33941. /**
  33942. * Specifies if back face culling is enabled
  33943. */
  33944. this._backFaceCulling = true;
  33945. /**
  33946. * Specifies if the material should be serialized
  33947. */
  33948. this.doNotSerialize = false;
  33949. /**
  33950. * Specifies if the effect should be stored on sub meshes
  33951. */
  33952. this.storeEffectOnSubMeshes = false;
  33953. /**
  33954. * An event triggered when the material is disposed
  33955. */
  33956. this.onDisposeObservable = new BABYLON.Observable();
  33957. /**
  33958. * An event triggered when the material is bound
  33959. */
  33960. this.onBindObservable = new BABYLON.Observable();
  33961. /**
  33962. * An event triggered when the material is unbound
  33963. */
  33964. this.onUnBindObservable = new BABYLON.Observable();
  33965. /**
  33966. * Stores the value of the alpha mode
  33967. */
  33968. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  33969. /**
  33970. * Stores the state of the need depth pre-pass value
  33971. */
  33972. this._needDepthPrePass = false;
  33973. /**
  33974. * Specifies if depth writing should be disabled
  33975. */
  33976. this.disableDepthWrite = false;
  33977. /**
  33978. * Specifies if depth writing should be forced
  33979. */
  33980. this.forceDepthWrite = false;
  33981. /**
  33982. * Specifies if there should be a separate pass for culling
  33983. */
  33984. this.separateCullingPass = false;
  33985. /**
  33986. * Stores the state specifing if fog should be enabled
  33987. */
  33988. this._fogEnabled = true;
  33989. /**
  33990. * Stores the size of points
  33991. */
  33992. this.pointSize = 1.0;
  33993. /**
  33994. * Stores the z offset value
  33995. */
  33996. this.zOffset = 0;
  33997. /**
  33998. * Specifies if the material was previously ready
  33999. */
  34000. this._wasPreviouslyReady = false;
  34001. /**
  34002. * Stores the fill mode state
  34003. */
  34004. this._fillMode = Material.TriangleFillMode;
  34005. this.name = name;
  34006. this.id = name || BABYLON.Tools.RandomId();
  34007. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34008. if (this._scene.useRightHandedSystem) {
  34009. this.sideOrientation = Material.ClockWiseSideOrientation;
  34010. }
  34011. else {
  34012. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34013. }
  34014. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34015. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34016. if (!doNotAdd) {
  34017. this._scene.materials.push(this);
  34018. }
  34019. }
  34020. Object.defineProperty(Material, "TriangleFillMode", {
  34021. /**
  34022. * Returns the triangle fill mode
  34023. */
  34024. get: function () {
  34025. return Material._TriangleFillMode;
  34026. },
  34027. enumerable: true,
  34028. configurable: true
  34029. });
  34030. Object.defineProperty(Material, "WireFrameFillMode", {
  34031. /**
  34032. * Returns the wireframe mode
  34033. */
  34034. get: function () {
  34035. return Material._WireFrameFillMode;
  34036. },
  34037. enumerable: true,
  34038. configurable: true
  34039. });
  34040. Object.defineProperty(Material, "PointFillMode", {
  34041. /**
  34042. * Returns the point fill mode
  34043. */
  34044. get: function () {
  34045. return Material._PointFillMode;
  34046. },
  34047. enumerable: true,
  34048. configurable: true
  34049. });
  34050. Object.defineProperty(Material, "PointListDrawMode", {
  34051. /**
  34052. * Returns the point list draw mode
  34053. */
  34054. get: function () {
  34055. return Material._PointListDrawMode;
  34056. },
  34057. enumerable: true,
  34058. configurable: true
  34059. });
  34060. Object.defineProperty(Material, "LineListDrawMode", {
  34061. /**
  34062. * Returns the line list draw mode
  34063. */
  34064. get: function () {
  34065. return Material._LineListDrawMode;
  34066. },
  34067. enumerable: true,
  34068. configurable: true
  34069. });
  34070. Object.defineProperty(Material, "LineLoopDrawMode", {
  34071. /**
  34072. * Returns the line loop draw mode
  34073. */
  34074. get: function () {
  34075. return Material._LineLoopDrawMode;
  34076. },
  34077. enumerable: true,
  34078. configurable: true
  34079. });
  34080. Object.defineProperty(Material, "LineStripDrawMode", {
  34081. /**
  34082. * Returns the line strip draw mode
  34083. */
  34084. get: function () {
  34085. return Material._LineStripDrawMode;
  34086. },
  34087. enumerable: true,
  34088. configurable: true
  34089. });
  34090. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34091. /**
  34092. * Returns the triangle strip draw mode
  34093. */
  34094. get: function () {
  34095. return Material._TriangleStripDrawMode;
  34096. },
  34097. enumerable: true,
  34098. configurable: true
  34099. });
  34100. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34101. /**
  34102. * Returns the triangle fan draw mode
  34103. */
  34104. get: function () {
  34105. return Material._TriangleFanDrawMode;
  34106. },
  34107. enumerable: true,
  34108. configurable: true
  34109. });
  34110. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34111. /**
  34112. * Returns the clock-wise side orientation
  34113. */
  34114. get: function () {
  34115. return Material._ClockWiseSideOrientation;
  34116. },
  34117. enumerable: true,
  34118. configurable: true
  34119. });
  34120. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34121. /**
  34122. * Returns the counter clock-wise side orientation
  34123. */
  34124. get: function () {
  34125. return Material._CounterClockWiseSideOrientation;
  34126. },
  34127. enumerable: true,
  34128. configurable: true
  34129. });
  34130. Object.defineProperty(Material, "TextureDirtyFlag", {
  34131. /**
  34132. * Returns the dirty texture flag value
  34133. */
  34134. get: function () {
  34135. return Material._TextureDirtyFlag;
  34136. },
  34137. enumerable: true,
  34138. configurable: true
  34139. });
  34140. Object.defineProperty(Material, "LightDirtyFlag", {
  34141. /**
  34142. * Returns the dirty light flag value
  34143. */
  34144. get: function () {
  34145. return Material._LightDirtyFlag;
  34146. },
  34147. enumerable: true,
  34148. configurable: true
  34149. });
  34150. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34151. /**
  34152. * Returns the dirty fresnel flag value
  34153. */
  34154. get: function () {
  34155. return Material._FresnelDirtyFlag;
  34156. },
  34157. enumerable: true,
  34158. configurable: true
  34159. });
  34160. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34161. /**
  34162. * Returns the dirty attributes flag value
  34163. */
  34164. get: function () {
  34165. return Material._AttributesDirtyFlag;
  34166. },
  34167. enumerable: true,
  34168. configurable: true
  34169. });
  34170. Object.defineProperty(Material, "MiscDirtyFlag", {
  34171. /**
  34172. * Returns the dirty misc flag value
  34173. */
  34174. get: function () {
  34175. return Material._MiscDirtyFlag;
  34176. },
  34177. enumerable: true,
  34178. configurable: true
  34179. });
  34180. Object.defineProperty(Material.prototype, "alpha", {
  34181. /**
  34182. * Gets the alpha value of the material
  34183. */
  34184. get: function () {
  34185. return this._alpha;
  34186. },
  34187. /**
  34188. * Sets the alpha value of the material
  34189. */
  34190. set: function (value) {
  34191. if (this._alpha === value) {
  34192. return;
  34193. }
  34194. this._alpha = value;
  34195. this.markAsDirty(Material.MiscDirtyFlag);
  34196. },
  34197. enumerable: true,
  34198. configurable: true
  34199. });
  34200. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34201. /**
  34202. * Gets the back-face culling state
  34203. */
  34204. get: function () {
  34205. return this._backFaceCulling;
  34206. },
  34207. /**
  34208. * Sets the back-face culling state
  34209. */
  34210. set: function (value) {
  34211. if (this._backFaceCulling === value) {
  34212. return;
  34213. }
  34214. this._backFaceCulling = value;
  34215. this.markAsDirty(Material.TextureDirtyFlag);
  34216. },
  34217. enumerable: true,
  34218. configurable: true
  34219. });
  34220. Object.defineProperty(Material.prototype, "onDispose", {
  34221. /**
  34222. * Called during a dispose event
  34223. */
  34224. set: function (callback) {
  34225. if (this._onDisposeObserver) {
  34226. this.onDisposeObservable.remove(this._onDisposeObserver);
  34227. }
  34228. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34229. },
  34230. enumerable: true,
  34231. configurable: true
  34232. });
  34233. Object.defineProperty(Material.prototype, "onBind", {
  34234. /**
  34235. * Called during a bind event
  34236. */
  34237. set: function (callback) {
  34238. if (this._onBindObserver) {
  34239. this.onBindObservable.remove(this._onBindObserver);
  34240. }
  34241. this._onBindObserver = this.onBindObservable.add(callback);
  34242. },
  34243. enumerable: true,
  34244. configurable: true
  34245. });
  34246. Object.defineProperty(Material.prototype, "alphaMode", {
  34247. /**
  34248. * Gets the value of the alpha mode
  34249. */
  34250. get: function () {
  34251. return this._alphaMode;
  34252. },
  34253. /**
  34254. * Sets the value of the alpha mode.
  34255. *
  34256. * | Value | Type | Description |
  34257. * | --- | --- | --- |
  34258. * | 0 | ALPHA_DISABLE | |
  34259. * | 1 | ALPHA_ADD | |
  34260. * | 2 | ALPHA_COMBINE | |
  34261. * | 3 | ALPHA_SUBTRACT | |
  34262. * | 4 | ALPHA_MULTIPLY | |
  34263. * | 5 | ALPHA_MAXIMIZED | |
  34264. * | 6 | ALPHA_ONEONE | |
  34265. * | 7 | ALPHA_PREMULTIPLIED | |
  34266. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34267. * | 9 | ALPHA_INTERPOLATE | |
  34268. * | 10 | ALPHA_SCREENMODE | |
  34269. *
  34270. */
  34271. set: function (value) {
  34272. if (this._alphaMode === value) {
  34273. return;
  34274. }
  34275. this._alphaMode = value;
  34276. this.markAsDirty(Material.TextureDirtyFlag);
  34277. },
  34278. enumerable: true,
  34279. configurable: true
  34280. });
  34281. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34282. /**
  34283. * Gets the depth pre-pass value
  34284. */
  34285. get: function () {
  34286. return this._needDepthPrePass;
  34287. },
  34288. /**
  34289. * Sets the need depth pre-pass value
  34290. */
  34291. set: function (value) {
  34292. if (this._needDepthPrePass === value) {
  34293. return;
  34294. }
  34295. this._needDepthPrePass = value;
  34296. if (this._needDepthPrePass) {
  34297. this.checkReadyOnEveryCall = true;
  34298. }
  34299. },
  34300. enumerable: true,
  34301. configurable: true
  34302. });
  34303. Object.defineProperty(Material.prototype, "fogEnabled", {
  34304. /**
  34305. * Gets the value of the fog enabled state
  34306. */
  34307. get: function () {
  34308. return this._fogEnabled;
  34309. },
  34310. /**
  34311. * Sets the state for enabling fog
  34312. */
  34313. set: function (value) {
  34314. if (this._fogEnabled === value) {
  34315. return;
  34316. }
  34317. this._fogEnabled = value;
  34318. this.markAsDirty(Material.MiscDirtyFlag);
  34319. },
  34320. enumerable: true,
  34321. configurable: true
  34322. });
  34323. Object.defineProperty(Material.prototype, "wireframe", {
  34324. /**
  34325. * Gets a value specifying if wireframe mode is enabled
  34326. */
  34327. get: function () {
  34328. switch (this._fillMode) {
  34329. case Material.WireFrameFillMode:
  34330. case Material.LineListDrawMode:
  34331. case Material.LineLoopDrawMode:
  34332. case Material.LineStripDrawMode:
  34333. return true;
  34334. }
  34335. return this._scene.forceWireframe;
  34336. },
  34337. /**
  34338. * Sets the state of wireframe mode
  34339. */
  34340. set: function (value) {
  34341. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34342. },
  34343. enumerable: true,
  34344. configurable: true
  34345. });
  34346. Object.defineProperty(Material.prototype, "pointsCloud", {
  34347. /**
  34348. * Gets the value specifying if point clouds are enabled
  34349. */
  34350. get: function () {
  34351. switch (this._fillMode) {
  34352. case Material.PointFillMode:
  34353. case Material.PointListDrawMode:
  34354. return true;
  34355. }
  34356. return this._scene.forcePointsCloud;
  34357. },
  34358. /**
  34359. * Sets the state of point cloud mode
  34360. */
  34361. set: function (value) {
  34362. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34363. },
  34364. enumerable: true,
  34365. configurable: true
  34366. });
  34367. Object.defineProperty(Material.prototype, "fillMode", {
  34368. /**
  34369. * Gets the material fill mode
  34370. */
  34371. get: function () {
  34372. return this._fillMode;
  34373. },
  34374. /**
  34375. * Sets the material fill mode
  34376. */
  34377. set: function (value) {
  34378. if (this._fillMode === value) {
  34379. return;
  34380. }
  34381. this._fillMode = value;
  34382. this.markAsDirty(Material.MiscDirtyFlag);
  34383. },
  34384. enumerable: true,
  34385. configurable: true
  34386. });
  34387. /**
  34388. * Returns a string representation of the current material
  34389. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34390. * @returns a string with material information
  34391. */
  34392. Material.prototype.toString = function (fullDetails) {
  34393. var ret = "Name: " + this.name;
  34394. if (fullDetails) {
  34395. }
  34396. return ret;
  34397. };
  34398. /**
  34399. * Gets the class name of the material
  34400. * @returns a string with the class name of the material
  34401. */
  34402. Material.prototype.getClassName = function () {
  34403. return "Material";
  34404. };
  34405. Object.defineProperty(Material.prototype, "isFrozen", {
  34406. /**
  34407. * Specifies if updates for the material been locked
  34408. */
  34409. get: function () {
  34410. return this.checkReadyOnlyOnce;
  34411. },
  34412. enumerable: true,
  34413. configurable: true
  34414. });
  34415. /**
  34416. * Locks updates for the material
  34417. */
  34418. Material.prototype.freeze = function () {
  34419. this.checkReadyOnlyOnce = true;
  34420. };
  34421. /**
  34422. * Unlocks updates for the material
  34423. */
  34424. Material.prototype.unfreeze = function () {
  34425. this.checkReadyOnlyOnce = false;
  34426. };
  34427. /**
  34428. * Specifies if the material is ready to be used
  34429. * @param mesh defines the mesh to check
  34430. * @param useInstances specifies if instances should be used
  34431. * @returns a boolean indicating if the material is ready to be used
  34432. */
  34433. Material.prototype.isReady = function (mesh, useInstances) {
  34434. return true;
  34435. };
  34436. /**
  34437. * Specifies that the submesh is ready to be used
  34438. * @param mesh defines the mesh to check
  34439. * @param subMesh defines which submesh to check
  34440. * @param useInstances specifies that instances should be used
  34441. * @returns a boolean indicating that the submesh is ready or not
  34442. */
  34443. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34444. return false;
  34445. };
  34446. /**
  34447. * Returns the material effect
  34448. * @returns the effect associated with the material
  34449. */
  34450. Material.prototype.getEffect = function () {
  34451. return this._effect;
  34452. };
  34453. /**
  34454. * Returns the current scene
  34455. * @returns a Scene
  34456. */
  34457. Material.prototype.getScene = function () {
  34458. return this._scene;
  34459. };
  34460. /**
  34461. * Specifies if the material will require alpha blending
  34462. * @returns a boolean specifying if alpha blending is needed
  34463. */
  34464. Material.prototype.needAlphaBlending = function () {
  34465. return (this.alpha < 1.0);
  34466. };
  34467. /**
  34468. * Specifies if the mesh will require alpha blending
  34469. * @param mesh defines the mesh to check
  34470. * @returns a boolean specifying if alpha blending is needed for the mesh
  34471. */
  34472. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34473. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34474. };
  34475. /**
  34476. * Specifies if this material should be rendered in alpha test mode
  34477. * @returns a boolean specifying if an alpha test is needed.
  34478. */
  34479. Material.prototype.needAlphaTesting = function () {
  34480. return false;
  34481. };
  34482. /**
  34483. * Gets the texture used for the alpha test
  34484. * @returns the texture to use for alpha testing
  34485. */
  34486. Material.prototype.getAlphaTestTexture = function () {
  34487. return null;
  34488. };
  34489. /**
  34490. * Marks the material to indicate that it needs to be re-calculated
  34491. */
  34492. Material.prototype.markDirty = function () {
  34493. this._wasPreviouslyReady = false;
  34494. };
  34495. /** @ignore */
  34496. Material.prototype._preBind = function (effect, overrideOrientation) {
  34497. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34498. var engine = this._scene.getEngine();
  34499. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34500. var reverse = orientation === Material.ClockWiseSideOrientation;
  34501. engine.enableEffect(effect ? effect : this._effect);
  34502. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34503. return reverse;
  34504. };
  34505. /**
  34506. * Binds the material to the mesh
  34507. * @param world defines the world transformation matrix
  34508. * @param mesh defines the mesh to bind the material to
  34509. */
  34510. Material.prototype.bind = function (world, mesh) {
  34511. };
  34512. /**
  34513. * Binds the submesh to the material
  34514. * @param world defines the world transformation matrix
  34515. * @param mesh defines the mesh containing the submesh
  34516. * @param subMesh defines the submesh to bind the material to
  34517. */
  34518. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34519. };
  34520. /**
  34521. * Binds the world matrix to the material
  34522. * @param world defines the world transformation matrix
  34523. */
  34524. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34525. };
  34526. /**
  34527. * Binds the scene's uniform buffer to the effect.
  34528. * @param effect defines the effect to bind to the scene uniform buffer
  34529. * @param sceneUbo defines the uniform buffer storing scene data
  34530. */
  34531. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34532. sceneUbo.bindToEffect(effect, "Scene");
  34533. };
  34534. /**
  34535. * Binds the view matrix to the effect
  34536. * @param effect defines the effect to bind the view matrix to
  34537. */
  34538. Material.prototype.bindView = function (effect) {
  34539. if (!this._useUBO) {
  34540. effect.setMatrix("view", this.getScene().getViewMatrix());
  34541. }
  34542. else {
  34543. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34544. }
  34545. };
  34546. /**
  34547. * Binds the view projection matrix to the effect
  34548. * @param effect defines the effect to bind the view projection matrix to
  34549. */
  34550. Material.prototype.bindViewProjection = function (effect) {
  34551. if (!this._useUBO) {
  34552. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34553. }
  34554. else {
  34555. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34556. }
  34557. };
  34558. /**
  34559. * Specifies if material alpha testing should be turned on for the mesh
  34560. * @param mesh defines the mesh to check
  34561. */
  34562. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  34563. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  34564. };
  34565. /**
  34566. * Processes to execute after binding the material to a mesh
  34567. * @param mesh defines the rendered mesh
  34568. */
  34569. Material.prototype._afterBind = function (mesh) {
  34570. this._scene._cachedMaterial = this;
  34571. if (mesh) {
  34572. this._scene._cachedVisibility = mesh.visibility;
  34573. }
  34574. else {
  34575. this._scene._cachedVisibility = 1;
  34576. }
  34577. if (mesh) {
  34578. this.onBindObservable.notifyObservers(mesh);
  34579. }
  34580. if (this.disableDepthWrite) {
  34581. var engine = this._scene.getEngine();
  34582. this._cachedDepthWriteState = engine.getDepthWrite();
  34583. engine.setDepthWrite(false);
  34584. }
  34585. };
  34586. /**
  34587. * Unbinds the material from the mesh
  34588. */
  34589. Material.prototype.unbind = function () {
  34590. this.onUnBindObservable.notifyObservers(this);
  34591. if (this.disableDepthWrite) {
  34592. var engine = this._scene.getEngine();
  34593. engine.setDepthWrite(this._cachedDepthWriteState);
  34594. }
  34595. };
  34596. /**
  34597. * Gets the active textures from the material
  34598. * @returns an array of textures
  34599. */
  34600. Material.prototype.getActiveTextures = function () {
  34601. return [];
  34602. };
  34603. /**
  34604. * Specifies if the material uses a texture
  34605. * @param texture defines the texture to check against the material
  34606. * @returns a boolean specifying if the material uses the texture
  34607. */
  34608. Material.prototype.hasTexture = function (texture) {
  34609. return false;
  34610. };
  34611. /**
  34612. * Makes a duplicate of the material, and gives it a new name
  34613. * @param name defines the new name for the duplicated material
  34614. * @returns the cloned material
  34615. */
  34616. Material.prototype.clone = function (name) {
  34617. return null;
  34618. };
  34619. /**
  34620. * Gets the meshes bound to the material
  34621. * @returns an array of meshes bound to the material
  34622. */
  34623. Material.prototype.getBindedMeshes = function () {
  34624. var result = new Array();
  34625. for (var index = 0; index < this._scene.meshes.length; index++) {
  34626. var mesh = this._scene.meshes[index];
  34627. if (mesh.material === this) {
  34628. result.push(mesh);
  34629. }
  34630. }
  34631. return result;
  34632. };
  34633. /**
  34634. * Force shader compilation
  34635. * @param mesh defines the mesh associated with this material
  34636. * @param onCompiled defines a function to execute once the material is compiled
  34637. * @param options defines the options to configure the compilation
  34638. */
  34639. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  34640. var _this = this;
  34641. var localOptions = __assign({ clipPlane: false }, options);
  34642. var subMesh = new BABYLON.BaseSubMesh();
  34643. var scene = this.getScene();
  34644. var checkReady = function () {
  34645. if (!_this._scene || !_this._scene.getEngine()) {
  34646. return;
  34647. }
  34648. if (subMesh._materialDefines) {
  34649. subMesh._materialDefines._renderId = -1;
  34650. }
  34651. var clipPlaneState = scene.clipPlane;
  34652. if (localOptions.clipPlane) {
  34653. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  34654. }
  34655. if (_this.storeEffectOnSubMeshes) {
  34656. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  34657. if (onCompiled) {
  34658. onCompiled(_this);
  34659. }
  34660. }
  34661. else {
  34662. setTimeout(checkReady, 16);
  34663. }
  34664. }
  34665. else {
  34666. if (_this.isReady(mesh)) {
  34667. if (onCompiled) {
  34668. onCompiled(_this);
  34669. }
  34670. }
  34671. else {
  34672. setTimeout(checkReady, 16);
  34673. }
  34674. }
  34675. if (localOptions.clipPlane) {
  34676. scene.clipPlane = clipPlaneState;
  34677. }
  34678. };
  34679. checkReady();
  34680. };
  34681. /**
  34682. * Force shader compilation
  34683. * @param mesh defines the mesh that will use this material
  34684. * @param options defines additional options for compiling the shaders
  34685. * @returns a promise that resolves when the compilation completes
  34686. */
  34687. Material.prototype.forceCompilationAsync = function (mesh, options) {
  34688. var _this = this;
  34689. return new Promise(function (resolve) {
  34690. _this.forceCompilation(mesh, function () {
  34691. resolve();
  34692. }, options);
  34693. });
  34694. };
  34695. /**
  34696. * Marks a define in the material to indicate that it needs to be re-computed
  34697. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  34698. */
  34699. Material.prototype.markAsDirty = function (flag) {
  34700. if (flag & Material.TextureDirtyFlag) {
  34701. this._markAllSubMeshesAsTexturesDirty();
  34702. }
  34703. if (flag & Material.LightDirtyFlag) {
  34704. this._markAllSubMeshesAsLightsDirty();
  34705. }
  34706. if (flag & Material.FresnelDirtyFlag) {
  34707. this._markAllSubMeshesAsFresnelDirty();
  34708. }
  34709. if (flag & Material.AttributesDirtyFlag) {
  34710. this._markAllSubMeshesAsAttributesDirty();
  34711. }
  34712. if (flag & Material.MiscDirtyFlag) {
  34713. this._markAllSubMeshesAsMiscDirty();
  34714. }
  34715. this.getScene().resetCachedMaterial();
  34716. };
  34717. /**
  34718. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  34719. * @param func defines a function which checks material defines against the submeshes
  34720. */
  34721. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  34722. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  34723. var mesh = _a[_i];
  34724. if (!mesh.subMeshes) {
  34725. continue;
  34726. }
  34727. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  34728. var subMesh = _c[_b];
  34729. if (subMesh.getMaterial() !== this) {
  34730. continue;
  34731. }
  34732. if (!subMesh._materialDefines) {
  34733. continue;
  34734. }
  34735. func(subMesh._materialDefines);
  34736. }
  34737. }
  34738. };
  34739. /**
  34740. * Indicates that image processing needs to be re-calculated for all submeshes
  34741. */
  34742. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  34743. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  34744. };
  34745. /**
  34746. * Indicates that textures need to be re-calculated for all submeshes
  34747. */
  34748. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  34749. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  34750. };
  34751. /**
  34752. * Indicates that fresnel needs to be re-calculated for all submeshes
  34753. */
  34754. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  34755. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  34756. };
  34757. /**
  34758. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  34759. */
  34760. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  34761. this._markAllSubMeshesAsDirty(function (defines) {
  34762. defines.markAsFresnelDirty();
  34763. defines.markAsMiscDirty();
  34764. });
  34765. };
  34766. /**
  34767. * Indicates that lights need to be re-calculated for all submeshes
  34768. */
  34769. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  34770. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  34771. };
  34772. /**
  34773. * Indicates that attributes need to be re-calculated for all submeshes
  34774. */
  34775. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  34776. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  34777. };
  34778. /**
  34779. * Indicates that misc needs to be re-calculated for all submeshes
  34780. */
  34781. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  34782. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  34783. };
  34784. /**
  34785. * Indicates that textures and misc need to be re-calculated for all submeshes
  34786. */
  34787. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  34788. this._markAllSubMeshesAsDirty(function (defines) {
  34789. defines.markAsTexturesDirty();
  34790. defines.markAsMiscDirty();
  34791. });
  34792. };
  34793. /**
  34794. * Disposes the material
  34795. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  34796. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  34797. */
  34798. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34799. // Animations
  34800. this.getScene().stopAnimation(this);
  34801. this.getScene().freeProcessedMaterials();
  34802. // Remove from scene
  34803. var index = this._scene.materials.indexOf(this);
  34804. if (index >= 0) {
  34805. this._scene.materials.splice(index, 1);
  34806. }
  34807. // Remove from meshes
  34808. for (index = 0; index < this._scene.meshes.length; index++) {
  34809. var mesh = this._scene.meshes[index];
  34810. if (mesh.material === this) {
  34811. mesh.material = null;
  34812. if (mesh.geometry) {
  34813. var geometry = (mesh.geometry);
  34814. if (this.storeEffectOnSubMeshes) {
  34815. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  34816. var subMesh = _a[_i];
  34817. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  34818. if (forceDisposeEffect && subMesh._materialEffect) {
  34819. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  34820. }
  34821. }
  34822. }
  34823. else {
  34824. geometry._releaseVertexArrayObject(this._effect);
  34825. }
  34826. }
  34827. }
  34828. }
  34829. this._uniformBuffer.dispose();
  34830. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  34831. if (forceDisposeEffect && this._effect) {
  34832. if (!this.storeEffectOnSubMeshes) {
  34833. this._scene.getEngine()._releaseEffect(this._effect);
  34834. }
  34835. this._effect = null;
  34836. }
  34837. // Callback
  34838. this.onDisposeObservable.notifyObservers(this);
  34839. this.onDisposeObservable.clear();
  34840. this.onBindObservable.clear();
  34841. this.onUnBindObservable.clear();
  34842. };
  34843. /**
  34844. * Serializes this material
  34845. * @returns the serialized material object
  34846. */
  34847. Material.prototype.serialize = function () {
  34848. return BABYLON.SerializationHelper.Serialize(this);
  34849. };
  34850. /**
  34851. * Creates a MultiMaterial from parsed MultiMaterial data.
  34852. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  34853. * @param scene defines the hosting scene
  34854. * @returns a new MultiMaterial
  34855. */
  34856. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  34857. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  34858. multiMaterial.id = parsedMultiMaterial.id;
  34859. if (BABYLON.Tags) {
  34860. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  34861. }
  34862. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  34863. var subMatId = parsedMultiMaterial.materials[matIndex];
  34864. if (subMatId) {
  34865. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  34866. }
  34867. else {
  34868. multiMaterial.subMaterials.push(null);
  34869. }
  34870. }
  34871. return multiMaterial;
  34872. };
  34873. /**
  34874. * Creates a material from parsed material data
  34875. * @param parsedMaterial defines parsed material data
  34876. * @param scene defines the hosting scene
  34877. * @param rootUrl defines the root URL to use to load textures
  34878. * @returns a new material
  34879. */
  34880. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  34881. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  34882. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  34883. }
  34884. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  34885. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  34886. if (!BABYLON.LegacyPBRMaterial) {
  34887. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  34888. return;
  34889. }
  34890. }
  34891. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  34892. return materialType.Parse(parsedMaterial, scene, rootUrl);
  34893. ;
  34894. };
  34895. // Triangle views
  34896. Material._TriangleFillMode = 0;
  34897. Material._WireFrameFillMode = 1;
  34898. Material._PointFillMode = 2;
  34899. // Draw modes
  34900. Material._PointListDrawMode = 3;
  34901. Material._LineListDrawMode = 4;
  34902. Material._LineLoopDrawMode = 5;
  34903. Material._LineStripDrawMode = 6;
  34904. Material._TriangleStripDrawMode = 7;
  34905. Material._TriangleFanDrawMode = 8;
  34906. /**
  34907. * Stores the clock-wise side orientation
  34908. */
  34909. Material._ClockWiseSideOrientation = 0;
  34910. /**
  34911. * Stores the counter clock-wise side orientation
  34912. */
  34913. Material._CounterClockWiseSideOrientation = 1;
  34914. /**
  34915. * The dirty texture flag value
  34916. */
  34917. Material._TextureDirtyFlag = 1;
  34918. /**
  34919. * The dirty light flag value
  34920. */
  34921. Material._LightDirtyFlag = 2;
  34922. /**
  34923. * The dirty fresnel flag value
  34924. */
  34925. Material._FresnelDirtyFlag = 4;
  34926. /**
  34927. * The dirty attribute flag value
  34928. */
  34929. Material._AttributesDirtyFlag = 8;
  34930. /**
  34931. * The dirty misc flag value
  34932. */
  34933. Material._MiscDirtyFlag = 16;
  34934. __decorate([
  34935. BABYLON.serialize()
  34936. ], Material.prototype, "id", void 0);
  34937. __decorate([
  34938. BABYLON.serialize()
  34939. ], Material.prototype, "name", void 0);
  34940. __decorate([
  34941. BABYLON.serialize()
  34942. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  34943. __decorate([
  34944. BABYLON.serialize()
  34945. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  34946. __decorate([
  34947. BABYLON.serialize()
  34948. ], Material.prototype, "state", void 0);
  34949. __decorate([
  34950. BABYLON.serialize("alpha")
  34951. ], Material.prototype, "_alpha", void 0);
  34952. __decorate([
  34953. BABYLON.serialize("backFaceCulling")
  34954. ], Material.prototype, "_backFaceCulling", void 0);
  34955. __decorate([
  34956. BABYLON.serialize()
  34957. ], Material.prototype, "sideOrientation", void 0);
  34958. __decorate([
  34959. BABYLON.serialize("alphaMode")
  34960. ], Material.prototype, "_alphaMode", void 0);
  34961. __decorate([
  34962. BABYLON.serialize()
  34963. ], Material.prototype, "_needDepthPrePass", void 0);
  34964. __decorate([
  34965. BABYLON.serialize()
  34966. ], Material.prototype, "disableDepthWrite", void 0);
  34967. __decorate([
  34968. BABYLON.serialize()
  34969. ], Material.prototype, "forceDepthWrite", void 0);
  34970. __decorate([
  34971. BABYLON.serialize()
  34972. ], Material.prototype, "separateCullingPass", void 0);
  34973. __decorate([
  34974. BABYLON.serialize("fogEnabled")
  34975. ], Material.prototype, "_fogEnabled", void 0);
  34976. __decorate([
  34977. BABYLON.serialize()
  34978. ], Material.prototype, "pointSize", void 0);
  34979. __decorate([
  34980. BABYLON.serialize()
  34981. ], Material.prototype, "zOffset", void 0);
  34982. __decorate([
  34983. BABYLON.serialize()
  34984. ], Material.prototype, "wireframe", null);
  34985. __decorate([
  34986. BABYLON.serialize()
  34987. ], Material.prototype, "pointsCloud", null);
  34988. __decorate([
  34989. BABYLON.serialize()
  34990. ], Material.prototype, "fillMode", null);
  34991. return Material;
  34992. }());
  34993. BABYLON.Material = Material;
  34994. })(BABYLON || (BABYLON = {}));
  34995. //# sourceMappingURL=babylon.material.js.map
  34996. "use strict";
  34997. var BABYLON;
  34998. (function (BABYLON) {
  34999. var UniformBuffer = /** @class */ (function () {
  35000. /**
  35001. * Uniform buffer objects.
  35002. *
  35003. * Handles blocks of uniform on the GPU.
  35004. *
  35005. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35006. *
  35007. * For more information, please refer to :
  35008. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35009. */
  35010. function UniformBuffer(engine, data, dynamic) {
  35011. this._engine = engine;
  35012. this._noUBO = !engine.supportsUniformBuffers;
  35013. this._dynamic = dynamic;
  35014. this._data = data || [];
  35015. this._uniformLocations = {};
  35016. this._uniformSizes = {};
  35017. this._uniformLocationPointer = 0;
  35018. this._needSync = false;
  35019. if (this._noUBO) {
  35020. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35021. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35022. this.updateFloat = this._updateFloatForEffect;
  35023. this.updateFloat2 = this._updateFloat2ForEffect;
  35024. this.updateFloat3 = this._updateFloat3ForEffect;
  35025. this.updateFloat4 = this._updateFloat4ForEffect;
  35026. this.updateMatrix = this._updateMatrixForEffect;
  35027. this.updateVector3 = this._updateVector3ForEffect;
  35028. this.updateVector4 = this._updateVector4ForEffect;
  35029. this.updateColor3 = this._updateColor3ForEffect;
  35030. this.updateColor4 = this._updateColor4ForEffect;
  35031. }
  35032. else {
  35033. this._engine._uniformBuffers.push(this);
  35034. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35035. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35036. this.updateFloat = this._updateFloatForUniform;
  35037. this.updateFloat2 = this._updateFloat2ForUniform;
  35038. this.updateFloat3 = this._updateFloat3ForUniform;
  35039. this.updateFloat4 = this._updateFloat4ForUniform;
  35040. this.updateMatrix = this._updateMatrixForUniform;
  35041. this.updateVector3 = this._updateVector3ForUniform;
  35042. this.updateVector4 = this._updateVector4ForUniform;
  35043. this.updateColor3 = this._updateColor3ForUniform;
  35044. this.updateColor4 = this._updateColor4ForUniform;
  35045. }
  35046. }
  35047. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35048. // Properties
  35049. /**
  35050. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35051. * or just falling back on setUniformXXX calls.
  35052. */
  35053. get: function () {
  35054. return !this._noUBO;
  35055. },
  35056. enumerable: true,
  35057. configurable: true
  35058. });
  35059. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35060. /**
  35061. * Indicates if the WebGL underlying uniform buffer is in sync
  35062. * with the javascript cache data.
  35063. */
  35064. get: function () {
  35065. return !this._needSync;
  35066. },
  35067. enumerable: true,
  35068. configurable: true
  35069. });
  35070. /**
  35071. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35072. * Also, a dynamic UniformBuffer will disable cache verification and always
  35073. * update the underlying WebGL uniform buffer to the GPU.
  35074. */
  35075. UniformBuffer.prototype.isDynamic = function () {
  35076. return this._dynamic !== undefined;
  35077. };
  35078. /**
  35079. * The data cache on JS side.
  35080. */
  35081. UniformBuffer.prototype.getData = function () {
  35082. return this._bufferData;
  35083. };
  35084. /**
  35085. * The underlying WebGL Uniform buffer.
  35086. */
  35087. UniformBuffer.prototype.getBuffer = function () {
  35088. return this._buffer;
  35089. };
  35090. /**
  35091. * std140 layout specifies how to align data within an UBO structure.
  35092. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35093. * for specs.
  35094. */
  35095. UniformBuffer.prototype._fillAlignment = function (size) {
  35096. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35097. // and 4x4 matrices
  35098. // TODO : change if other types are used
  35099. var alignment;
  35100. if (size <= 2) {
  35101. alignment = size;
  35102. }
  35103. else {
  35104. alignment = 4;
  35105. }
  35106. if ((this._uniformLocationPointer % alignment) !== 0) {
  35107. var oldPointer = this._uniformLocationPointer;
  35108. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35109. var diff = this._uniformLocationPointer - oldPointer;
  35110. for (var i = 0; i < diff; i++) {
  35111. this._data.push(0);
  35112. }
  35113. }
  35114. };
  35115. /**
  35116. * Adds an uniform in the buffer.
  35117. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35118. * for the layout to be correct !
  35119. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35120. * @param {number|number[]} size Data size, or data directly.
  35121. */
  35122. UniformBuffer.prototype.addUniform = function (name, size) {
  35123. if (this._noUBO) {
  35124. return;
  35125. }
  35126. if (this._uniformLocations[name] !== undefined) {
  35127. // Already existing uniform
  35128. return;
  35129. }
  35130. // This function must be called in the order of the shader layout !
  35131. // size can be the size of the uniform, or data directly
  35132. var data;
  35133. if (size instanceof Array) {
  35134. data = size;
  35135. size = data.length;
  35136. }
  35137. else {
  35138. size = size;
  35139. data = [];
  35140. // Fill with zeros
  35141. for (var i = 0; i < size; i++) {
  35142. data.push(0);
  35143. }
  35144. }
  35145. this._fillAlignment(size);
  35146. this._uniformSizes[name] = size;
  35147. this._uniformLocations[name] = this._uniformLocationPointer;
  35148. this._uniformLocationPointer += size;
  35149. for (var i = 0; i < size; i++) {
  35150. this._data.push(data[i]);
  35151. }
  35152. this._needSync = true;
  35153. };
  35154. /**
  35155. * Wrapper for addUniform.
  35156. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35157. * @param {Matrix} mat A 4x4 matrix.
  35158. */
  35159. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35160. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35161. };
  35162. /**
  35163. * Wrapper for addUniform.
  35164. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35165. * @param {number} x
  35166. * @param {number} y
  35167. */
  35168. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35169. var temp = [x, y];
  35170. this.addUniform(name, temp);
  35171. };
  35172. /**
  35173. * Wrapper for addUniform.
  35174. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35175. * @param {number} x
  35176. * @param {number} y
  35177. * @param {number} z
  35178. */
  35179. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35180. var temp = [x, y, z];
  35181. this.addUniform(name, temp);
  35182. };
  35183. /**
  35184. * Wrapper for addUniform.
  35185. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35186. * @param {Color3} color
  35187. */
  35188. UniformBuffer.prototype.addColor3 = function (name, color) {
  35189. var temp = new Array();
  35190. color.toArray(temp);
  35191. this.addUniform(name, temp);
  35192. };
  35193. /**
  35194. * Wrapper for addUniform.
  35195. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35196. * @param {Color3} color
  35197. * @param {number} alpha
  35198. */
  35199. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35200. var temp = new Array();
  35201. color.toArray(temp);
  35202. temp.push(alpha);
  35203. this.addUniform(name, temp);
  35204. };
  35205. /**
  35206. * Wrapper for addUniform.
  35207. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35208. * @param {Vector3} vector
  35209. */
  35210. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35211. var temp = new Array();
  35212. vector.toArray(temp);
  35213. this.addUniform(name, temp);
  35214. };
  35215. /**
  35216. * Wrapper for addUniform.
  35217. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35218. */
  35219. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35220. this.addUniform(name, 12);
  35221. };
  35222. /**
  35223. * Wrapper for addUniform.
  35224. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35225. */
  35226. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35227. this.addUniform(name, 8);
  35228. };
  35229. /**
  35230. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35231. */
  35232. UniformBuffer.prototype.create = function () {
  35233. if (this._noUBO) {
  35234. return;
  35235. }
  35236. if (this._buffer) {
  35237. return; // nothing to do
  35238. }
  35239. // See spec, alignment must be filled as a vec4
  35240. this._fillAlignment(4);
  35241. this._bufferData = new Float32Array(this._data);
  35242. this._rebuild();
  35243. this._needSync = true;
  35244. };
  35245. UniformBuffer.prototype._rebuild = function () {
  35246. if (this._noUBO) {
  35247. return;
  35248. }
  35249. if (this._dynamic) {
  35250. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35251. }
  35252. else {
  35253. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35254. }
  35255. };
  35256. /**
  35257. * Updates the WebGL Uniform Buffer on the GPU.
  35258. * If the `dynamic` flag is set to true, no cache comparison is done.
  35259. * Otherwise, the buffer will be updated only if the cache differs.
  35260. */
  35261. UniformBuffer.prototype.update = function () {
  35262. if (!this._buffer) {
  35263. this.create();
  35264. return;
  35265. }
  35266. if (!this._dynamic && !this._needSync) {
  35267. return;
  35268. }
  35269. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35270. this._needSync = false;
  35271. };
  35272. /**
  35273. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35274. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35275. * @param {number[]|Float32Array} data Flattened data
  35276. * @param {number} size Size of the data.
  35277. */
  35278. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35279. var location = this._uniformLocations[uniformName];
  35280. if (location === undefined) {
  35281. if (this._buffer) {
  35282. // Cannot add an uniform if the buffer is already created
  35283. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35284. return;
  35285. }
  35286. this.addUniform(uniformName, size);
  35287. location = this._uniformLocations[uniformName];
  35288. }
  35289. if (!this._buffer) {
  35290. this.create();
  35291. }
  35292. if (!this._dynamic) {
  35293. // Cache for static uniform buffers
  35294. var changed = false;
  35295. for (var i = 0; i < size; i++) {
  35296. if (this._bufferData[location + i] !== data[i]) {
  35297. changed = true;
  35298. this._bufferData[location + i] = data[i];
  35299. }
  35300. }
  35301. this._needSync = this._needSync || changed;
  35302. }
  35303. else {
  35304. // No cache for dynamic
  35305. for (var i = 0; i < size; i++) {
  35306. this._bufferData[location + i] = data[i];
  35307. }
  35308. }
  35309. };
  35310. // Update methods
  35311. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35312. // To match std140, matrix must be realigned
  35313. for (var i = 0; i < 3; i++) {
  35314. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35315. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35316. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35317. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35318. }
  35319. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35320. };
  35321. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35322. this._currentEffect.setMatrix3x3(name, matrix);
  35323. };
  35324. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35325. this._currentEffect.setMatrix2x2(name, matrix);
  35326. };
  35327. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35328. // To match std140, matrix must be realigned
  35329. for (var i = 0; i < 2; i++) {
  35330. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35331. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35332. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35333. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35334. }
  35335. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35336. };
  35337. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35338. this._currentEffect.setFloat(name, x);
  35339. };
  35340. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35341. UniformBuffer._tempBuffer[0] = x;
  35342. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35343. };
  35344. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35345. if (suffix === void 0) { suffix = ""; }
  35346. this._currentEffect.setFloat2(name + suffix, x, y);
  35347. };
  35348. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35349. if (suffix === void 0) { suffix = ""; }
  35350. UniformBuffer._tempBuffer[0] = x;
  35351. UniformBuffer._tempBuffer[1] = y;
  35352. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35353. };
  35354. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35355. if (suffix === void 0) { suffix = ""; }
  35356. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35357. };
  35358. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35359. if (suffix === void 0) { suffix = ""; }
  35360. UniformBuffer._tempBuffer[0] = x;
  35361. UniformBuffer._tempBuffer[1] = y;
  35362. UniformBuffer._tempBuffer[2] = z;
  35363. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35364. };
  35365. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35366. if (suffix === void 0) { suffix = ""; }
  35367. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35368. };
  35369. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35370. if (suffix === void 0) { suffix = ""; }
  35371. UniformBuffer._tempBuffer[0] = x;
  35372. UniformBuffer._tempBuffer[1] = y;
  35373. UniformBuffer._tempBuffer[2] = z;
  35374. UniformBuffer._tempBuffer[3] = w;
  35375. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35376. };
  35377. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35378. this._currentEffect.setMatrix(name, mat);
  35379. };
  35380. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35381. this.updateUniform(name, mat.toArray(), 16);
  35382. };
  35383. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35384. this._currentEffect.setVector3(name, vector);
  35385. };
  35386. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35387. vector.toArray(UniformBuffer._tempBuffer);
  35388. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35389. };
  35390. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35391. this._currentEffect.setVector4(name, vector);
  35392. };
  35393. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35394. vector.toArray(UniformBuffer._tempBuffer);
  35395. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35396. };
  35397. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35398. if (suffix === void 0) { suffix = ""; }
  35399. this._currentEffect.setColor3(name + suffix, color);
  35400. };
  35401. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35402. if (suffix === void 0) { suffix = ""; }
  35403. color.toArray(UniformBuffer._tempBuffer);
  35404. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35405. };
  35406. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35407. if (suffix === void 0) { suffix = ""; }
  35408. this._currentEffect.setColor4(name + suffix, color, alpha);
  35409. };
  35410. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35411. if (suffix === void 0) { suffix = ""; }
  35412. color.toArray(UniformBuffer._tempBuffer);
  35413. UniformBuffer._tempBuffer[3] = alpha;
  35414. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35415. };
  35416. /**
  35417. * Sets a sampler uniform on the effect.
  35418. * @param {string} name Name of the sampler.
  35419. * @param {Texture} texture
  35420. */
  35421. UniformBuffer.prototype.setTexture = function (name, texture) {
  35422. this._currentEffect.setTexture(name, texture);
  35423. };
  35424. /**
  35425. * Directly updates the value of the uniform in the cache AND on the GPU.
  35426. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35427. * @param {number[]|Float32Array} data Flattened data
  35428. */
  35429. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35430. this.updateUniform(uniformName, data, data.length);
  35431. this.update();
  35432. };
  35433. /**
  35434. * Binds this uniform buffer to an effect.
  35435. * @param {Effect} effect
  35436. * @param {string} name Name of the uniform block in the shader.
  35437. */
  35438. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35439. this._currentEffect = effect;
  35440. if (this._noUBO || !this._buffer) {
  35441. return;
  35442. }
  35443. effect.bindUniformBuffer(this._buffer, name);
  35444. };
  35445. /**
  35446. * Disposes the uniform buffer.
  35447. */
  35448. UniformBuffer.prototype.dispose = function () {
  35449. if (this._noUBO) {
  35450. return;
  35451. }
  35452. var index = this._engine._uniformBuffers.indexOf(this);
  35453. if (index !== -1) {
  35454. this._engine._uniformBuffers.splice(index, 1);
  35455. }
  35456. if (!this._buffer) {
  35457. return;
  35458. }
  35459. if (this._engine._releaseBuffer(this._buffer)) {
  35460. this._buffer = null;
  35461. }
  35462. };
  35463. // Pool for avoiding memory leaks
  35464. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35465. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35466. return UniformBuffer;
  35467. }());
  35468. BABYLON.UniformBuffer = UniformBuffer;
  35469. })(BABYLON || (BABYLON = {}));
  35470. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35471. "use strict";
  35472. var BABYLON;
  35473. (function (BABYLON) {
  35474. /**
  35475. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35476. */
  35477. var VertexData = /** @class */ (function () {
  35478. function VertexData() {
  35479. }
  35480. /**
  35481. * Uses the passed data array to set the set the values for the specified kind of data
  35482. * @param data a linear array of floating numbers
  35483. * @param kind the type of data that is being set, eg positions, colors etc
  35484. */
  35485. VertexData.prototype.set = function (data, kind) {
  35486. switch (kind) {
  35487. case BABYLON.VertexBuffer.PositionKind:
  35488. this.positions = data;
  35489. break;
  35490. case BABYLON.VertexBuffer.NormalKind:
  35491. this.normals = data;
  35492. break;
  35493. case BABYLON.VertexBuffer.TangentKind:
  35494. this.tangents = data;
  35495. break;
  35496. case BABYLON.VertexBuffer.UVKind:
  35497. this.uvs = data;
  35498. break;
  35499. case BABYLON.VertexBuffer.UV2Kind:
  35500. this.uvs2 = data;
  35501. break;
  35502. case BABYLON.VertexBuffer.UV3Kind:
  35503. this.uvs3 = data;
  35504. break;
  35505. case BABYLON.VertexBuffer.UV4Kind:
  35506. this.uvs4 = data;
  35507. break;
  35508. case BABYLON.VertexBuffer.UV5Kind:
  35509. this.uvs5 = data;
  35510. break;
  35511. case BABYLON.VertexBuffer.UV6Kind:
  35512. this.uvs6 = data;
  35513. break;
  35514. case BABYLON.VertexBuffer.ColorKind:
  35515. this.colors = data;
  35516. break;
  35517. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35518. this.matricesIndices = data;
  35519. break;
  35520. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35521. this.matricesWeights = data;
  35522. break;
  35523. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35524. this.matricesIndicesExtra = data;
  35525. break;
  35526. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35527. this.matricesWeightsExtra = data;
  35528. break;
  35529. }
  35530. };
  35531. /**
  35532. * Associates the vertexData to the passed Mesh.
  35533. * Sets it as updatable or not (default `false`)
  35534. * @param mesh the mesh the vertexData is applied to
  35535. * @param updatable when used and having the value true allows new data to update the vertexData
  35536. * @returns the VertexData
  35537. */
  35538. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35539. this._applyTo(mesh, updatable);
  35540. return this;
  35541. };
  35542. /**
  35543. * Associates the vertexData to the passed Geometry.
  35544. * Sets it as updatable or not (default `false`)
  35545. * @param geometry the geometry the vertexData is applied to
  35546. * @param updatable when used and having the value true allows new data to update the vertexData
  35547. * @returns VertexData
  35548. */
  35549. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35550. this._applyTo(geometry, updatable);
  35551. return this;
  35552. };
  35553. /**
  35554. * Updates the associated mesh
  35555. * @param mesh the mesh to be updated
  35556. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35557. * @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
  35558. * @returns VertexData
  35559. */
  35560. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35561. this._update(mesh);
  35562. return this;
  35563. };
  35564. /**
  35565. * Updates the associated geometry
  35566. * @param geometry the geometry to be updated
  35567. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35568. * @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
  35569. * @returns VertexData.
  35570. */
  35571. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35572. this._update(geometry);
  35573. return this;
  35574. };
  35575. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35576. if (updatable === void 0) { updatable = false; }
  35577. if (this.positions) {
  35578. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35579. }
  35580. if (this.normals) {
  35581. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35582. }
  35583. if (this.tangents) {
  35584. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  35585. }
  35586. if (this.uvs) {
  35587. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35588. }
  35589. if (this.uvs2) {
  35590. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35591. }
  35592. if (this.uvs3) {
  35593. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35594. }
  35595. if (this.uvs4) {
  35596. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35597. }
  35598. if (this.uvs5) {
  35599. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35600. }
  35601. if (this.uvs6) {
  35602. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35603. }
  35604. if (this.colors) {
  35605. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35606. }
  35607. if (this.matricesIndices) {
  35608. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35609. }
  35610. if (this.matricesWeights) {
  35611. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35612. }
  35613. if (this.matricesIndicesExtra) {
  35614. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35615. }
  35616. if (this.matricesWeightsExtra) {
  35617. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35618. }
  35619. if (this.indices) {
  35620. meshOrGeometry.setIndices(this.indices, null, updatable);
  35621. }
  35622. return this;
  35623. };
  35624. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35625. if (this.positions) {
  35626. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35627. }
  35628. if (this.normals) {
  35629. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35630. }
  35631. if (this.tangents) {
  35632. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  35633. }
  35634. if (this.uvs) {
  35635. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35636. }
  35637. if (this.uvs2) {
  35638. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35639. }
  35640. if (this.uvs3) {
  35641. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35642. }
  35643. if (this.uvs4) {
  35644. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35645. }
  35646. if (this.uvs5) {
  35647. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35648. }
  35649. if (this.uvs6) {
  35650. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35651. }
  35652. if (this.colors) {
  35653. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35654. }
  35655. if (this.matricesIndices) {
  35656. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35657. }
  35658. if (this.matricesWeights) {
  35659. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35660. }
  35661. if (this.matricesIndicesExtra) {
  35662. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35663. }
  35664. if (this.matricesWeightsExtra) {
  35665. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  35666. }
  35667. if (this.indices) {
  35668. meshOrGeometry.setIndices(this.indices, null);
  35669. }
  35670. return this;
  35671. };
  35672. /**
  35673. * Transforms each position and each normal of the vertexData according to the passed Matrix
  35674. * @param matrix the transforming matrix
  35675. * @returns the VertexData
  35676. */
  35677. VertexData.prototype.transform = function (matrix) {
  35678. var transformed = BABYLON.Vector3.Zero();
  35679. var index;
  35680. if (this.positions) {
  35681. var position = BABYLON.Vector3.Zero();
  35682. for (index = 0; index < this.positions.length; index += 3) {
  35683. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  35684. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  35685. this.positions[index] = transformed.x;
  35686. this.positions[index + 1] = transformed.y;
  35687. this.positions[index + 2] = transformed.z;
  35688. }
  35689. }
  35690. if (this.normals) {
  35691. var normal = BABYLON.Vector3.Zero();
  35692. for (index = 0; index < this.normals.length; index += 3) {
  35693. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  35694. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  35695. this.normals[index] = transformed.x;
  35696. this.normals[index + 1] = transformed.y;
  35697. this.normals[index + 2] = transformed.z;
  35698. }
  35699. }
  35700. if (this.tangents) {
  35701. var tangent = BABYLON.Vector4.Zero();
  35702. var tangentTransformed = BABYLON.Vector4.Zero();
  35703. for (index = 0; index < this.tangents.length; index += 4) {
  35704. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  35705. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  35706. this.tangents[index] = tangentTransformed.x;
  35707. this.tangents[index + 1] = tangentTransformed.y;
  35708. this.tangents[index + 2] = tangentTransformed.z;
  35709. this.tangents[index + 3] = tangentTransformed.w;
  35710. }
  35711. }
  35712. return this;
  35713. };
  35714. /**
  35715. * Merges the passed VertexData into the current one
  35716. * @param other the VertexData to be merged into the current one
  35717. * @returns the modified VertexData
  35718. */
  35719. VertexData.prototype.merge = function (other) {
  35720. this._validate();
  35721. other._validate();
  35722. if (!this.normals !== !other.normals ||
  35723. !this.tangents !== !other.tangents ||
  35724. !this.uvs !== !other.uvs ||
  35725. !this.uvs2 !== !other.uvs2 ||
  35726. !this.uvs3 !== !other.uvs3 ||
  35727. !this.uvs4 !== !other.uvs4 ||
  35728. !this.uvs5 !== !other.uvs5 ||
  35729. !this.uvs6 !== !other.uvs6 ||
  35730. !this.colors !== !other.colors ||
  35731. !this.matricesIndices !== !other.matricesIndices ||
  35732. !this.matricesWeights !== !other.matricesWeights ||
  35733. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  35734. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  35735. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  35736. }
  35737. if (other.indices) {
  35738. if (!this.indices) {
  35739. this.indices = [];
  35740. }
  35741. var offset = this.positions ? this.positions.length / 3 : 0;
  35742. for (var index = 0; index < other.indices.length; index++) {
  35743. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  35744. this.indices.push(other.indices[index] + offset);
  35745. }
  35746. }
  35747. this.positions = this._mergeElement(this.positions, other.positions);
  35748. this.normals = this._mergeElement(this.normals, other.normals);
  35749. this.tangents = this._mergeElement(this.tangents, other.tangents);
  35750. this.uvs = this._mergeElement(this.uvs, other.uvs);
  35751. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  35752. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  35753. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  35754. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  35755. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  35756. this.colors = this._mergeElement(this.colors, other.colors);
  35757. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  35758. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  35759. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  35760. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  35761. return this;
  35762. };
  35763. VertexData.prototype._mergeElement = function (source, other) {
  35764. if (!source) {
  35765. return other;
  35766. }
  35767. if (!other) {
  35768. return source;
  35769. }
  35770. var len = other.length + source.length;
  35771. var isSrcTypedArray = source instanceof Float32Array;
  35772. var isOthTypedArray = other instanceof Float32Array;
  35773. // use non-loop method when the source is Float32Array
  35774. if (isSrcTypedArray) {
  35775. var ret32 = new Float32Array(len);
  35776. ret32.set(source);
  35777. ret32.set(other, source.length);
  35778. return ret32;
  35779. // source is number[], when other is also use concat
  35780. }
  35781. else if (!isOthTypedArray) {
  35782. return source.concat(other);
  35783. // source is a number[], but other is a Float32Array, loop required
  35784. }
  35785. else {
  35786. var ret = source.slice(0); // copy source to a separate array
  35787. for (var i = 0, len = other.length; i < len; i++) {
  35788. ret.push(other[i]);
  35789. }
  35790. return ret;
  35791. }
  35792. };
  35793. VertexData.prototype._validate = function () {
  35794. if (!this.positions) {
  35795. throw new Error("Positions are required");
  35796. }
  35797. var getElementCount = function (kind, values) {
  35798. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  35799. if ((values.length % stride) !== 0) {
  35800. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  35801. }
  35802. return values.length / stride;
  35803. };
  35804. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  35805. var validateElementCount = function (kind, values) {
  35806. var elementCount = getElementCount(kind, values);
  35807. if (elementCount !== positionsElementCount) {
  35808. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  35809. }
  35810. };
  35811. if (this.normals)
  35812. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  35813. if (this.tangents)
  35814. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  35815. if (this.uvs)
  35816. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  35817. if (this.uvs2)
  35818. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  35819. if (this.uvs3)
  35820. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  35821. if (this.uvs4)
  35822. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  35823. if (this.uvs5)
  35824. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  35825. if (this.uvs6)
  35826. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  35827. if (this.colors)
  35828. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  35829. if (this.matricesIndices)
  35830. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  35831. if (this.matricesWeights)
  35832. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  35833. if (this.matricesIndicesExtra)
  35834. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  35835. if (this.matricesWeightsExtra)
  35836. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  35837. };
  35838. /**
  35839. * Serializes the VertexData
  35840. * @returns a serialized object
  35841. */
  35842. VertexData.prototype.serialize = function () {
  35843. var serializationObject = this.serialize();
  35844. if (this.positions) {
  35845. serializationObject.positions = this.positions;
  35846. }
  35847. if (this.normals) {
  35848. serializationObject.normals = this.normals;
  35849. }
  35850. if (this.tangents) {
  35851. serializationObject.tangents = this.tangents;
  35852. }
  35853. if (this.uvs) {
  35854. serializationObject.uvs = this.uvs;
  35855. }
  35856. if (this.uvs2) {
  35857. serializationObject.uvs2 = this.uvs2;
  35858. }
  35859. if (this.uvs3) {
  35860. serializationObject.uvs3 = this.uvs3;
  35861. }
  35862. if (this.uvs4) {
  35863. serializationObject.uvs4 = this.uvs4;
  35864. }
  35865. if (this.uvs5) {
  35866. serializationObject.uvs5 = this.uvs5;
  35867. }
  35868. if (this.uvs6) {
  35869. serializationObject.uvs6 = this.uvs6;
  35870. }
  35871. if (this.colors) {
  35872. serializationObject.colors = this.colors;
  35873. }
  35874. if (this.matricesIndices) {
  35875. serializationObject.matricesIndices = this.matricesIndices;
  35876. serializationObject.matricesIndices._isExpanded = true;
  35877. }
  35878. if (this.matricesWeights) {
  35879. serializationObject.matricesWeights = this.matricesWeights;
  35880. }
  35881. if (this.matricesIndicesExtra) {
  35882. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  35883. serializationObject.matricesIndicesExtra._isExpanded = true;
  35884. }
  35885. if (this.matricesWeightsExtra) {
  35886. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  35887. }
  35888. serializationObject.indices = this.indices;
  35889. return serializationObject;
  35890. };
  35891. // Statics
  35892. /**
  35893. * Extracts the vertexData from a mesh
  35894. * @param mesh the mesh from which to extract the VertexData
  35895. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  35896. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  35897. * @returns the object VertexData associated to the passed mesh
  35898. */
  35899. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  35900. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  35901. };
  35902. /**
  35903. * Extracts the vertexData from the geometry
  35904. * @param geometry the geometry from which to extract the VertexData
  35905. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  35906. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  35907. * @returns the object VertexData associated to the passed mesh
  35908. */
  35909. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  35910. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  35911. };
  35912. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  35913. var result = new VertexData();
  35914. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35915. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  35916. }
  35917. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35918. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  35919. }
  35920. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35921. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  35922. }
  35923. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35924. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  35925. }
  35926. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35927. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  35928. }
  35929. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35930. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  35931. }
  35932. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35933. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  35934. }
  35935. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35936. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  35937. }
  35938. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35939. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  35940. }
  35941. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35942. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  35943. }
  35944. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35945. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  35946. }
  35947. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35948. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  35949. }
  35950. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  35951. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  35952. }
  35953. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  35954. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  35955. }
  35956. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  35957. return result;
  35958. };
  35959. /**
  35960. * Creates the VertexData for a Ribbon
  35961. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  35962. * * pathArray array of paths, each of which an array of successive Vector3
  35963. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  35964. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  35965. * * 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
  35966. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35967. * * 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)
  35968. * * 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)
  35969. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  35970. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  35971. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  35972. * @returns the VertexData of the ribbon
  35973. */
  35974. VertexData.CreateRibbon = function (options) {
  35975. var pathArray = options.pathArray;
  35976. var closeArray = options.closeArray || false;
  35977. var closePath = options.closePath || false;
  35978. var invertUV = options.invertUV || false;
  35979. var defaultOffset = Math.floor(pathArray[0].length / 2);
  35980. var offset = options.offset || defaultOffset;
  35981. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  35982. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35983. var customUV = options.uvs;
  35984. var customColors = options.colors;
  35985. var positions = [];
  35986. var indices = [];
  35987. var normals = [];
  35988. var uvs = [];
  35989. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  35990. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  35991. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  35992. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  35993. var minlg; // minimal length among all paths from pathArray
  35994. var lg = []; // array of path lengths : nb of vertex per path
  35995. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  35996. var p; // path iterator
  35997. var i; // point iterator
  35998. var j; // point iterator
  35999. // if single path in pathArray
  36000. if (pathArray.length < 2) {
  36001. var ar1 = [];
  36002. var ar2 = [];
  36003. for (i = 0; i < pathArray[0].length - offset; i++) {
  36004. ar1.push(pathArray[0][i]);
  36005. ar2.push(pathArray[0][i + offset]);
  36006. }
  36007. pathArray = [ar1, ar2];
  36008. }
  36009. // positions and horizontal distances (u)
  36010. var idc = 0;
  36011. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36012. var path;
  36013. var l;
  36014. minlg = pathArray[0].length;
  36015. var vectlg;
  36016. var dist;
  36017. for (p = 0; p < pathArray.length; p++) {
  36018. uTotalDistance[p] = 0;
  36019. us[p] = [0];
  36020. path = pathArray[p];
  36021. l = path.length;
  36022. minlg = (minlg < l) ? minlg : l;
  36023. j = 0;
  36024. while (j < l) {
  36025. positions.push(path[j].x, path[j].y, path[j].z);
  36026. if (j > 0) {
  36027. vectlg = path[j].subtract(path[j - 1]).length();
  36028. dist = vectlg + uTotalDistance[p];
  36029. us[p].push(dist);
  36030. uTotalDistance[p] = dist;
  36031. }
  36032. j++;
  36033. }
  36034. if (closePath) {
  36035. j--;
  36036. positions.push(path[0].x, path[0].y, path[0].z);
  36037. vectlg = path[j].subtract(path[0]).length();
  36038. dist = vectlg + uTotalDistance[p];
  36039. us[p].push(dist);
  36040. uTotalDistance[p] = dist;
  36041. }
  36042. lg[p] = l + closePathCorr;
  36043. idx[p] = idc;
  36044. idc += (l + closePathCorr);
  36045. }
  36046. // vertical distances (v)
  36047. var path1;
  36048. var path2;
  36049. var vertex1 = null;
  36050. var vertex2 = null;
  36051. for (i = 0; i < minlg + closePathCorr; i++) {
  36052. vTotalDistance[i] = 0;
  36053. vs[i] = [0];
  36054. for (p = 0; p < pathArray.length - 1; p++) {
  36055. path1 = pathArray[p];
  36056. path2 = pathArray[p + 1];
  36057. if (i === minlg) {
  36058. vertex1 = path1[0];
  36059. vertex2 = path2[0];
  36060. }
  36061. else {
  36062. vertex1 = path1[i];
  36063. vertex2 = path2[i];
  36064. }
  36065. vectlg = vertex2.subtract(vertex1).length();
  36066. dist = vectlg + vTotalDistance[i];
  36067. vs[i].push(dist);
  36068. vTotalDistance[i] = dist;
  36069. }
  36070. if (closeArray && vertex2 && vertex1) {
  36071. path1 = pathArray[p];
  36072. path2 = pathArray[0];
  36073. if (i === minlg) {
  36074. vertex2 = path2[0];
  36075. }
  36076. vectlg = vertex2.subtract(vertex1).length();
  36077. dist = vectlg + vTotalDistance[i];
  36078. vTotalDistance[i] = dist;
  36079. }
  36080. }
  36081. // uvs
  36082. var u;
  36083. var v;
  36084. if (customUV) {
  36085. for (p = 0; p < customUV.length; p++) {
  36086. uvs.push(customUV[p].x, customUV[p].y);
  36087. }
  36088. }
  36089. else {
  36090. for (p = 0; p < pathArray.length; p++) {
  36091. for (i = 0; i < minlg + closePathCorr; i++) {
  36092. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36093. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36094. if (invertUV) {
  36095. uvs.push(v, u);
  36096. }
  36097. else {
  36098. uvs.push(u, v);
  36099. }
  36100. }
  36101. }
  36102. }
  36103. // indices
  36104. p = 0; // path index
  36105. var pi = 0; // positions array index
  36106. var l1 = lg[p] - 1; // path1 length
  36107. var l2 = lg[p + 1] - 1; // path2 length
  36108. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36109. var shft = idx[1] - idx[0]; // shift
  36110. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36111. while (pi <= min && p < path1nb) {
  36112. // 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
  36113. indices.push(pi, pi + shft, pi + 1);
  36114. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36115. pi += 1;
  36116. if (pi === min) {
  36117. p++;
  36118. if (p === lg.length - 1) {
  36119. shft = idx[0] - idx[p];
  36120. l1 = lg[p] - 1;
  36121. l2 = lg[0] - 1;
  36122. }
  36123. else {
  36124. shft = idx[p + 1] - idx[p];
  36125. l1 = lg[p] - 1;
  36126. l2 = lg[p + 1] - 1;
  36127. }
  36128. pi = idx[p];
  36129. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36130. }
  36131. }
  36132. // normals
  36133. VertexData.ComputeNormals(positions, indices, normals);
  36134. if (closePath) {
  36135. var indexFirst = 0;
  36136. var indexLast = 0;
  36137. for (p = 0; p < pathArray.length; p++) {
  36138. indexFirst = idx[p] * 3;
  36139. if (p + 1 < pathArray.length) {
  36140. indexLast = (idx[p + 1] - 1) * 3;
  36141. }
  36142. else {
  36143. indexLast = normals.length - 3;
  36144. }
  36145. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36146. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36147. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36148. normals[indexLast] = normals[indexFirst];
  36149. normals[indexLast + 1] = normals[indexFirst + 1];
  36150. normals[indexLast + 2] = normals[indexFirst + 2];
  36151. }
  36152. }
  36153. // sides
  36154. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36155. // Colors
  36156. var colors = null;
  36157. if (customColors) {
  36158. colors = new Float32Array(customColors.length * 4);
  36159. for (var c = 0; c < customColors.length; c++) {
  36160. colors[c * 4] = customColors[c].r;
  36161. colors[c * 4 + 1] = customColors[c].g;
  36162. colors[c * 4 + 2] = customColors[c].b;
  36163. colors[c * 4 + 3] = customColors[c].a;
  36164. }
  36165. }
  36166. // Result
  36167. var vertexData = new VertexData();
  36168. var positions32 = new Float32Array(positions);
  36169. var normals32 = new Float32Array(normals);
  36170. var uvs32 = new Float32Array(uvs);
  36171. vertexData.indices = indices;
  36172. vertexData.positions = positions32;
  36173. vertexData.normals = normals32;
  36174. vertexData.uvs = uvs32;
  36175. if (colors) {
  36176. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36177. }
  36178. if (closePath) {
  36179. vertexData._idx = idx;
  36180. }
  36181. return vertexData;
  36182. };
  36183. /**
  36184. * Creates the VertexData for a box
  36185. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36186. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36187. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36188. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36189. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36190. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36191. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36192. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36193. * * 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)
  36194. * * 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)
  36195. * @returns the VertexData of the box
  36196. */
  36197. VertexData.CreateBox = function (options) {
  36198. var normalsSource = [
  36199. new BABYLON.Vector3(0, 0, 1),
  36200. new BABYLON.Vector3(0, 0, -1),
  36201. new BABYLON.Vector3(1, 0, 0),
  36202. new BABYLON.Vector3(-1, 0, 0),
  36203. new BABYLON.Vector3(0, 1, 0),
  36204. new BABYLON.Vector3(0, -1, 0)
  36205. ];
  36206. var indices = [];
  36207. var positions = [];
  36208. var normals = [];
  36209. var uvs = [];
  36210. var width = options.width || options.size || 1;
  36211. var height = options.height || options.size || 1;
  36212. var depth = options.depth || options.size || 1;
  36213. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36214. var faceUV = options.faceUV || new Array(6);
  36215. var faceColors = options.faceColors;
  36216. var colors = [];
  36217. // default face colors and UV if undefined
  36218. for (var f = 0; f < 6; f++) {
  36219. if (faceUV[f] === undefined) {
  36220. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36221. }
  36222. if (faceColors && faceColors[f] === undefined) {
  36223. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36224. }
  36225. }
  36226. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36227. // Create each face in turn.
  36228. for (var index = 0; index < normalsSource.length; index++) {
  36229. var normal = normalsSource[index];
  36230. // Get two vectors perpendicular to the face normal and to each other.
  36231. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36232. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36233. // Six indices (two triangles) per face.
  36234. var verticesLength = positions.length / 3;
  36235. indices.push(verticesLength);
  36236. indices.push(verticesLength + 1);
  36237. indices.push(verticesLength + 2);
  36238. indices.push(verticesLength);
  36239. indices.push(verticesLength + 2);
  36240. indices.push(verticesLength + 3);
  36241. // Four vertices per face.
  36242. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36243. positions.push(vertex.x, vertex.y, vertex.z);
  36244. normals.push(normal.x, normal.y, normal.z);
  36245. uvs.push(faceUV[index].z, faceUV[index].w);
  36246. if (faceColors) {
  36247. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36248. }
  36249. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36250. positions.push(vertex.x, vertex.y, vertex.z);
  36251. normals.push(normal.x, normal.y, normal.z);
  36252. uvs.push(faceUV[index].x, faceUV[index].w);
  36253. if (faceColors) {
  36254. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36255. }
  36256. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36257. positions.push(vertex.x, vertex.y, vertex.z);
  36258. normals.push(normal.x, normal.y, normal.z);
  36259. uvs.push(faceUV[index].x, faceUV[index].y);
  36260. if (faceColors) {
  36261. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36262. }
  36263. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36264. positions.push(vertex.x, vertex.y, vertex.z);
  36265. normals.push(normal.x, normal.y, normal.z);
  36266. uvs.push(faceUV[index].z, faceUV[index].y);
  36267. if (faceColors) {
  36268. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36269. }
  36270. }
  36271. // sides
  36272. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36273. // Result
  36274. var vertexData = new VertexData();
  36275. vertexData.indices = indices;
  36276. vertexData.positions = positions;
  36277. vertexData.normals = normals;
  36278. vertexData.uvs = uvs;
  36279. if (faceColors) {
  36280. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36281. vertexData.colors = totalColors;
  36282. }
  36283. return vertexData;
  36284. };
  36285. /**
  36286. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36287. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36288. * * segments sets the number of horizontal strips optional, default 32
  36289. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36290. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36291. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36292. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36293. * * 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
  36294. * * 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
  36295. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36296. * * 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)
  36297. * * 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)
  36298. * @returns the VertexData of the ellipsoid
  36299. */
  36300. VertexData.CreateSphere = function (options) {
  36301. var segments = options.segments || 32;
  36302. var diameterX = options.diameterX || options.diameter || 1;
  36303. var diameterY = options.diameterY || options.diameter || 1;
  36304. var diameterZ = options.diameterZ || options.diameter || 1;
  36305. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36306. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36307. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36308. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36309. var totalZRotationSteps = 2 + segments;
  36310. var totalYRotationSteps = 2 * totalZRotationSteps;
  36311. var indices = [];
  36312. var positions = [];
  36313. var normals = [];
  36314. var uvs = [];
  36315. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36316. var normalizedZ = zRotationStep / totalZRotationSteps;
  36317. var angleZ = normalizedZ * Math.PI * slice;
  36318. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36319. var normalizedY = yRotationStep / totalYRotationSteps;
  36320. var angleY = normalizedY * Math.PI * 2 * arc;
  36321. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36322. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36323. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36324. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36325. var vertex = complete.multiply(radius);
  36326. var normal = complete.divide(radius).normalize();
  36327. positions.push(vertex.x, vertex.y, vertex.z);
  36328. normals.push(normal.x, normal.y, normal.z);
  36329. uvs.push(normalizedY, normalizedZ);
  36330. }
  36331. if (zRotationStep > 0) {
  36332. var verticesCount = positions.length / 3;
  36333. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36334. indices.push((firstIndex));
  36335. indices.push((firstIndex + 1));
  36336. indices.push(firstIndex + totalYRotationSteps + 1);
  36337. indices.push((firstIndex + totalYRotationSteps + 1));
  36338. indices.push((firstIndex + 1));
  36339. indices.push((firstIndex + totalYRotationSteps + 2));
  36340. }
  36341. }
  36342. }
  36343. // Sides
  36344. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36345. // Result
  36346. var vertexData = new VertexData();
  36347. vertexData.indices = indices;
  36348. vertexData.positions = positions;
  36349. vertexData.normals = normals;
  36350. vertexData.uvs = uvs;
  36351. return vertexData;
  36352. };
  36353. /**
  36354. * Creates the VertexData for a cylinder, cone or prism
  36355. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36356. * * height sets the height (y direction) of the cylinder, optional, default 2
  36357. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36358. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36359. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36360. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36361. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36362. * * 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
  36363. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36364. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36365. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36366. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36367. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36368. * * 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)
  36369. * * 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)
  36370. * @returns the VertexData of the cylinder, cone or prism
  36371. */
  36372. VertexData.CreateCylinder = function (options) {
  36373. var height = options.height || 2;
  36374. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36375. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36376. var tessellation = options.tessellation || 24;
  36377. var subdivisions = options.subdivisions || 1;
  36378. var hasRings = options.hasRings ? true : false;
  36379. var enclose = options.enclose ? true : false;
  36380. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36381. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36382. var faceUV = options.faceUV || new Array(3);
  36383. var faceColors = options.faceColors;
  36384. // default face colors and UV if undefined
  36385. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36386. var ringNb = (hasRings) ? subdivisions : 1;
  36387. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36388. var f;
  36389. for (f = 0; f < surfaceNb; f++) {
  36390. if (faceColors && faceColors[f] === undefined) {
  36391. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36392. }
  36393. }
  36394. for (f = 0; f < surfaceNb; f++) {
  36395. if (faceUV && faceUV[f] === undefined) {
  36396. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36397. }
  36398. }
  36399. var indices = new Array();
  36400. var positions = new Array();
  36401. var normals = new Array();
  36402. var uvs = new Array();
  36403. var colors = new Array();
  36404. var angle_step = Math.PI * 2 * arc / tessellation;
  36405. var angle;
  36406. var h;
  36407. var radius;
  36408. var tan = (diameterBottom - diameterTop) / 2 / height;
  36409. var ringVertex = BABYLON.Vector3.Zero();
  36410. var ringNormal = BABYLON.Vector3.Zero();
  36411. var ringFirstVertex = BABYLON.Vector3.Zero();
  36412. var ringFirstNormal = BABYLON.Vector3.Zero();
  36413. var quadNormal = BABYLON.Vector3.Zero();
  36414. var Y = BABYLON.Axis.Y;
  36415. // positions, normals, uvs
  36416. var i;
  36417. var j;
  36418. var r;
  36419. var ringIdx = 1;
  36420. var s = 1; // surface index
  36421. var cs = 0;
  36422. var v = 0;
  36423. for (i = 0; i <= subdivisions; i++) {
  36424. h = i / subdivisions;
  36425. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36426. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36427. for (r = 0; r < ringIdx; r++) {
  36428. if (hasRings) {
  36429. s += r;
  36430. }
  36431. if (enclose) {
  36432. s += 2 * r;
  36433. }
  36434. for (j = 0; j <= tessellation; j++) {
  36435. angle = j * angle_step;
  36436. // position
  36437. ringVertex.x = Math.cos(-angle) * radius;
  36438. ringVertex.y = -height / 2 + h * height;
  36439. ringVertex.z = Math.sin(-angle) * radius;
  36440. // normal
  36441. if (diameterTop === 0 && i === subdivisions) {
  36442. // if no top cap, reuse former normals
  36443. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36444. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36445. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36446. }
  36447. else {
  36448. ringNormal.x = ringVertex.x;
  36449. ringNormal.z = ringVertex.z;
  36450. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36451. ringNormal.normalize();
  36452. }
  36453. // keep first ring vertex values for enclose
  36454. if (j === 0) {
  36455. ringFirstVertex.copyFrom(ringVertex);
  36456. ringFirstNormal.copyFrom(ringNormal);
  36457. }
  36458. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36459. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36460. if (hasRings) {
  36461. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36462. }
  36463. else {
  36464. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36465. }
  36466. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36467. if (faceColors) {
  36468. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36469. }
  36470. }
  36471. // if enclose, add four vertices and their dedicated normals
  36472. if (arc !== 1 && enclose) {
  36473. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36474. positions.push(0, ringVertex.y, 0);
  36475. positions.push(0, ringVertex.y, 0);
  36476. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36477. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36478. quadNormal.normalize();
  36479. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36480. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36481. quadNormal.normalize();
  36482. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36483. if (hasRings) {
  36484. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36485. }
  36486. else {
  36487. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36488. }
  36489. uvs.push(faceUV[s + 1].x, v);
  36490. uvs.push(faceUV[s + 1].z, v);
  36491. if (hasRings) {
  36492. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36493. }
  36494. else {
  36495. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36496. }
  36497. uvs.push(faceUV[s + 2].x, v);
  36498. uvs.push(faceUV[s + 2].z, v);
  36499. if (faceColors) {
  36500. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36501. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36502. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36503. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36504. }
  36505. }
  36506. if (cs !== s) {
  36507. cs = s;
  36508. }
  36509. }
  36510. }
  36511. // indices
  36512. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36513. var s;
  36514. i = 0;
  36515. for (s = 0; s < subdivisions; s++) {
  36516. var i0 = 0;
  36517. var i1 = 0;
  36518. var i2 = 0;
  36519. var i3 = 0;
  36520. for (j = 0; j < tessellation; j++) {
  36521. i0 = i * (e + 1) + j;
  36522. i1 = (i + 1) * (e + 1) + j;
  36523. i2 = i * (e + 1) + (j + 1);
  36524. i3 = (i + 1) * (e + 1) + (j + 1);
  36525. indices.push(i0, i1, i2);
  36526. indices.push(i3, i2, i1);
  36527. }
  36528. if (arc !== 1 && enclose) {
  36529. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36530. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36531. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36532. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36533. }
  36534. i = (hasRings) ? (i + 2) : (i + 1);
  36535. }
  36536. // Caps
  36537. var createCylinderCap = function (isTop) {
  36538. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36539. if (radius === 0) {
  36540. return;
  36541. }
  36542. // Cap positions, normals & uvs
  36543. var angle;
  36544. var circleVector;
  36545. var i;
  36546. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36547. var c = null;
  36548. if (faceColors) {
  36549. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36550. }
  36551. // cap center
  36552. var vbase = positions.length / 3;
  36553. var offset = isTop ? height / 2 : -height / 2;
  36554. var center = new BABYLON.Vector3(0, offset, 0);
  36555. positions.push(center.x, center.y, center.z);
  36556. normals.push(0, isTop ? 1 : -1, 0);
  36557. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36558. if (c) {
  36559. colors.push(c.r, c.g, c.b, c.a);
  36560. }
  36561. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36562. for (i = 0; i <= tessellation; i++) {
  36563. angle = Math.PI * 2 * i * arc / tessellation;
  36564. var cos = Math.cos(-angle);
  36565. var sin = Math.sin(-angle);
  36566. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36567. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36568. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36569. normals.push(0, isTop ? 1 : -1, 0);
  36570. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36571. if (c) {
  36572. colors.push(c.r, c.g, c.b, c.a);
  36573. }
  36574. }
  36575. // Cap indices
  36576. for (i = 0; i < tessellation; i++) {
  36577. if (!isTop) {
  36578. indices.push(vbase);
  36579. indices.push(vbase + (i + 1));
  36580. indices.push(vbase + (i + 2));
  36581. }
  36582. else {
  36583. indices.push(vbase);
  36584. indices.push(vbase + (i + 2));
  36585. indices.push(vbase + (i + 1));
  36586. }
  36587. }
  36588. };
  36589. // add caps to geometry
  36590. createCylinderCap(false);
  36591. createCylinderCap(true);
  36592. // Sides
  36593. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36594. var vertexData = new VertexData();
  36595. vertexData.indices = indices;
  36596. vertexData.positions = positions;
  36597. vertexData.normals = normals;
  36598. vertexData.uvs = uvs;
  36599. if (faceColors) {
  36600. vertexData.colors = colors;
  36601. }
  36602. return vertexData;
  36603. };
  36604. /**
  36605. * Creates the VertexData for a torus
  36606. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36607. * * diameter the diameter of the torus, optional default 1
  36608. * * thickness the diameter of the tube forming the torus, optional default 0.5
  36609. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36610. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36611. * * 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)
  36612. * * 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)
  36613. * @returns the VertexData of the torus
  36614. */
  36615. VertexData.CreateTorus = function (options) {
  36616. var indices = [];
  36617. var positions = [];
  36618. var normals = [];
  36619. var uvs = [];
  36620. var diameter = options.diameter || 1;
  36621. var thickness = options.thickness || 0.5;
  36622. var tessellation = options.tessellation || 16;
  36623. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36624. var stride = tessellation + 1;
  36625. for (var i = 0; i <= tessellation; i++) {
  36626. var u = i / tessellation;
  36627. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36628. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36629. for (var j = 0; j <= tessellation; j++) {
  36630. var v = 1 - j / tessellation;
  36631. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36632. var dx = Math.cos(innerAngle);
  36633. var dy = Math.sin(innerAngle);
  36634. // Create a vertex.
  36635. var normal = new BABYLON.Vector3(dx, dy, 0);
  36636. var position = normal.scale(thickness / 2);
  36637. var textureCoordinate = new BABYLON.Vector2(u, v);
  36638. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36639. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36640. positions.push(position.x, position.y, position.z);
  36641. normals.push(normal.x, normal.y, normal.z);
  36642. uvs.push(textureCoordinate.x, textureCoordinate.y);
  36643. // And create indices for two triangles.
  36644. var nextI = (i + 1) % stride;
  36645. var nextJ = (j + 1) % stride;
  36646. indices.push(i * stride + j);
  36647. indices.push(i * stride + nextJ);
  36648. indices.push(nextI * stride + j);
  36649. indices.push(i * stride + nextJ);
  36650. indices.push(nextI * stride + nextJ);
  36651. indices.push(nextI * stride + j);
  36652. }
  36653. }
  36654. // Sides
  36655. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36656. // Result
  36657. var vertexData = new VertexData();
  36658. vertexData.indices = indices;
  36659. vertexData.positions = positions;
  36660. vertexData.normals = normals;
  36661. vertexData.uvs = uvs;
  36662. return vertexData;
  36663. };
  36664. /**
  36665. * Creates the VertexData of the LineSystem
  36666. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  36667. * - lines an array of lines, each line being an array of successive Vector3
  36668. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  36669. * @returns the VertexData of the LineSystem
  36670. */
  36671. VertexData.CreateLineSystem = function (options) {
  36672. var indices = [];
  36673. var positions = [];
  36674. var lines = options.lines;
  36675. var colors = options.colors;
  36676. var vertexColors = [];
  36677. var idx = 0;
  36678. for (var l = 0; l < lines.length; l++) {
  36679. var points = lines[l];
  36680. for (var index = 0; index < points.length; index++) {
  36681. positions.push(points[index].x, points[index].y, points[index].z);
  36682. if (colors) {
  36683. var color = colors[l];
  36684. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  36685. }
  36686. if (index > 0) {
  36687. indices.push(idx - 1);
  36688. indices.push(idx);
  36689. }
  36690. idx++;
  36691. }
  36692. }
  36693. var vertexData = new VertexData();
  36694. vertexData.indices = indices;
  36695. vertexData.positions = positions;
  36696. if (colors) {
  36697. vertexData.colors = vertexColors;
  36698. }
  36699. return vertexData;
  36700. };
  36701. /**
  36702. * Create the VertexData for a DashedLines
  36703. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  36704. * - points an array successive Vector3
  36705. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  36706. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  36707. * - dashNb the intended total number of dashes, optional, default 200
  36708. * @returns the VertexData for the DashedLines
  36709. */
  36710. VertexData.CreateDashedLines = function (options) {
  36711. var dashSize = options.dashSize || 3;
  36712. var gapSize = options.gapSize || 1;
  36713. var dashNb = options.dashNb || 200;
  36714. var points = options.points;
  36715. var positions = new Array();
  36716. var indices = new Array();
  36717. var curvect = BABYLON.Vector3.Zero();
  36718. var lg = 0;
  36719. var nb = 0;
  36720. var shft = 0;
  36721. var dashshft = 0;
  36722. var curshft = 0;
  36723. var idx = 0;
  36724. var i = 0;
  36725. for (i = 0; i < points.length - 1; i++) {
  36726. points[i + 1].subtractToRef(points[i], curvect);
  36727. lg += curvect.length();
  36728. }
  36729. shft = lg / dashNb;
  36730. dashshft = dashSize * shft / (dashSize + gapSize);
  36731. for (i = 0; i < points.length - 1; i++) {
  36732. points[i + 1].subtractToRef(points[i], curvect);
  36733. nb = Math.floor(curvect.length() / shft);
  36734. curvect.normalize();
  36735. for (var j = 0; j < nb; j++) {
  36736. curshft = shft * j;
  36737. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  36738. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  36739. indices.push(idx, idx + 1);
  36740. idx += 2;
  36741. }
  36742. }
  36743. // Result
  36744. var vertexData = new VertexData();
  36745. vertexData.positions = positions;
  36746. vertexData.indices = indices;
  36747. return vertexData;
  36748. };
  36749. /**
  36750. * Creates the VertexData for a Ground
  36751. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  36752. * - width the width (x direction) of the ground, optional, default 1
  36753. * - height the height (z direction) of the ground, optional, default 1
  36754. * - subdivisions the number of subdivisions per side, optional, default 1
  36755. * @returns the VertexData of the Ground
  36756. */
  36757. VertexData.CreateGround = function (options) {
  36758. var indices = [];
  36759. var positions = [];
  36760. var normals = [];
  36761. var uvs = [];
  36762. var row, col;
  36763. var width = options.width || 1;
  36764. var height = options.height || 1;
  36765. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  36766. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  36767. for (row = 0; row <= subdivisionsY; row++) {
  36768. for (col = 0; col <= subdivisionsX; col++) {
  36769. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  36770. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36771. positions.push(position.x, position.y, position.z);
  36772. normals.push(normal.x, normal.y, normal.z);
  36773. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  36774. }
  36775. }
  36776. for (row = 0; row < subdivisionsY; row++) {
  36777. for (col = 0; col < subdivisionsX; col++) {
  36778. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36779. indices.push(col + 1 + row * (subdivisionsX + 1));
  36780. indices.push(col + row * (subdivisionsX + 1));
  36781. indices.push(col + (row + 1) * (subdivisionsX + 1));
  36782. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36783. indices.push(col + row * (subdivisionsX + 1));
  36784. }
  36785. }
  36786. // Result
  36787. var vertexData = new VertexData();
  36788. vertexData.indices = indices;
  36789. vertexData.positions = positions;
  36790. vertexData.normals = normals;
  36791. vertexData.uvs = uvs;
  36792. return vertexData;
  36793. };
  36794. /**
  36795. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  36796. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  36797. * * xmin the ground minimum X coordinate, optional, default -1
  36798. * * zmin the ground minimum Z coordinate, optional, default -1
  36799. * * xmax the ground maximum X coordinate, optional, default 1
  36800. * * zmax the ground maximum Z coordinate, optional, default 1
  36801. * * 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}
  36802. * * 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}
  36803. * @returns the VertexData of the TiledGround
  36804. */
  36805. VertexData.CreateTiledGround = function (options) {
  36806. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  36807. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  36808. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  36809. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  36810. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  36811. var precision = options.precision || { w: 1, h: 1 };
  36812. var indices = new Array();
  36813. var positions = new Array();
  36814. var normals = new Array();
  36815. var uvs = new Array();
  36816. var row, col, tileRow, tileCol;
  36817. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  36818. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  36819. precision.w = (precision.w < 1) ? 1 : precision.w;
  36820. precision.h = (precision.h < 1) ? 1 : precision.h;
  36821. var tileSize = {
  36822. 'w': (xmax - xmin) / subdivisions.w,
  36823. 'h': (zmax - zmin) / subdivisions.h
  36824. };
  36825. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  36826. // Indices
  36827. var base = positions.length / 3;
  36828. var rowLength = precision.w + 1;
  36829. for (row = 0; row < precision.h; row++) {
  36830. for (col = 0; col < precision.w; col++) {
  36831. var square = [
  36832. base + col + row * rowLength,
  36833. base + (col + 1) + row * rowLength,
  36834. base + (col + 1) + (row + 1) * rowLength,
  36835. base + col + (row + 1) * rowLength
  36836. ];
  36837. indices.push(square[1]);
  36838. indices.push(square[2]);
  36839. indices.push(square[3]);
  36840. indices.push(square[0]);
  36841. indices.push(square[1]);
  36842. indices.push(square[3]);
  36843. }
  36844. }
  36845. // Position, normals and uvs
  36846. var position = BABYLON.Vector3.Zero();
  36847. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36848. for (row = 0; row <= precision.h; row++) {
  36849. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  36850. for (col = 0; col <= precision.w; col++) {
  36851. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  36852. position.y = 0;
  36853. positions.push(position.x, position.y, position.z);
  36854. normals.push(normal.x, normal.y, normal.z);
  36855. uvs.push(col / precision.w, row / precision.h);
  36856. }
  36857. }
  36858. }
  36859. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  36860. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  36861. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  36862. }
  36863. }
  36864. // Result
  36865. var vertexData = new VertexData();
  36866. vertexData.indices = indices;
  36867. vertexData.positions = positions;
  36868. vertexData.normals = normals;
  36869. vertexData.uvs = uvs;
  36870. return vertexData;
  36871. };
  36872. /**
  36873. * Creates the VertexData of the Ground designed from a heightmap
  36874. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  36875. * * width the width (x direction) of the ground
  36876. * * height the height (z direction) of the ground
  36877. * * subdivisions the number of subdivisions per side
  36878. * * minHeight the minimum altitude on the ground, optional, default 0
  36879. * * maxHeight the maximum altitude on the ground, optional default 1
  36880. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  36881. * * buffer the array holding the image color data
  36882. * * bufferWidth the width of image
  36883. * * bufferHeight the height of image
  36884. * @returns the VertexData of the Ground designed from a heightmap
  36885. */
  36886. VertexData.CreateGroundFromHeightMap = function (options) {
  36887. var indices = [];
  36888. var positions = [];
  36889. var normals = [];
  36890. var uvs = [];
  36891. var row, col;
  36892. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  36893. // Vertices
  36894. for (row = 0; row <= options.subdivisions; row++) {
  36895. for (col = 0; col <= options.subdivisions; col++) {
  36896. 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));
  36897. // Compute height
  36898. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  36899. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  36900. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  36901. var r = options.buffer[pos] / 255.0;
  36902. var g = options.buffer[pos + 1] / 255.0;
  36903. var b = options.buffer[pos + 2] / 255.0;
  36904. var gradient = r * filter.r + g * filter.g + b * filter.b;
  36905. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  36906. // Add vertex
  36907. positions.push(position.x, position.y, position.z);
  36908. normals.push(0, 0, 0);
  36909. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  36910. }
  36911. }
  36912. // Indices
  36913. for (row = 0; row < options.subdivisions; row++) {
  36914. for (col = 0; col < options.subdivisions; col++) {
  36915. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  36916. indices.push(col + 1 + row * (options.subdivisions + 1));
  36917. indices.push(col + row * (options.subdivisions + 1));
  36918. indices.push(col + (row + 1) * (options.subdivisions + 1));
  36919. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  36920. indices.push(col + row * (options.subdivisions + 1));
  36921. }
  36922. }
  36923. // Normals
  36924. VertexData.ComputeNormals(positions, indices, normals);
  36925. // Result
  36926. var vertexData = new VertexData();
  36927. vertexData.indices = indices;
  36928. vertexData.positions = positions;
  36929. vertexData.normals = normals;
  36930. vertexData.uvs = uvs;
  36931. return vertexData;
  36932. };
  36933. /**
  36934. * Creates the VertexData for a Plane
  36935. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  36936. * * size sets the width and height of the plane to the value of size, optional default 1
  36937. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  36938. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  36939. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36940. * * 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)
  36941. * * 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)
  36942. * @returns the VertexData of the box
  36943. */
  36944. VertexData.CreatePlane = function (options) {
  36945. var indices = [];
  36946. var positions = [];
  36947. var normals = [];
  36948. var uvs = [];
  36949. var width = options.width || options.size || 1;
  36950. var height = options.height || options.size || 1;
  36951. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36952. // Vertices
  36953. var halfWidth = width / 2.0;
  36954. var halfHeight = height / 2.0;
  36955. positions.push(-halfWidth, -halfHeight, 0);
  36956. normals.push(0, 0, -1.0);
  36957. uvs.push(0.0, 0.0);
  36958. positions.push(halfWidth, -halfHeight, 0);
  36959. normals.push(0, 0, -1.0);
  36960. uvs.push(1.0, 0.0);
  36961. positions.push(halfWidth, halfHeight, 0);
  36962. normals.push(0, 0, -1.0);
  36963. uvs.push(1.0, 1.0);
  36964. positions.push(-halfWidth, halfHeight, 0);
  36965. normals.push(0, 0, -1.0);
  36966. uvs.push(0.0, 1.0);
  36967. // Indices
  36968. indices.push(0);
  36969. indices.push(1);
  36970. indices.push(2);
  36971. indices.push(0);
  36972. indices.push(2);
  36973. indices.push(3);
  36974. // Sides
  36975. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36976. // Result
  36977. var vertexData = new VertexData();
  36978. vertexData.indices = indices;
  36979. vertexData.positions = positions;
  36980. vertexData.normals = normals;
  36981. vertexData.uvs = uvs;
  36982. return vertexData;
  36983. };
  36984. /**
  36985. * Creates the VertexData of the Disc or regular Polygon
  36986. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  36987. * * radius the radius of the disc, optional default 0.5
  36988. * * tessellation the number of polygon sides, optional, default 64
  36989. * * 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
  36990. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36991. * * 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)
  36992. * * 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)
  36993. * @returns the VertexData of the box
  36994. */
  36995. VertexData.CreateDisc = function (options) {
  36996. var positions = new Array();
  36997. var indices = new Array();
  36998. var normals = new Array();
  36999. var uvs = new Array();
  37000. var radius = options.radius || 0.5;
  37001. var tessellation = options.tessellation || 64;
  37002. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37003. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37004. // positions and uvs
  37005. positions.push(0, 0, 0); // disc center first
  37006. uvs.push(0.5, 0.5);
  37007. var theta = Math.PI * 2 * arc;
  37008. var step = theta / tessellation;
  37009. for (var a = 0; a < theta; a += step) {
  37010. var x = Math.cos(a);
  37011. var y = Math.sin(a);
  37012. var u = (x + 1) / 2;
  37013. var v = (1 - y) / 2;
  37014. positions.push(radius * x, radius * y, 0);
  37015. uvs.push(u, v);
  37016. }
  37017. if (arc === 1) {
  37018. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37019. uvs.push(uvs[2], uvs[3]);
  37020. }
  37021. //indices
  37022. var vertexNb = positions.length / 3;
  37023. for (var i = 1; i < vertexNb - 1; i++) {
  37024. indices.push(i + 1, 0, i);
  37025. }
  37026. // result
  37027. VertexData.ComputeNormals(positions, indices, normals);
  37028. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37029. var vertexData = new VertexData();
  37030. vertexData.indices = indices;
  37031. vertexData.positions = positions;
  37032. vertexData.normals = normals;
  37033. vertexData.uvs = uvs;
  37034. return vertexData;
  37035. };
  37036. /**
  37037. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37038. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37039. * @param polygon a mesh built from polygonTriangulation.build()
  37040. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37041. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37042. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37043. * @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)
  37044. * @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)
  37045. * @returns the VertexData of the Polygon
  37046. */
  37047. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37048. var faceUV = fUV || new Array(3);
  37049. var faceColors = fColors;
  37050. var colors = [];
  37051. // default face colors and UV if undefined
  37052. for (var f = 0; f < 3; f++) {
  37053. if (faceUV[f] === undefined) {
  37054. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37055. }
  37056. if (faceColors && faceColors[f] === undefined) {
  37057. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37058. }
  37059. }
  37060. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37061. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37062. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37063. var indices = polygon.getIndices();
  37064. // set face colours and textures
  37065. var idx = 0;
  37066. var face = 0;
  37067. for (var index = 0; index < normals.length; index += 3) {
  37068. //Edge Face no. 1
  37069. if (Math.abs(normals[index + 1]) < 0.001) {
  37070. face = 1;
  37071. }
  37072. //Top Face no. 0
  37073. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37074. face = 0;
  37075. }
  37076. //Bottom Face no. 2
  37077. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37078. face = 2;
  37079. }
  37080. idx = index / 3;
  37081. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37082. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37083. if (faceColors) {
  37084. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37085. }
  37086. }
  37087. // sides
  37088. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37089. // Result
  37090. var vertexData = new VertexData();
  37091. vertexData.indices = indices;
  37092. vertexData.positions = positions;
  37093. vertexData.normals = normals;
  37094. vertexData.uvs = uvs;
  37095. if (faceColors) {
  37096. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37097. vertexData.colors = totalColors;
  37098. }
  37099. return vertexData;
  37100. };
  37101. /**
  37102. * Creates the VertexData of the IcoSphere
  37103. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37104. * * radius the radius of the IcoSphere, optional default 1
  37105. * * radiusX allows stretching in the x direction, optional, default radius
  37106. * * radiusY allows stretching in the y direction, optional, default radius
  37107. * * radiusZ allows stretching in the z direction, optional, default radius
  37108. * * flat when true creates a flat shaded mesh, optional, default true
  37109. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37110. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37111. * * 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)
  37112. * * 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)
  37113. * @returns the VertexData of the IcoSphere
  37114. */
  37115. VertexData.CreateIcoSphere = function (options) {
  37116. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37117. var radius = options.radius || 1;
  37118. var flat = (options.flat === undefined) ? true : options.flat;
  37119. var subdivisions = options.subdivisions || 4;
  37120. var radiusX = options.radiusX || radius;
  37121. var radiusY = options.radiusY || radius;
  37122. var radiusZ = options.radiusZ || radius;
  37123. var t = (1 + Math.sqrt(5)) / 2;
  37124. // 12 vertex x,y,z
  37125. var ico_vertices = [
  37126. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37127. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37128. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37129. ];
  37130. // index of 3 vertex makes a face of icopshere
  37131. var ico_indices = [
  37132. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37133. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37134. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37135. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37136. ];
  37137. // vertex for uv have aliased position, not for UV
  37138. var vertices_unalias_id = [
  37139. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37140. // vertex alias
  37141. 0,
  37142. 2,
  37143. 3,
  37144. 3,
  37145. 3,
  37146. 4,
  37147. 7,
  37148. 8,
  37149. 9,
  37150. 9,
  37151. 10,
  37152. 11 // 23: B + 12
  37153. ];
  37154. // uv as integer step (not pixels !)
  37155. var ico_vertexuv = [
  37156. 5, 1, 3, 1, 6, 4, 0, 0,
  37157. 5, 3, 4, 2, 2, 2, 4, 0,
  37158. 2, 0, 1, 1, 6, 0, 6, 2,
  37159. // vertex alias (for same vertex on different faces)
  37160. 0, 4,
  37161. 3, 3,
  37162. 4, 4,
  37163. 3, 1,
  37164. 4, 2,
  37165. 4, 4,
  37166. 0, 2,
  37167. 1, 1,
  37168. 2, 2,
  37169. 3, 3,
  37170. 1, 3,
  37171. 2, 4 // 23: B + 12
  37172. ];
  37173. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37174. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37175. // First island of uv mapping
  37176. // v = 4h 3+ 2
  37177. // v = 3h 9+ 4
  37178. // v = 2h 9+ 5 B
  37179. // v = 1h 9 1 0
  37180. // v = 0h 3 8 7 A
  37181. // u = 0 1 2 3 4 5 6 *a
  37182. // Second island of uv mapping
  37183. // v = 4h 0+ B+ 4+
  37184. // v = 3h A+ 2+
  37185. // v = 2h 7+ 6 3+
  37186. // v = 1h 8+ 3+
  37187. // v = 0h
  37188. // u = 0 1 2 3 4 5 6 *a
  37189. // Face layout on texture UV mapping
  37190. // ============
  37191. // \ 4 /\ 16 / ======
  37192. // \ / \ / /\ 11 /
  37193. // \/ 7 \/ / \ /
  37194. // ======= / 10 \/
  37195. // /\ 17 /\ =======
  37196. // / \ / \ \ 15 /\
  37197. // / 8 \/ 12 \ \ / \
  37198. // ============ \/ 6 \
  37199. // \ 18 /\ ============
  37200. // \ / \ \ 5 /\ 0 /
  37201. // \/ 13 \ \ / \ /
  37202. // ======= \/ 1 \/
  37203. // =============
  37204. // /\ 19 /\ 2 /\
  37205. // / \ / \ / \
  37206. // / 14 \/ 9 \/ 3 \
  37207. // ===================
  37208. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37209. var ustep = 138 / 1024;
  37210. var vstep = 239 / 1024;
  37211. var uoffset = 60 / 1024;
  37212. var voffset = 26 / 1024;
  37213. // Second island should have margin, not to touch the first island
  37214. // avoid any borderline artefact in pixel rounding
  37215. var island_u_offset = -40 / 1024;
  37216. var island_v_offset = +20 / 1024;
  37217. // face is either island 0 or 1 :
  37218. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37219. var island = [
  37220. 0, 0, 0, 0, 1,
  37221. 0, 0, 1, 1, 0,
  37222. 0, 0, 1, 1, 0,
  37223. 0, 1, 1, 1, 0 // 15 - 19
  37224. ];
  37225. var indices = new Array();
  37226. var positions = new Array();
  37227. var normals = new Array();
  37228. var uvs = new Array();
  37229. var current_indice = 0;
  37230. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37231. var face_vertex_pos = new Array(3);
  37232. var face_vertex_uv = new Array(3);
  37233. var v012;
  37234. for (v012 = 0; v012 < 3; v012++) {
  37235. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37236. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37237. }
  37238. // create all with normals
  37239. for (var face = 0; face < 20; face++) {
  37240. // 3 vertex per face
  37241. for (v012 = 0; v012 < 3; v012++) {
  37242. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37243. var v_id = ico_indices[3 * face + v012];
  37244. // vertex have 3D position (x,y,z)
  37245. 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]);
  37246. // Normalize to get normal, then scale to radius
  37247. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37248. // uv Coordinates from vertex ID
  37249. 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);
  37250. }
  37251. // Subdivide the face (interpolate pos, norm, uv)
  37252. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37253. // - norm is linear interpolation of vertex corner normal
  37254. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37255. // - uv is linear interpolation
  37256. //
  37257. // Topology is as below for sub-divide by 2
  37258. // vertex shown as v0,v1,v2
  37259. // interp index is i1 to progress in range [v0,v1[
  37260. // interp index is i2 to progress in range [v0,v2[
  37261. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37262. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37263. //
  37264. //
  37265. // i2 v2
  37266. // ^ ^
  37267. // / / \
  37268. // / / \
  37269. // / / \
  37270. // / / (0,1) \
  37271. // / #---------\
  37272. // / / \ (0,0)'/ \
  37273. // / / \ / \
  37274. // / / \ / \
  37275. // / / (0,0) \ / (1,0) \
  37276. // / #---------#---------\
  37277. // v0 v1
  37278. //
  37279. // --------------------> i1
  37280. //
  37281. // interp of (i1,i2):
  37282. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37283. // along i1 : lerp(x0,x1, i1/(S-i2))
  37284. //
  37285. // centroid of triangle is needed to get help normal computation
  37286. // (c1,c2) are used for centroid location
  37287. var interp_vertex = function (i1, i2, c1, c2) {
  37288. // vertex is interpolated from
  37289. // - face_vertex_pos[0..2]
  37290. // - face_vertex_uv[0..2]
  37291. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37292. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37293. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37294. pos_interp.normalize();
  37295. var vertex_normal;
  37296. if (flat) {
  37297. // in flat mode, recalculate normal as face centroid normal
  37298. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37299. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37300. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37301. }
  37302. else {
  37303. // in smooth mode, recalculate normal from each single vertex position
  37304. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37305. }
  37306. // Vertex normal need correction due to X,Y,Z radius scaling
  37307. vertex_normal.x /= radiusX;
  37308. vertex_normal.y /= radiusY;
  37309. vertex_normal.z /= radiusZ;
  37310. vertex_normal.normalize();
  37311. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37312. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37313. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37314. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37315. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37316. uvs.push(uv_interp.x, uv_interp.y);
  37317. // push each vertex has member of a face
  37318. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37319. indices.push(current_indice);
  37320. current_indice++;
  37321. };
  37322. for (var i2 = 0; i2 < subdivisions; i2++) {
  37323. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37324. // face : (i1,i2) for /\ :
  37325. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37326. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37327. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37328. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37329. if (i1 + i2 + 1 < subdivisions) {
  37330. // face : (i1,i2)' for \/ :
  37331. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37332. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37333. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37334. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37335. }
  37336. }
  37337. }
  37338. }
  37339. // Sides
  37340. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37341. // Result
  37342. var vertexData = new VertexData();
  37343. vertexData.indices = indices;
  37344. vertexData.positions = positions;
  37345. vertexData.normals = normals;
  37346. vertexData.uvs = uvs;
  37347. return vertexData;
  37348. };
  37349. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37350. /**
  37351. * Creates the VertexData for a Polyhedron
  37352. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37353. * * type provided types are:
  37354. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37355. * * 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)
  37356. * * size the size of the IcoSphere, optional default 1
  37357. * * sizeX allows stretching in the x direction, optional, default size
  37358. * * sizeY allows stretching in the y direction, optional, default size
  37359. * * sizeZ allows stretching in the z direction, optional, default size
  37360. * * 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
  37361. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37362. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37363. * * flat when true creates a flat shaded mesh, optional, default true
  37364. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37365. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37366. * * 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)
  37367. * * 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)
  37368. * @returns the VertexData of the Polyhedron
  37369. */
  37370. VertexData.CreatePolyhedron = function (options) {
  37371. // provided polyhedron types :
  37372. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37373. // 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)
  37374. var polyhedra = [];
  37375. 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]] };
  37376. 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]] };
  37377. polyhedra[2] = {
  37378. 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]],
  37379. 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]]
  37380. };
  37381. polyhedra[3] = {
  37382. 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]],
  37383. 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]]
  37384. };
  37385. polyhedra[4] = {
  37386. 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]],
  37387. 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]]
  37388. };
  37389. 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]] };
  37390. 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]] };
  37391. 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]] };
  37392. 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]] };
  37393. 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]] };
  37394. 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]] };
  37395. 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]] };
  37396. 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]] };
  37397. 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]] };
  37398. polyhedra[14] = {
  37399. 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]],
  37400. 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]]
  37401. };
  37402. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37403. var size = options.size;
  37404. var sizeX = options.sizeX || size || 1;
  37405. var sizeY = options.sizeY || size || 1;
  37406. var sizeZ = options.sizeZ || size || 1;
  37407. var data = options.custom || polyhedra[type];
  37408. var nbfaces = data.face.length;
  37409. var faceUV = options.faceUV || new Array(nbfaces);
  37410. var faceColors = options.faceColors;
  37411. var flat = (options.flat === undefined) ? true : options.flat;
  37412. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37413. var positions = new Array();
  37414. var indices = new Array();
  37415. var normals = new Array();
  37416. var uvs = new Array();
  37417. var colors = new Array();
  37418. var index = 0;
  37419. var faceIdx = 0; // face cursor in the array "indexes"
  37420. var indexes = new Array();
  37421. var i = 0;
  37422. var f = 0;
  37423. var u, v, ang, x, y, tmp;
  37424. // default face colors and UV if undefined
  37425. if (flat) {
  37426. for (f = 0; f < nbfaces; f++) {
  37427. if (faceColors && faceColors[f] === undefined) {
  37428. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37429. }
  37430. if (faceUV && faceUV[f] === undefined) {
  37431. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37432. }
  37433. }
  37434. }
  37435. if (!flat) {
  37436. for (i = 0; i < data.vertex.length; i++) {
  37437. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37438. uvs.push(0, 0);
  37439. }
  37440. for (f = 0; f < nbfaces; f++) {
  37441. for (i = 0; i < data.face[f].length - 2; i++) {
  37442. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37443. }
  37444. }
  37445. }
  37446. else {
  37447. for (f = 0; f < nbfaces; f++) {
  37448. var fl = data.face[f].length; // number of vertices of the current face
  37449. ang = 2 * Math.PI / fl;
  37450. x = 0.5 * Math.tan(ang / 2);
  37451. y = 0.5;
  37452. // positions, uvs, colors
  37453. for (i = 0; i < fl; i++) {
  37454. // positions
  37455. 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);
  37456. indexes.push(index);
  37457. index++;
  37458. // uvs
  37459. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37460. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37461. uvs.push(u, v);
  37462. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37463. y = x * Math.sin(ang) + y * Math.cos(ang);
  37464. x = tmp;
  37465. // colors
  37466. if (faceColors) {
  37467. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37468. }
  37469. }
  37470. // indices from indexes
  37471. for (i = 0; i < fl - 2; i++) {
  37472. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37473. }
  37474. faceIdx += fl;
  37475. }
  37476. }
  37477. VertexData.ComputeNormals(positions, indices, normals);
  37478. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37479. var vertexData = new VertexData();
  37480. vertexData.positions = positions;
  37481. vertexData.indices = indices;
  37482. vertexData.normals = normals;
  37483. vertexData.uvs = uvs;
  37484. if (faceColors && flat) {
  37485. vertexData.colors = colors;
  37486. }
  37487. return vertexData;
  37488. };
  37489. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37490. /**
  37491. * Creates the VertexData for a TorusKnot
  37492. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37493. * * radius the radius of the torus knot, optional, default 2
  37494. * * tube the thickness of the tube, optional, default 0.5
  37495. * * radialSegments the number of sides on each tube segments, optional, default 32
  37496. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37497. * * p the number of windings around the z axis, optional, default 2
  37498. * * q the number of windings around the x axis, optional, default 3
  37499. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37500. * * 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)
  37501. * * 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)
  37502. * @returns the VertexData of the Torus Knot
  37503. */
  37504. VertexData.CreateTorusKnot = function (options) {
  37505. var indices = new Array();
  37506. var positions = new Array();
  37507. var normals = new Array();
  37508. var uvs = new Array();
  37509. var radius = options.radius || 2;
  37510. var tube = options.tube || 0.5;
  37511. var radialSegments = options.radialSegments || 32;
  37512. var tubularSegments = options.tubularSegments || 32;
  37513. var p = options.p || 2;
  37514. var q = options.q || 3;
  37515. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37516. // Helper
  37517. var getPos = function (angle) {
  37518. var cu = Math.cos(angle);
  37519. var su = Math.sin(angle);
  37520. var quOverP = q / p * angle;
  37521. var cs = Math.cos(quOverP);
  37522. var tx = radius * (2 + cs) * 0.5 * cu;
  37523. var ty = radius * (2 + cs) * su * 0.5;
  37524. var tz = radius * Math.sin(quOverP) * 0.5;
  37525. return new BABYLON.Vector3(tx, ty, tz);
  37526. };
  37527. // Vertices
  37528. var i;
  37529. var j;
  37530. for (i = 0; i <= radialSegments; i++) {
  37531. var modI = i % radialSegments;
  37532. var u = modI / radialSegments * 2 * p * Math.PI;
  37533. var p1 = getPos(u);
  37534. var p2 = getPos(u + 0.01);
  37535. var tang = p2.subtract(p1);
  37536. var n = p2.add(p1);
  37537. var bitan = BABYLON.Vector3.Cross(tang, n);
  37538. n = BABYLON.Vector3.Cross(bitan, tang);
  37539. bitan.normalize();
  37540. n.normalize();
  37541. for (j = 0; j < tubularSegments; j++) {
  37542. var modJ = j % tubularSegments;
  37543. var v = modJ / tubularSegments * 2 * Math.PI;
  37544. var cx = -tube * Math.cos(v);
  37545. var cy = tube * Math.sin(v);
  37546. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37547. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37548. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37549. uvs.push(i / radialSegments);
  37550. uvs.push(j / tubularSegments);
  37551. }
  37552. }
  37553. for (i = 0; i < radialSegments; i++) {
  37554. for (j = 0; j < tubularSegments; j++) {
  37555. var jNext = (j + 1) % tubularSegments;
  37556. var a = i * tubularSegments + j;
  37557. var b = (i + 1) * tubularSegments + j;
  37558. var c = (i + 1) * tubularSegments + jNext;
  37559. var d = i * tubularSegments + jNext;
  37560. indices.push(d);
  37561. indices.push(b);
  37562. indices.push(a);
  37563. indices.push(d);
  37564. indices.push(c);
  37565. indices.push(b);
  37566. }
  37567. }
  37568. // Normals
  37569. VertexData.ComputeNormals(positions, indices, normals);
  37570. // Sides
  37571. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37572. // Result
  37573. var vertexData = new VertexData();
  37574. vertexData.indices = indices;
  37575. vertexData.positions = positions;
  37576. vertexData.normals = normals;
  37577. vertexData.uvs = uvs;
  37578. return vertexData;
  37579. };
  37580. // Tools
  37581. /**
  37582. * Compute normals for given positions and indices
  37583. * @param positions an array of vertex positions, [...., x, y, z, ......]
  37584. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  37585. * @param normals an array of vertex normals, [...., x, y, z, ......]
  37586. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  37587. * * facetNormals : optional array of facet normals (vector3)
  37588. * * facetPositions : optional array of facet positions (vector3)
  37589. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  37590. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  37591. * * bInfo : optional bounding info, required for facetPartitioning computation
  37592. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  37593. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  37594. * * useRightHandedSystem: optional boolean to for right handed system computation
  37595. * * depthSort : optional boolean to enable the facet depth sort computation
  37596. * * distanceTo : optional Vector3 to compute the facet depth from this location
  37597. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  37598. */
  37599. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  37600. // temporary scalar variables
  37601. var index = 0; // facet index
  37602. var p1p2x = 0.0; // p1p2 vector x coordinate
  37603. var p1p2y = 0.0; // p1p2 vector y coordinate
  37604. var p1p2z = 0.0; // p1p2 vector z coordinate
  37605. var p3p2x = 0.0; // p3p2 vector x coordinate
  37606. var p3p2y = 0.0; // p3p2 vector y coordinate
  37607. var p3p2z = 0.0; // p3p2 vector z coordinate
  37608. var faceNormalx = 0.0; // facet normal x coordinate
  37609. var faceNormaly = 0.0; // facet normal y coordinate
  37610. var faceNormalz = 0.0; // facet normal z coordinate
  37611. var length = 0.0; // facet normal length before normalization
  37612. var v1x = 0; // vector1 x index in the positions array
  37613. var v1y = 0; // vector1 y index in the positions array
  37614. var v1z = 0; // vector1 z index in the positions array
  37615. var v2x = 0; // vector2 x index in the positions array
  37616. var v2y = 0; // vector2 y index in the positions array
  37617. var v2z = 0; // vector2 z index in the positions array
  37618. var v3x = 0; // vector3 x index in the positions array
  37619. var v3y = 0; // vector3 y index in the positions array
  37620. var v3z = 0; // vector3 z index in the positions array
  37621. var computeFacetNormals = false;
  37622. var computeFacetPositions = false;
  37623. var computeFacetPartitioning = false;
  37624. var computeDepthSort = false;
  37625. var faceNormalSign = 1;
  37626. var ratio = 0;
  37627. var distanceTo = null;
  37628. if (options) {
  37629. computeFacetNormals = (options.facetNormals) ? true : false;
  37630. computeFacetPositions = (options.facetPositions) ? true : false;
  37631. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  37632. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  37633. ratio = options.ratio || 0;
  37634. computeDepthSort = (options.depthSort) ? true : false;
  37635. distanceTo = (options.distanceTo);
  37636. if (computeDepthSort) {
  37637. if (distanceTo === undefined) {
  37638. distanceTo = BABYLON.Vector3.Zero();
  37639. }
  37640. var depthSortedFacets = options.depthSortedFacets;
  37641. }
  37642. }
  37643. // facetPartitioning reinit if needed
  37644. var xSubRatio = 0;
  37645. var ySubRatio = 0;
  37646. var zSubRatio = 0;
  37647. var subSq = 0;
  37648. if (computeFacetPartitioning && options && options.bbSize) {
  37649. var ox = 0; // X partitioning index for facet position
  37650. var oy = 0; // Y partinioning index for facet position
  37651. var oz = 0; // Z partinioning index for facet position
  37652. var b1x = 0; // X partitioning index for facet v1 vertex
  37653. var b1y = 0; // Y partitioning index for facet v1 vertex
  37654. var b1z = 0; // z partitioning index for facet v1 vertex
  37655. var b2x = 0; // X partitioning index for facet v2 vertex
  37656. var b2y = 0; // Y partitioning index for facet v2 vertex
  37657. var b2z = 0; // Z partitioning index for facet v2 vertex
  37658. var b3x = 0; // X partitioning index for facet v3 vertex
  37659. var b3y = 0; // Y partitioning index for facet v3 vertex
  37660. var b3z = 0; // Z partitioning index for facet v3 vertex
  37661. var block_idx_o = 0; // facet barycenter block index
  37662. var block_idx_v1 = 0; // v1 vertex block index
  37663. var block_idx_v2 = 0; // v2 vertex block index
  37664. var block_idx_v3 = 0; // v3 vertex block index
  37665. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  37666. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  37667. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  37668. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  37669. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  37670. subSq = options.subDiv.max * options.subDiv.max;
  37671. options.facetPartitioning.length = 0;
  37672. }
  37673. // reset the normals
  37674. for (index = 0; index < positions.length; index++) {
  37675. normals[index] = 0.0;
  37676. }
  37677. // Loop : 1 indice triplet = 1 facet
  37678. var nbFaces = (indices.length / 3) | 0;
  37679. for (index = 0; index < nbFaces; index++) {
  37680. // get the indexes of the coordinates of each vertex of the facet
  37681. v1x = indices[index * 3] * 3;
  37682. v1y = v1x + 1;
  37683. v1z = v1x + 2;
  37684. v2x = indices[index * 3 + 1] * 3;
  37685. v2y = v2x + 1;
  37686. v2z = v2x + 2;
  37687. v3x = indices[index * 3 + 2] * 3;
  37688. v3y = v3x + 1;
  37689. v3z = v3x + 2;
  37690. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  37691. p1p2y = positions[v1y] - positions[v2y];
  37692. p1p2z = positions[v1z] - positions[v2z];
  37693. p3p2x = positions[v3x] - positions[v2x];
  37694. p3p2y = positions[v3y] - positions[v2y];
  37695. p3p2z = positions[v3z] - positions[v2z];
  37696. // compute the face normal with the cross product
  37697. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  37698. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  37699. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  37700. // normalize this normal and store it in the array facetData
  37701. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37702. length = (length === 0) ? 1.0 : length;
  37703. faceNormalx /= length;
  37704. faceNormaly /= length;
  37705. faceNormalz /= length;
  37706. if (computeFacetNormals && options) {
  37707. options.facetNormals[index].x = faceNormalx;
  37708. options.facetNormals[index].y = faceNormaly;
  37709. options.facetNormals[index].z = faceNormalz;
  37710. }
  37711. if (computeFacetPositions && options) {
  37712. // compute and the facet barycenter coordinates in the array facetPositions
  37713. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  37714. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  37715. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  37716. }
  37717. if (computeFacetPartitioning && options) {
  37718. // store the facet indexes in arrays in the main facetPartitioning array :
  37719. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  37720. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  37721. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  37722. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  37723. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37724. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37725. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37726. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37727. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37728. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37729. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37730. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37731. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37732. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  37733. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  37734. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  37735. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  37736. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  37737. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  37738. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  37739. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  37740. // push each facet index in each block containing the vertex
  37741. options.facetPartitioning[block_idx_v1].push(index);
  37742. if (block_idx_v2 != block_idx_v1) {
  37743. options.facetPartitioning[block_idx_v2].push(index);
  37744. }
  37745. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  37746. options.facetPartitioning[block_idx_v3].push(index);
  37747. }
  37748. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  37749. options.facetPartitioning[block_idx_o].push(index);
  37750. }
  37751. }
  37752. if (computeDepthSort && options && options.facetPositions) {
  37753. var dsf = depthSortedFacets[index];
  37754. dsf.ind = index * 3;
  37755. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  37756. }
  37757. // compute the normals anyway
  37758. normals[v1x] += faceNormalx; // accumulate all the normals per face
  37759. normals[v1y] += faceNormaly;
  37760. normals[v1z] += faceNormalz;
  37761. normals[v2x] += faceNormalx;
  37762. normals[v2y] += faceNormaly;
  37763. normals[v2z] += faceNormalz;
  37764. normals[v3x] += faceNormalx;
  37765. normals[v3y] += faceNormaly;
  37766. normals[v3z] += faceNormalz;
  37767. }
  37768. // last normalization of each normal
  37769. for (index = 0; index < normals.length / 3; index++) {
  37770. faceNormalx = normals[index * 3];
  37771. faceNormaly = normals[index * 3 + 1];
  37772. faceNormalz = normals[index * 3 + 2];
  37773. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37774. length = (length === 0) ? 1.0 : length;
  37775. faceNormalx /= length;
  37776. faceNormaly /= length;
  37777. faceNormalz /= length;
  37778. normals[index * 3] = faceNormalx;
  37779. normals[index * 3 + 1] = faceNormaly;
  37780. normals[index * 3 + 2] = faceNormalz;
  37781. }
  37782. };
  37783. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  37784. var li = indices.length;
  37785. var ln = normals.length;
  37786. var i;
  37787. var n;
  37788. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37789. switch (sideOrientation) {
  37790. case BABYLON.Mesh.FRONTSIDE:
  37791. // nothing changed
  37792. break;
  37793. case BABYLON.Mesh.BACKSIDE:
  37794. var tmp;
  37795. // indices
  37796. for (i = 0; i < li; i += 3) {
  37797. tmp = indices[i];
  37798. indices[i] = indices[i + 2];
  37799. indices[i + 2] = tmp;
  37800. }
  37801. // normals
  37802. for (n = 0; n < ln; n++) {
  37803. normals[n] = -normals[n];
  37804. }
  37805. break;
  37806. case BABYLON.Mesh.DOUBLESIDE:
  37807. // positions
  37808. var lp = positions.length;
  37809. var l = lp / 3;
  37810. for (var p = 0; p < lp; p++) {
  37811. positions[lp + p] = positions[p];
  37812. }
  37813. // indices
  37814. for (i = 0; i < li; i += 3) {
  37815. indices[i + li] = indices[i + 2] + l;
  37816. indices[i + 1 + li] = indices[i + 1] + l;
  37817. indices[i + 2 + li] = indices[i] + l;
  37818. }
  37819. // normals
  37820. for (n = 0; n < ln; n++) {
  37821. normals[ln + n] = -normals[n];
  37822. }
  37823. // uvs
  37824. var lu = uvs.length;
  37825. var u = 0;
  37826. for (u = 0; u < lu; u++) {
  37827. uvs[u + lu] = uvs[u];
  37828. }
  37829. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  37830. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  37831. u = 0;
  37832. for (i = 0; i < lu / 2; i++) {
  37833. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  37834. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  37835. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  37836. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  37837. u += 2;
  37838. }
  37839. break;
  37840. }
  37841. };
  37842. /**
  37843. * Applies VertexData created from the imported parameters to the geometry
  37844. * @param parsedVertexData the parsed data from an imported file
  37845. * @param geometry the geometry to apply the VertexData to
  37846. */
  37847. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  37848. var vertexData = new VertexData();
  37849. // positions
  37850. var positions = parsedVertexData.positions;
  37851. if (positions) {
  37852. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  37853. }
  37854. // normals
  37855. var normals = parsedVertexData.normals;
  37856. if (normals) {
  37857. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  37858. }
  37859. // tangents
  37860. var tangents = parsedVertexData.tangents;
  37861. if (tangents) {
  37862. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  37863. }
  37864. // uvs
  37865. var uvs = parsedVertexData.uvs;
  37866. if (uvs) {
  37867. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  37868. }
  37869. // uv2s
  37870. var uv2s = parsedVertexData.uv2s;
  37871. if (uv2s) {
  37872. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  37873. }
  37874. // uv3s
  37875. var uv3s = parsedVertexData.uv3s;
  37876. if (uv3s) {
  37877. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  37878. }
  37879. // uv4s
  37880. var uv4s = parsedVertexData.uv4s;
  37881. if (uv4s) {
  37882. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  37883. }
  37884. // uv5s
  37885. var uv5s = parsedVertexData.uv5s;
  37886. if (uv5s) {
  37887. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  37888. }
  37889. // uv6s
  37890. var uv6s = parsedVertexData.uv6s;
  37891. if (uv6s) {
  37892. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  37893. }
  37894. // colors
  37895. var colors = parsedVertexData.colors;
  37896. if (colors) {
  37897. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  37898. }
  37899. // matricesIndices
  37900. var matricesIndices = parsedVertexData.matricesIndices;
  37901. if (matricesIndices) {
  37902. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  37903. }
  37904. // matricesWeights
  37905. var matricesWeights = parsedVertexData.matricesWeights;
  37906. if (matricesWeights) {
  37907. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  37908. }
  37909. // indices
  37910. var indices = parsedVertexData.indices;
  37911. if (indices) {
  37912. vertexData.indices = indices;
  37913. }
  37914. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  37915. };
  37916. return VertexData;
  37917. }());
  37918. BABYLON.VertexData = VertexData;
  37919. })(BABYLON || (BABYLON = {}));
  37920. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  37921. "use strict";
  37922. var BABYLON;
  37923. (function (BABYLON) {
  37924. /**
  37925. * Class used to store geometry data (vertex buffers + index buffer)
  37926. */
  37927. var Geometry = /** @class */ (function () {
  37928. /**
  37929. * Creates a new geometry
  37930. * @param id defines the unique ID
  37931. * @param scene defines the hosting scene
  37932. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  37933. * @param updatable defines if geometry must be updatable (false by default)
  37934. * @param mesh defines the mesh that will be associated with the geometry
  37935. */
  37936. function Geometry(id, scene, vertexData, updatable, mesh) {
  37937. if (updatable === void 0) { updatable = false; }
  37938. if (mesh === void 0) { mesh = null; }
  37939. /**
  37940. * Gets the delay loading state of the geometry (none by default which means not delayed)
  37941. */
  37942. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  37943. this._totalVertices = 0;
  37944. this._isDisposed = false;
  37945. this._indexBufferIsUpdatable = false;
  37946. this.id = id;
  37947. this._engine = scene.getEngine();
  37948. this._meshes = [];
  37949. this._scene = scene;
  37950. //Init vertex buffer cache
  37951. this._vertexBuffers = {};
  37952. this._indices = [];
  37953. this._updatable = updatable;
  37954. // vertexData
  37955. if (vertexData) {
  37956. this.setAllVerticesData(vertexData, updatable);
  37957. }
  37958. else {
  37959. this._totalVertices = 0;
  37960. this._indices = [];
  37961. }
  37962. if (this._engine.getCaps().vertexArrayObject) {
  37963. this._vertexArrayObjects = {};
  37964. }
  37965. // applyToMesh
  37966. if (mesh) {
  37967. if (mesh.getClassName() === "LinesMesh") {
  37968. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  37969. this._updateExtend();
  37970. }
  37971. this.applyToMesh(mesh);
  37972. mesh.computeWorldMatrix(true);
  37973. }
  37974. }
  37975. Object.defineProperty(Geometry.prototype, "boundingBias", {
  37976. /**
  37977. * 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
  37978. */
  37979. get: function () {
  37980. return this._boundingBias;
  37981. },
  37982. /**
  37983. * 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
  37984. */
  37985. set: function (value) {
  37986. if (this._boundingBias && this._boundingBias.equals(value)) {
  37987. return;
  37988. }
  37989. this._boundingBias = value.clone();
  37990. this._updateBoundingInfo(true, null);
  37991. },
  37992. enumerable: true,
  37993. configurable: true
  37994. });
  37995. /**
  37996. * Static function used to attach a new empty geometry to a mesh
  37997. * @param mesh defines the mesh to attach the geometry to
  37998. * @returns the new {BABYLON.Geometry}
  37999. */
  38000. Geometry.CreateGeometryForMesh = function (mesh) {
  38001. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38002. geometry.applyToMesh(mesh);
  38003. return geometry;
  38004. };
  38005. Object.defineProperty(Geometry.prototype, "extend", {
  38006. /**
  38007. * Gets the current extend of the geometry
  38008. */
  38009. get: function () {
  38010. return this._extend;
  38011. },
  38012. enumerable: true,
  38013. configurable: true
  38014. });
  38015. /**
  38016. * Gets the hosting scene
  38017. * @returns the hosting {BABYLON.Scene}
  38018. */
  38019. Geometry.prototype.getScene = function () {
  38020. return this._scene;
  38021. };
  38022. /**
  38023. * Gets the hosting engine
  38024. * @returns the hosting {BABYLON.Engine}
  38025. */
  38026. Geometry.prototype.getEngine = function () {
  38027. return this._engine;
  38028. };
  38029. /**
  38030. * Defines if the geometry is ready to use
  38031. * @returns true if the geometry is ready to be used
  38032. */
  38033. Geometry.prototype.isReady = function () {
  38034. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38035. };
  38036. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38037. /**
  38038. * Gets a value indicating that the geometry should not be serialized
  38039. */
  38040. get: function () {
  38041. for (var index = 0; index < this._meshes.length; index++) {
  38042. if (!this._meshes[index].doNotSerialize) {
  38043. return false;
  38044. }
  38045. }
  38046. return true;
  38047. },
  38048. enumerable: true,
  38049. configurable: true
  38050. });
  38051. /** @ignore */
  38052. Geometry.prototype._rebuild = function () {
  38053. if (this._vertexArrayObjects) {
  38054. this._vertexArrayObjects = {};
  38055. }
  38056. // Index buffer
  38057. if (this._meshes.length !== 0 && this._indices) {
  38058. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38059. }
  38060. // Vertex buffers
  38061. for (var key in this._vertexBuffers) {
  38062. var vertexBuffer = this._vertexBuffers[key];
  38063. vertexBuffer._rebuild();
  38064. }
  38065. };
  38066. /**
  38067. * Affects all gemetry data in one call
  38068. * @param vertexData defines the geometry data
  38069. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38070. */
  38071. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38072. vertexData.applyToGeometry(this, updatable);
  38073. this.notifyUpdate();
  38074. };
  38075. /**
  38076. * Set specific vertex data
  38077. * @param kind defines the data kind (Position, normal, etc...)
  38078. * @param data defines the vertex data to use
  38079. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38080. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38081. */
  38082. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38083. if (updatable === void 0) { updatable = false; }
  38084. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38085. this.setVerticesBuffer(buffer);
  38086. };
  38087. /**
  38088. * Removes a specific vertex data
  38089. * @param kind defines the data kind (Position, normal, etc...)
  38090. */
  38091. Geometry.prototype.removeVerticesData = function (kind) {
  38092. if (this._vertexBuffers[kind]) {
  38093. this._vertexBuffers[kind].dispose();
  38094. delete this._vertexBuffers[kind];
  38095. }
  38096. };
  38097. /**
  38098. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38099. * @param buffer defines the vertex buffer to use
  38100. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38101. */
  38102. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38103. if (totalVertices === void 0) { totalVertices = null; }
  38104. var kind = buffer.getKind();
  38105. if (this._vertexBuffers[kind]) {
  38106. this._vertexBuffers[kind].dispose();
  38107. }
  38108. this._vertexBuffers[kind] = buffer;
  38109. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38110. var data = buffer.getData();
  38111. if (totalVertices != null) {
  38112. this._totalVertices = totalVertices;
  38113. }
  38114. else {
  38115. if (data != null) {
  38116. this._totalVertices = data.length / (buffer.byteStride / 4);
  38117. }
  38118. }
  38119. this._updateExtend(data);
  38120. this._resetPointsArrayCache();
  38121. var meshes = this._meshes;
  38122. var numOfMeshes = meshes.length;
  38123. for (var index = 0; index < numOfMeshes; index++) {
  38124. var mesh = meshes[index];
  38125. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38126. mesh._createGlobalSubMesh(false);
  38127. mesh.computeWorldMatrix(true);
  38128. }
  38129. }
  38130. this.notifyUpdate(kind);
  38131. if (this._vertexArrayObjects) {
  38132. this._disposeVertexArrayObjects();
  38133. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38134. }
  38135. };
  38136. /**
  38137. * Update a specific vertex buffer
  38138. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38139. * It will do nothing if the buffer is not updatable
  38140. * @param kind defines the data kind (Position, normal, etc...)
  38141. * @param data defines the data to use
  38142. * @param offset defines the offset in the target buffer where to store the data
  38143. * @param useBytes set to true if the offset is in bytes
  38144. */
  38145. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38146. if (useBytes === void 0) { useBytes = false; }
  38147. var vertexBuffer = this.getVertexBuffer(kind);
  38148. if (!vertexBuffer) {
  38149. return;
  38150. }
  38151. vertexBuffer.updateDirectly(data, offset, useBytes);
  38152. this.notifyUpdate(kind);
  38153. };
  38154. /**
  38155. * Update a specific vertex buffer
  38156. * This function will create a new buffer if the current one is not updatable
  38157. * @param kind defines the data kind (Position, normal, etc...)
  38158. * @param data defines the data to use
  38159. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38160. */
  38161. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38162. if (updateExtends === void 0) { updateExtends = false; }
  38163. var vertexBuffer = this.getVertexBuffer(kind);
  38164. if (!vertexBuffer) {
  38165. return;
  38166. }
  38167. vertexBuffer.update(data);
  38168. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38169. this._updateBoundingInfo(updateExtends, data);
  38170. }
  38171. this.notifyUpdate(kind);
  38172. };
  38173. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38174. if (updateExtends) {
  38175. this._updateExtend(data);
  38176. }
  38177. var meshes = this._meshes;
  38178. var numOfMeshes = meshes.length;
  38179. this._resetPointsArrayCache();
  38180. for (var index = 0; index < numOfMeshes; index++) {
  38181. var mesh = meshes[index];
  38182. if (updateExtends) {
  38183. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38184. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38185. var subMesh = mesh.subMeshes[subIndex];
  38186. subMesh.refreshBoundingInfo();
  38187. }
  38188. }
  38189. }
  38190. };
  38191. /** @ignore */
  38192. Geometry.prototype._bind = function (effect, indexToBind) {
  38193. if (!effect) {
  38194. return;
  38195. }
  38196. if (indexToBind === undefined) {
  38197. indexToBind = this._indexBuffer;
  38198. }
  38199. var vbs = this.getVertexBuffers();
  38200. if (!vbs) {
  38201. return;
  38202. }
  38203. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38204. this._engine.bindBuffers(vbs, indexToBind, effect);
  38205. return;
  38206. }
  38207. // Using VAO
  38208. if (!this._vertexArrayObjects[effect.key]) {
  38209. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38210. }
  38211. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38212. };
  38213. /**
  38214. * Gets total number of vertices
  38215. * @returns the total number of vertices
  38216. */
  38217. Geometry.prototype.getTotalVertices = function () {
  38218. if (!this.isReady()) {
  38219. return 0;
  38220. }
  38221. return this._totalVertices;
  38222. };
  38223. /**
  38224. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38225. * @param kind defines the data kind (Position, normal, etc...)
  38226. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38227. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38228. * @returns a float array containing vertex data
  38229. */
  38230. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38231. var vertexBuffer = this.getVertexBuffer(kind);
  38232. if (!vertexBuffer) {
  38233. return null;
  38234. }
  38235. var data = vertexBuffer.getData();
  38236. if (!data) {
  38237. return null;
  38238. }
  38239. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  38240. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38241. var count = this._totalVertices * defaultStride;
  38242. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  38243. var copy_1 = new Array(count);
  38244. vertexBuffer.forEach(count, function (value, index) {
  38245. copy_1[index] = value;
  38246. });
  38247. return copy_1;
  38248. }
  38249. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38250. if (data instanceof Array) {
  38251. var offset = vertexBuffer.byteOffset / 4;
  38252. return BABYLON.Tools.Slice(data, offset, offset + count);
  38253. }
  38254. else if (data instanceof ArrayBuffer) {
  38255. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38256. }
  38257. else {
  38258. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38259. }
  38260. }
  38261. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38262. return BABYLON.Tools.Slice(data);
  38263. }
  38264. return data;
  38265. };
  38266. /**
  38267. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38268. * @param kind defines the data kind (Position, normal, etc...)
  38269. * @returns true if the vertex buffer with the specified kind is updatable
  38270. */
  38271. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38272. var vb = this._vertexBuffers[kind];
  38273. if (!vb) {
  38274. return false;
  38275. }
  38276. return vb.isUpdatable();
  38277. };
  38278. /**
  38279. * Gets a specific vertex buffer
  38280. * @param kind defines the data kind (Position, normal, etc...)
  38281. * @returns a {BABYLON.VertexBuffer}
  38282. */
  38283. Geometry.prototype.getVertexBuffer = function (kind) {
  38284. if (!this.isReady()) {
  38285. return null;
  38286. }
  38287. return this._vertexBuffers[kind];
  38288. };
  38289. /**
  38290. * Returns all vertex buffers
  38291. * @return an object holding all vertex buffers indexed by kind
  38292. */
  38293. Geometry.prototype.getVertexBuffers = function () {
  38294. if (!this.isReady()) {
  38295. return null;
  38296. }
  38297. return this._vertexBuffers;
  38298. };
  38299. /**
  38300. * Gets a boolean indicating if specific vertex buffer is present
  38301. * @param kind defines the data kind (Position, normal, etc...)
  38302. * @returns true if data is present
  38303. */
  38304. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38305. if (!this._vertexBuffers) {
  38306. if (this._delayInfo) {
  38307. return this._delayInfo.indexOf(kind) !== -1;
  38308. }
  38309. return false;
  38310. }
  38311. return this._vertexBuffers[kind] !== undefined;
  38312. };
  38313. /**
  38314. * Gets a list of all attached data kinds (Position, normal, etc...)
  38315. * @returns a list of string containing all kinds
  38316. */
  38317. Geometry.prototype.getVerticesDataKinds = function () {
  38318. var result = [];
  38319. var kind;
  38320. if (!this._vertexBuffers && this._delayInfo) {
  38321. for (kind in this._delayInfo) {
  38322. result.push(kind);
  38323. }
  38324. }
  38325. else {
  38326. for (kind in this._vertexBuffers) {
  38327. result.push(kind);
  38328. }
  38329. }
  38330. return result;
  38331. };
  38332. /**
  38333. * Update index buffer
  38334. * @param indices defines the indices to store in the index buffer
  38335. * @param offset defines the offset in the target buffer where to store the data
  38336. */
  38337. Geometry.prototype.updateIndices = function (indices, offset) {
  38338. if (!this._indexBuffer) {
  38339. return;
  38340. }
  38341. if (!this._indexBufferIsUpdatable) {
  38342. this.setIndices(indices, null, true);
  38343. }
  38344. else {
  38345. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38346. }
  38347. };
  38348. /**
  38349. * Creates a new index buffer
  38350. * @param indices defines the indices to store in the index buffer
  38351. * @param totalVertices defines the total number of vertices (could be null)
  38352. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38353. */
  38354. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38355. if (totalVertices === void 0) { totalVertices = null; }
  38356. if (updatable === void 0) { updatable = false; }
  38357. if (this._indexBuffer) {
  38358. this._engine._releaseBuffer(this._indexBuffer);
  38359. }
  38360. this._disposeVertexArrayObjects();
  38361. this._indices = indices;
  38362. this._indexBufferIsUpdatable = updatable;
  38363. if (this._meshes.length !== 0 && this._indices) {
  38364. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38365. }
  38366. if (totalVertices != undefined) {
  38367. this._totalVertices = totalVertices;
  38368. }
  38369. var meshes = this._meshes;
  38370. var numOfMeshes = meshes.length;
  38371. for (var index = 0; index < numOfMeshes; index++) {
  38372. meshes[index]._createGlobalSubMesh(true);
  38373. }
  38374. this.notifyUpdate();
  38375. };
  38376. /**
  38377. * Return the total number of indices
  38378. * @returns the total number of indices
  38379. */
  38380. Geometry.prototype.getTotalIndices = function () {
  38381. if (!this.isReady()) {
  38382. return 0;
  38383. }
  38384. return this._indices.length;
  38385. };
  38386. /**
  38387. * Gets the index buffer array
  38388. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38389. * @returns the index buffer array
  38390. */
  38391. Geometry.prototype.getIndices = function (copyWhenShared) {
  38392. if (!this.isReady()) {
  38393. return null;
  38394. }
  38395. var orig = this._indices;
  38396. if (!copyWhenShared || this._meshes.length === 1) {
  38397. return orig;
  38398. }
  38399. else {
  38400. var len = orig.length;
  38401. var copy = [];
  38402. for (var i = 0; i < len; i++) {
  38403. copy.push(orig[i]);
  38404. }
  38405. return copy;
  38406. }
  38407. };
  38408. /**
  38409. * Gets the index buffer
  38410. * @return the index buffer
  38411. */
  38412. Geometry.prototype.getIndexBuffer = function () {
  38413. if (!this.isReady()) {
  38414. return null;
  38415. }
  38416. return this._indexBuffer;
  38417. };
  38418. /** @ignore */
  38419. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38420. if (effect === void 0) { effect = null; }
  38421. if (!effect || !this._vertexArrayObjects) {
  38422. return;
  38423. }
  38424. if (this._vertexArrayObjects[effect.key]) {
  38425. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38426. delete this._vertexArrayObjects[effect.key];
  38427. }
  38428. };
  38429. /**
  38430. * Release the associated resources for a specific mesh
  38431. * @param mesh defines the source mesh
  38432. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38433. */
  38434. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38435. var meshes = this._meshes;
  38436. var index = meshes.indexOf(mesh);
  38437. if (index === -1) {
  38438. return;
  38439. }
  38440. meshes.splice(index, 1);
  38441. mesh._geometry = null;
  38442. if (meshes.length === 0 && shouldDispose) {
  38443. this.dispose();
  38444. }
  38445. };
  38446. /**
  38447. * Apply current geometry to a given mesh
  38448. * @param mesh defines the mesh to apply geometry to
  38449. */
  38450. Geometry.prototype.applyToMesh = function (mesh) {
  38451. if (mesh._geometry === this) {
  38452. return;
  38453. }
  38454. var previousGeometry = mesh._geometry;
  38455. if (previousGeometry) {
  38456. previousGeometry.releaseForMesh(mesh);
  38457. }
  38458. var meshes = this._meshes;
  38459. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38460. mesh._geometry = this;
  38461. this._scene.pushGeometry(this);
  38462. meshes.push(mesh);
  38463. if (this.isReady()) {
  38464. this._applyToMesh(mesh);
  38465. }
  38466. else {
  38467. mesh._boundingInfo = this._boundingInfo;
  38468. }
  38469. };
  38470. Geometry.prototype._updateExtend = function (data) {
  38471. if (data === void 0) { data = null; }
  38472. if (!data) {
  38473. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38474. }
  38475. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38476. };
  38477. Geometry.prototype._applyToMesh = function (mesh) {
  38478. var numOfMeshes = this._meshes.length;
  38479. // vertexBuffers
  38480. for (var kind in this._vertexBuffers) {
  38481. if (numOfMeshes === 1) {
  38482. this._vertexBuffers[kind].create();
  38483. }
  38484. var buffer = this._vertexBuffers[kind].getBuffer();
  38485. if (buffer)
  38486. buffer.references = numOfMeshes;
  38487. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38488. if (!this._extend) {
  38489. this._updateExtend();
  38490. }
  38491. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38492. mesh._createGlobalSubMesh(false);
  38493. //bounding info was just created again, world matrix should be applied again.
  38494. mesh._updateBoundingInfo();
  38495. }
  38496. }
  38497. // indexBuffer
  38498. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38499. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38500. }
  38501. if (this._indexBuffer) {
  38502. this._indexBuffer.references = numOfMeshes;
  38503. }
  38504. };
  38505. Geometry.prototype.notifyUpdate = function (kind) {
  38506. if (this.onGeometryUpdated) {
  38507. this.onGeometryUpdated(this, kind);
  38508. }
  38509. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38510. var mesh = _a[_i];
  38511. mesh._markSubMeshesAsAttributesDirty();
  38512. }
  38513. };
  38514. /**
  38515. * Load the geometry if it was flagged as delay loaded
  38516. * @param scene defines the hosting scene
  38517. * @param onLoaded defines a callback called when the geometry is loaded
  38518. */
  38519. Geometry.prototype.load = function (scene, onLoaded) {
  38520. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38521. return;
  38522. }
  38523. if (this.isReady()) {
  38524. if (onLoaded) {
  38525. onLoaded();
  38526. }
  38527. return;
  38528. }
  38529. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38530. this._queueLoad(scene, onLoaded);
  38531. };
  38532. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38533. var _this = this;
  38534. if (!this.delayLoadingFile) {
  38535. return;
  38536. }
  38537. scene._addPendingData(this);
  38538. scene._loadFile(this.delayLoadingFile, function (data) {
  38539. if (!_this._delayLoadingFunction) {
  38540. return;
  38541. }
  38542. _this._delayLoadingFunction(JSON.parse(data), _this);
  38543. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38544. _this._delayInfo = [];
  38545. scene._removePendingData(_this);
  38546. var meshes = _this._meshes;
  38547. var numOfMeshes = meshes.length;
  38548. for (var index = 0; index < numOfMeshes; index++) {
  38549. _this._applyToMesh(meshes[index]);
  38550. }
  38551. if (onLoaded) {
  38552. onLoaded();
  38553. }
  38554. }, undefined, true);
  38555. };
  38556. /**
  38557. * Invert the geometry to move from a right handed system to a left handed one.
  38558. */
  38559. Geometry.prototype.toLeftHanded = function () {
  38560. // Flip faces
  38561. var tIndices = this.getIndices(false);
  38562. if (tIndices != null && tIndices.length > 0) {
  38563. for (var i = 0; i < tIndices.length; i += 3) {
  38564. var tTemp = tIndices[i + 0];
  38565. tIndices[i + 0] = tIndices[i + 2];
  38566. tIndices[i + 2] = tTemp;
  38567. }
  38568. this.setIndices(tIndices);
  38569. }
  38570. // Negate position.z
  38571. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  38572. if (tPositions != null && tPositions.length > 0) {
  38573. for (var i = 0; i < tPositions.length; i += 3) {
  38574. tPositions[i + 2] = -tPositions[i + 2];
  38575. }
  38576. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  38577. }
  38578. // Negate normal.z
  38579. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  38580. if (tNormals != null && tNormals.length > 0) {
  38581. for (var i = 0; i < tNormals.length; i += 3) {
  38582. tNormals[i + 2] = -tNormals[i + 2];
  38583. }
  38584. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  38585. }
  38586. };
  38587. // Cache
  38588. /** @ignore */
  38589. Geometry.prototype._resetPointsArrayCache = function () {
  38590. this._positions = null;
  38591. };
  38592. /** @ignore */
  38593. Geometry.prototype._generatePointsArray = function () {
  38594. if (this._positions)
  38595. return true;
  38596. this._positions = [];
  38597. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38598. if (!data) {
  38599. return false;
  38600. }
  38601. for (var index = 0; index < data.length; index += 3) {
  38602. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  38603. }
  38604. return true;
  38605. };
  38606. /**
  38607. * Gets a value indicating if the geometry is disposed
  38608. * @returns true if the geometry was disposed
  38609. */
  38610. Geometry.prototype.isDisposed = function () {
  38611. return this._isDisposed;
  38612. };
  38613. Geometry.prototype._disposeVertexArrayObjects = function () {
  38614. if (this._vertexArrayObjects) {
  38615. for (var kind in this._vertexArrayObjects) {
  38616. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  38617. }
  38618. this._vertexArrayObjects = {};
  38619. }
  38620. };
  38621. /**
  38622. * Free all associated resources
  38623. */
  38624. Geometry.prototype.dispose = function () {
  38625. var meshes = this._meshes;
  38626. var numOfMeshes = meshes.length;
  38627. var index;
  38628. for (index = 0; index < numOfMeshes; index++) {
  38629. this.releaseForMesh(meshes[index]);
  38630. }
  38631. this._meshes = [];
  38632. this._disposeVertexArrayObjects();
  38633. for (var kind in this._vertexBuffers) {
  38634. this._vertexBuffers[kind].dispose();
  38635. }
  38636. this._vertexBuffers = {};
  38637. this._totalVertices = 0;
  38638. if (this._indexBuffer) {
  38639. this._engine._releaseBuffer(this._indexBuffer);
  38640. }
  38641. this._indexBuffer = null;
  38642. this._indices = [];
  38643. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38644. this.delayLoadingFile = null;
  38645. this._delayLoadingFunction = null;
  38646. this._delayInfo = [];
  38647. this._boundingInfo = null;
  38648. this._scene.removeGeometry(this);
  38649. this._isDisposed = true;
  38650. };
  38651. /**
  38652. * Clone the current geometry into a new geometry
  38653. * @param id defines the unique ID of the new geometry
  38654. * @returns a new geometry object
  38655. */
  38656. Geometry.prototype.copy = function (id) {
  38657. var vertexData = new BABYLON.VertexData();
  38658. vertexData.indices = [];
  38659. var indices = this.getIndices();
  38660. if (indices) {
  38661. for (var index = 0; index < indices.length; index++) {
  38662. vertexData.indices.push(indices[index]);
  38663. }
  38664. }
  38665. var updatable = false;
  38666. var stopChecking = false;
  38667. var kind;
  38668. for (kind in this._vertexBuffers) {
  38669. // using slice() to make a copy of the array and not just reference it
  38670. var data = this.getVerticesData(kind);
  38671. if (data instanceof Float32Array) {
  38672. vertexData.set(new Float32Array(data), kind);
  38673. }
  38674. else {
  38675. vertexData.set(data.slice(0), kind);
  38676. }
  38677. if (!stopChecking) {
  38678. var vb = this.getVertexBuffer(kind);
  38679. if (vb) {
  38680. updatable = vb.isUpdatable();
  38681. stopChecking = !updatable;
  38682. }
  38683. }
  38684. }
  38685. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  38686. geometry.delayLoadState = this.delayLoadState;
  38687. geometry.delayLoadingFile = this.delayLoadingFile;
  38688. geometry._delayLoadingFunction = this._delayLoadingFunction;
  38689. for (kind in this._delayInfo) {
  38690. geometry._delayInfo = geometry._delayInfo || [];
  38691. geometry._delayInfo.push(kind);
  38692. }
  38693. // Bounding info
  38694. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38695. return geometry;
  38696. };
  38697. /**
  38698. * Serialize the current geometry info (and not the vertices data) into a JSON object
  38699. * @return a JSON representation of the current geometry data (without the vertices data)
  38700. */
  38701. Geometry.prototype.serialize = function () {
  38702. var serializationObject = {};
  38703. serializationObject.id = this.id;
  38704. serializationObject.updatable = this._updatable;
  38705. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  38706. serializationObject.tags = BABYLON.Tags.GetTags(this);
  38707. }
  38708. return serializationObject;
  38709. };
  38710. Geometry.prototype.toNumberArray = function (origin) {
  38711. if (Array.isArray(origin)) {
  38712. return origin;
  38713. }
  38714. else {
  38715. return Array.prototype.slice.call(origin);
  38716. }
  38717. };
  38718. /**
  38719. * Serialize all vertices data into a JSON oject
  38720. * @returns a JSON representation of the current geometry data
  38721. */
  38722. Geometry.prototype.serializeVerticeData = function () {
  38723. var serializationObject = this.serialize();
  38724. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38725. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  38726. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  38727. serializationObject.positions._updatable = true;
  38728. }
  38729. }
  38730. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38731. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  38732. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  38733. serializationObject.normals._updatable = true;
  38734. }
  38735. }
  38736. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38737. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  38738. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  38739. serializationObject.tangets._updatable = true;
  38740. }
  38741. }
  38742. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38743. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  38744. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  38745. serializationObject.uvs._updatable = true;
  38746. }
  38747. }
  38748. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38749. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  38750. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  38751. serializationObject.uv2s._updatable = true;
  38752. }
  38753. }
  38754. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38755. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  38756. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  38757. serializationObject.uv3s._updatable = true;
  38758. }
  38759. }
  38760. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38761. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  38762. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  38763. serializationObject.uv4s._updatable = true;
  38764. }
  38765. }
  38766. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38767. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  38768. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  38769. serializationObject.uv5s._updatable = true;
  38770. }
  38771. }
  38772. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38773. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  38774. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  38775. serializationObject.uv6s._updatable = true;
  38776. }
  38777. }
  38778. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38779. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  38780. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  38781. serializationObject.colors._updatable = true;
  38782. }
  38783. }
  38784. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38785. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  38786. serializationObject.matricesIndices._isExpanded = true;
  38787. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38788. serializationObject.matricesIndices._updatable = true;
  38789. }
  38790. }
  38791. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38792. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  38793. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38794. serializationObject.matricesWeights._updatable = true;
  38795. }
  38796. }
  38797. serializationObject.indices = this.toNumberArray(this.getIndices());
  38798. return serializationObject;
  38799. };
  38800. // Statics
  38801. /**
  38802. * Extracts a clone of a mesh geometry
  38803. * @param mesh defines the source mesh
  38804. * @param id defines the unique ID of the new geometry object
  38805. * @returns the new geometry object
  38806. */
  38807. Geometry.ExtractFromMesh = function (mesh, id) {
  38808. var geometry = mesh._geometry;
  38809. if (!geometry) {
  38810. return null;
  38811. }
  38812. return geometry.copy(id);
  38813. };
  38814. /**
  38815. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  38816. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  38817. * Be aware Math.random() could cause collisions, but:
  38818. * "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"
  38819. * @returns a string containing a new GUID
  38820. */
  38821. Geometry.RandomId = function () {
  38822. return BABYLON.Tools.RandomId();
  38823. };
  38824. /** @ignore */
  38825. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  38826. var scene = mesh.getScene();
  38827. // Geometry
  38828. var geometryId = parsedGeometry.geometryId;
  38829. if (geometryId) {
  38830. var geometry = scene.getGeometryByID(geometryId);
  38831. if (geometry) {
  38832. geometry.applyToMesh(mesh);
  38833. }
  38834. }
  38835. else if (parsedGeometry instanceof ArrayBuffer) {
  38836. var binaryInfo = mesh._binaryInfo;
  38837. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  38838. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  38839. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  38840. }
  38841. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  38842. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  38843. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  38844. }
  38845. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  38846. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  38847. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  38848. }
  38849. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  38850. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  38851. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  38852. }
  38853. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  38854. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  38855. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  38856. }
  38857. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  38858. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  38859. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  38860. }
  38861. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  38862. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  38863. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  38864. }
  38865. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  38866. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  38867. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  38868. }
  38869. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  38870. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  38871. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  38872. }
  38873. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  38874. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  38875. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  38876. }
  38877. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  38878. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  38879. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  38880. }
  38881. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  38882. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  38883. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  38884. }
  38885. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  38886. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  38887. mesh.setIndices(indicesData, null);
  38888. }
  38889. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  38890. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  38891. mesh.subMeshes = [];
  38892. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  38893. var materialIndex = subMeshesData[(i * 5) + 0];
  38894. var verticesStart = subMeshesData[(i * 5) + 1];
  38895. var verticesCount = subMeshesData[(i * 5) + 2];
  38896. var indexStart = subMeshesData[(i * 5) + 3];
  38897. var indexCount = subMeshesData[(i * 5) + 4];
  38898. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  38899. }
  38900. }
  38901. }
  38902. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  38903. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  38904. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  38905. if (parsedGeometry.tangents) {
  38906. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  38907. }
  38908. if (parsedGeometry.uvs) {
  38909. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  38910. }
  38911. if (parsedGeometry.uvs2) {
  38912. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  38913. }
  38914. if (parsedGeometry.uvs3) {
  38915. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  38916. }
  38917. if (parsedGeometry.uvs4) {
  38918. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  38919. }
  38920. if (parsedGeometry.uvs5) {
  38921. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  38922. }
  38923. if (parsedGeometry.uvs6) {
  38924. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  38925. }
  38926. if (parsedGeometry.colors) {
  38927. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  38928. }
  38929. if (parsedGeometry.matricesIndices) {
  38930. if (!parsedGeometry.matricesIndices._isExpanded) {
  38931. var floatIndices = [];
  38932. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  38933. var matricesIndex = parsedGeometry.matricesIndices[i];
  38934. floatIndices.push(matricesIndex & 0x000000FF);
  38935. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  38936. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  38937. floatIndices.push(matricesIndex >> 24);
  38938. }
  38939. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  38940. }
  38941. else {
  38942. delete parsedGeometry.matricesIndices._isExpanded;
  38943. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  38944. }
  38945. }
  38946. if (parsedGeometry.matricesIndicesExtra) {
  38947. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  38948. var floatIndices = [];
  38949. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  38950. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  38951. floatIndices.push(matricesIndex & 0x000000FF);
  38952. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  38953. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  38954. floatIndices.push(matricesIndex >> 24);
  38955. }
  38956. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  38957. }
  38958. else {
  38959. delete parsedGeometry.matricesIndices._isExpanded;
  38960. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  38961. }
  38962. }
  38963. if (parsedGeometry.matricesWeights) {
  38964. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  38965. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  38966. }
  38967. if (parsedGeometry.matricesWeightsExtra) {
  38968. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  38969. }
  38970. mesh.setIndices(parsedGeometry.indices, null);
  38971. }
  38972. // SubMeshes
  38973. if (parsedGeometry.subMeshes) {
  38974. mesh.subMeshes = [];
  38975. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  38976. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  38977. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  38978. }
  38979. }
  38980. // Flat shading
  38981. if (mesh._shouldGenerateFlatShading) {
  38982. mesh.convertToFlatShadedMesh();
  38983. delete mesh._shouldGenerateFlatShading;
  38984. }
  38985. // Update
  38986. mesh.computeWorldMatrix(true);
  38987. // Octree
  38988. var sceneOctree = scene.selectionOctree;
  38989. if (sceneOctree !== undefined && sceneOctree !== null) {
  38990. sceneOctree.addMesh(mesh);
  38991. }
  38992. };
  38993. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  38994. var epsilon = 1e-3;
  38995. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  38996. return;
  38997. }
  38998. var noInfluenceBoneIndex = 0.0;
  38999. if (parsedGeometry.skeletonId > -1) {
  39000. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39001. if (!skeleton) {
  39002. return;
  39003. }
  39004. noInfluenceBoneIndex = skeleton.bones.length;
  39005. }
  39006. else {
  39007. return;
  39008. }
  39009. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39010. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39011. var matricesWeights = parsedGeometry.matricesWeights;
  39012. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39013. var influencers = parsedGeometry.numBoneInfluencer;
  39014. var size = matricesWeights.length;
  39015. for (var i = 0; i < size; i += 4) {
  39016. var weight = 0.0;
  39017. var firstZeroWeight = -1;
  39018. for (var j = 0; j < 4; j++) {
  39019. var w = matricesWeights[i + j];
  39020. weight += w;
  39021. if (w < epsilon && firstZeroWeight < 0) {
  39022. firstZeroWeight = j;
  39023. }
  39024. }
  39025. if (matricesWeightsExtra) {
  39026. for (var j = 0; j < 4; j++) {
  39027. var w = matricesWeightsExtra[i + j];
  39028. weight += w;
  39029. if (w < epsilon && firstZeroWeight < 0) {
  39030. firstZeroWeight = j + 4;
  39031. }
  39032. }
  39033. }
  39034. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39035. firstZeroWeight = influencers - 1;
  39036. }
  39037. if (weight > epsilon) {
  39038. var mweight = 1.0 / weight;
  39039. for (var j = 0; j < 4; j++) {
  39040. matricesWeights[i + j] *= mweight;
  39041. }
  39042. if (matricesWeightsExtra) {
  39043. for (var j = 0; j < 4; j++) {
  39044. matricesWeightsExtra[i + j] *= mweight;
  39045. }
  39046. }
  39047. }
  39048. else {
  39049. if (firstZeroWeight >= 4) {
  39050. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39051. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39052. }
  39053. else {
  39054. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39055. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39056. }
  39057. }
  39058. }
  39059. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39060. if (parsedGeometry.matricesWeightsExtra) {
  39061. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39062. }
  39063. };
  39064. /**
  39065. * Create a new geometry from persisted data (Using .babylon file format)
  39066. * @param parsedVertexData defines the persisted data
  39067. * @param scene defines the hosting scene
  39068. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39069. * @returns the new geometry object
  39070. */
  39071. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39072. if (scene.getGeometryByID(parsedVertexData.id)) {
  39073. return null; // null since geometry could be something else than a box...
  39074. }
  39075. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39076. if (BABYLON.Tags) {
  39077. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39078. }
  39079. if (parsedVertexData.delayLoadingFile) {
  39080. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39081. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39082. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39083. geometry._delayInfo = [];
  39084. if (parsedVertexData.hasUVs) {
  39085. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39086. }
  39087. if (parsedVertexData.hasUVs2) {
  39088. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39089. }
  39090. if (parsedVertexData.hasUVs3) {
  39091. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39092. }
  39093. if (parsedVertexData.hasUVs4) {
  39094. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39095. }
  39096. if (parsedVertexData.hasUVs5) {
  39097. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39098. }
  39099. if (parsedVertexData.hasUVs6) {
  39100. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39101. }
  39102. if (parsedVertexData.hasColors) {
  39103. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39104. }
  39105. if (parsedVertexData.hasMatricesIndices) {
  39106. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39107. }
  39108. if (parsedVertexData.hasMatricesWeights) {
  39109. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39110. }
  39111. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39112. }
  39113. else {
  39114. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39115. }
  39116. scene.pushGeometry(geometry, true);
  39117. return geometry;
  39118. };
  39119. return Geometry;
  39120. }());
  39121. BABYLON.Geometry = Geometry;
  39122. // Primitives
  39123. /// Abstract class
  39124. /**
  39125. * Abstract class used to provide common services for all typed geometries
  39126. */
  39127. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39128. __extends(_PrimitiveGeometry, _super);
  39129. /**
  39130. * Creates a new typed geometry
  39131. * @param id defines the unique ID of the geometry
  39132. * @param scene defines the hosting scene
  39133. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39134. * @param mesh defines the hosting mesh (can be null)
  39135. */
  39136. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39137. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39138. if (mesh === void 0) { mesh = null; }
  39139. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39140. _this._canBeRegenerated = _canBeRegenerated;
  39141. _this._beingRegenerated = true;
  39142. _this.regenerate();
  39143. _this._beingRegenerated = false;
  39144. return _this;
  39145. }
  39146. /**
  39147. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39148. * @returns true if the geometry can be regenerated
  39149. */
  39150. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39151. return this._canBeRegenerated;
  39152. };
  39153. /**
  39154. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39155. */
  39156. _PrimitiveGeometry.prototype.regenerate = function () {
  39157. if (!this._canBeRegenerated) {
  39158. return;
  39159. }
  39160. this._beingRegenerated = true;
  39161. this.setAllVerticesData(this._regenerateVertexData(), false);
  39162. this._beingRegenerated = false;
  39163. };
  39164. /**
  39165. * Clone the geometry
  39166. * @param id defines the unique ID of the new geometry
  39167. * @returns the new geometry
  39168. */
  39169. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39170. return _super.prototype.copy.call(this, id);
  39171. };
  39172. // overrides
  39173. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39174. if (!this._beingRegenerated) {
  39175. return;
  39176. }
  39177. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39178. };
  39179. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39180. if (!this._beingRegenerated) {
  39181. return;
  39182. }
  39183. _super.prototype.setVerticesData.call(this, kind, data, false);
  39184. };
  39185. // to override
  39186. /** @ignore */
  39187. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39188. throw new Error("Abstract method");
  39189. };
  39190. _PrimitiveGeometry.prototype.copy = function (id) {
  39191. throw new Error("Must be overriden in sub-classes.");
  39192. };
  39193. _PrimitiveGeometry.prototype.serialize = function () {
  39194. var serializationObject = _super.prototype.serialize.call(this);
  39195. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39196. return serializationObject;
  39197. };
  39198. return _PrimitiveGeometry;
  39199. }(Geometry));
  39200. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39201. /**
  39202. * Creates a ribbon geometry
  39203. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39204. */
  39205. var RibbonGeometry = /** @class */ (function (_super) {
  39206. __extends(RibbonGeometry, _super);
  39207. /**
  39208. * Creates a ribbon geometry
  39209. * @param id defines the unique ID of the geometry
  39210. * @param scene defines the hosting scene
  39211. * @param pathArray defines the array of paths to use
  39212. * @param closeArray defines if the last path and the first path must be joined
  39213. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39214. * @param offset defines the offset between points
  39215. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39216. * @param mesh defines the hosting mesh (can be null)
  39217. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39218. */
  39219. function RibbonGeometry(id, scene,
  39220. /**
  39221. * Defines the array of paths to use
  39222. */
  39223. pathArray,
  39224. /**
  39225. * Defines if the last and first points of each path in your pathArray must be joined
  39226. */
  39227. closeArray,
  39228. /**
  39229. * Defines if the last and first points of each path in your pathArray must be joined
  39230. */
  39231. closePath,
  39232. /**
  39233. * Defines the offset between points
  39234. */
  39235. offset, canBeRegenerated, mesh,
  39236. /**
  39237. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39238. */
  39239. side) {
  39240. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39241. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39242. _this.pathArray = pathArray;
  39243. _this.closeArray = closeArray;
  39244. _this.closePath = closePath;
  39245. _this.offset = offset;
  39246. _this.side = side;
  39247. return _this;
  39248. }
  39249. /** @ignore */
  39250. RibbonGeometry.prototype._regenerateVertexData = function () {
  39251. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39252. };
  39253. RibbonGeometry.prototype.copy = function (id) {
  39254. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39255. };
  39256. return RibbonGeometry;
  39257. }(_PrimitiveGeometry));
  39258. BABYLON.RibbonGeometry = RibbonGeometry;
  39259. /**
  39260. * Creates a box geometry
  39261. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39262. */
  39263. var BoxGeometry = /** @class */ (function (_super) {
  39264. __extends(BoxGeometry, _super);
  39265. /**
  39266. * Creates a box geometry
  39267. * @param id defines the unique ID of the geometry
  39268. * @param scene defines the hosting scene
  39269. * @param size defines the zise of the box (width, height and depth are the same)
  39270. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39271. * @param mesh defines the hosting mesh (can be null)
  39272. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39273. */
  39274. function BoxGeometry(id, scene,
  39275. /**
  39276. * Defines the zise of the box (width, height and depth are the same)
  39277. */
  39278. size, canBeRegenerated, mesh,
  39279. /**
  39280. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39281. */
  39282. side) {
  39283. if (mesh === void 0) { mesh = null; }
  39284. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39285. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39286. _this.size = size;
  39287. _this.side = side;
  39288. return _this;
  39289. }
  39290. BoxGeometry.prototype._regenerateVertexData = function () {
  39291. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39292. };
  39293. BoxGeometry.prototype.copy = function (id) {
  39294. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39295. };
  39296. BoxGeometry.prototype.serialize = function () {
  39297. var serializationObject = _super.prototype.serialize.call(this);
  39298. serializationObject.size = this.size;
  39299. return serializationObject;
  39300. };
  39301. BoxGeometry.Parse = function (parsedBox, scene) {
  39302. if (scene.getGeometryByID(parsedBox.id)) {
  39303. return null; // null since geometry could be something else than a box...
  39304. }
  39305. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39306. if (BABYLON.Tags) {
  39307. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39308. }
  39309. scene.pushGeometry(box, true);
  39310. return box;
  39311. };
  39312. return BoxGeometry;
  39313. }(_PrimitiveGeometry));
  39314. BABYLON.BoxGeometry = BoxGeometry;
  39315. /**
  39316. * Creates a sphere geometry
  39317. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39318. */
  39319. var SphereGeometry = /** @class */ (function (_super) {
  39320. __extends(SphereGeometry, _super);
  39321. /**
  39322. * Create a new sphere geometry
  39323. * @param id defines the unique ID of the geometry
  39324. * @param scene defines the hosting scene
  39325. * @param segments defines the number of segments to use to create the sphere
  39326. * @param diameter defines the diameter of the sphere
  39327. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39328. * @param mesh defines the hosting mesh (can be null)
  39329. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39330. */
  39331. function SphereGeometry(id, scene,
  39332. /**
  39333. * Defines the number of segments to use to create the sphere
  39334. */
  39335. segments,
  39336. /**
  39337. * Defines the diameter of the sphere
  39338. */
  39339. diameter, canBeRegenerated, mesh,
  39340. /**
  39341. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39342. */
  39343. side) {
  39344. if (mesh === void 0) { mesh = null; }
  39345. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39346. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39347. _this.segments = segments;
  39348. _this.diameter = diameter;
  39349. _this.side = side;
  39350. return _this;
  39351. }
  39352. SphereGeometry.prototype._regenerateVertexData = function () {
  39353. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39354. };
  39355. SphereGeometry.prototype.copy = function (id) {
  39356. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39357. };
  39358. SphereGeometry.prototype.serialize = function () {
  39359. var serializationObject = _super.prototype.serialize.call(this);
  39360. serializationObject.segments = this.segments;
  39361. serializationObject.diameter = this.diameter;
  39362. return serializationObject;
  39363. };
  39364. SphereGeometry.Parse = function (parsedSphere, scene) {
  39365. if (scene.getGeometryByID(parsedSphere.id)) {
  39366. return null; // null since geometry could be something else than a sphere...
  39367. }
  39368. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39369. if (BABYLON.Tags) {
  39370. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39371. }
  39372. scene.pushGeometry(sphere, true);
  39373. return sphere;
  39374. };
  39375. return SphereGeometry;
  39376. }(_PrimitiveGeometry));
  39377. BABYLON.SphereGeometry = SphereGeometry;
  39378. /**
  39379. * Creates a disc geometry
  39380. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39381. */
  39382. var DiscGeometry = /** @class */ (function (_super) {
  39383. __extends(DiscGeometry, _super);
  39384. /**
  39385. * Creates a new disc geometry
  39386. * @param id defines the unique ID of the geometry
  39387. * @param scene defines the hosting scene
  39388. * @param radius defines the radius of the disc
  39389. * @param tessellation defines the tesselation factor to apply to the disc
  39390. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39391. * @param mesh defines the hosting mesh (can be null)
  39392. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39393. */
  39394. function DiscGeometry(id, scene,
  39395. /**
  39396. * Defines the radius of the disc
  39397. */
  39398. radius,
  39399. /**
  39400. * Defines the tesselation factor to apply to the disc
  39401. */
  39402. tessellation, canBeRegenerated, mesh,
  39403. /**
  39404. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39405. */
  39406. side) {
  39407. if (mesh === void 0) { mesh = null; }
  39408. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39409. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39410. _this.radius = radius;
  39411. _this.tessellation = tessellation;
  39412. _this.side = side;
  39413. return _this;
  39414. }
  39415. DiscGeometry.prototype._regenerateVertexData = function () {
  39416. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39417. };
  39418. DiscGeometry.prototype.copy = function (id) {
  39419. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39420. };
  39421. return DiscGeometry;
  39422. }(_PrimitiveGeometry));
  39423. BABYLON.DiscGeometry = DiscGeometry;
  39424. /**
  39425. * Creates a new cylinder geometry
  39426. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39427. */
  39428. var CylinderGeometry = /** @class */ (function (_super) {
  39429. __extends(CylinderGeometry, _super);
  39430. /**
  39431. * Creates a new cylinder geometry
  39432. * @param id defines the unique ID of the geometry
  39433. * @param scene defines the hosting scene
  39434. * @param height defines the height of the cylinder
  39435. * @param diameterTop defines the diameter of the cylinder's top cap
  39436. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39437. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39438. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39439. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39440. * @param mesh defines the hosting mesh (can be null)
  39441. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39442. */
  39443. function CylinderGeometry(id, scene,
  39444. /**
  39445. * Defines the height of the cylinder
  39446. */
  39447. height,
  39448. /**
  39449. * Defines the diameter of the cylinder's top cap
  39450. */
  39451. diameterTop,
  39452. /**
  39453. * Defines the diameter of the cylinder's bottom cap
  39454. */
  39455. diameterBottom,
  39456. /**
  39457. * Defines the tessellation factor to apply to the cylinder
  39458. */
  39459. tessellation,
  39460. /**
  39461. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39462. */
  39463. subdivisions, canBeRegenerated, mesh,
  39464. /**
  39465. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39466. */
  39467. side) {
  39468. if (subdivisions === void 0) { subdivisions = 1; }
  39469. if (mesh === void 0) { mesh = null; }
  39470. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39471. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39472. _this.height = height;
  39473. _this.diameterTop = diameterTop;
  39474. _this.diameterBottom = diameterBottom;
  39475. _this.tessellation = tessellation;
  39476. _this.subdivisions = subdivisions;
  39477. _this.side = side;
  39478. return _this;
  39479. }
  39480. CylinderGeometry.prototype._regenerateVertexData = function () {
  39481. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39482. };
  39483. CylinderGeometry.prototype.copy = function (id) {
  39484. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39485. };
  39486. CylinderGeometry.prototype.serialize = function () {
  39487. var serializationObject = _super.prototype.serialize.call(this);
  39488. serializationObject.height = this.height;
  39489. serializationObject.diameterTop = this.diameterTop;
  39490. serializationObject.diameterBottom = this.diameterBottom;
  39491. serializationObject.tessellation = this.tessellation;
  39492. return serializationObject;
  39493. };
  39494. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39495. if (scene.getGeometryByID(parsedCylinder.id)) {
  39496. return null; // null since geometry could be something else than a cylinder...
  39497. }
  39498. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39499. if (BABYLON.Tags) {
  39500. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39501. }
  39502. scene.pushGeometry(cylinder, true);
  39503. return cylinder;
  39504. };
  39505. return CylinderGeometry;
  39506. }(_PrimitiveGeometry));
  39507. BABYLON.CylinderGeometry = CylinderGeometry;
  39508. /**
  39509. * Creates a new torus geometry
  39510. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39511. */
  39512. var TorusGeometry = /** @class */ (function (_super) {
  39513. __extends(TorusGeometry, _super);
  39514. /**
  39515. * Creates a new torus geometry
  39516. * @param id defines the unique ID of the geometry
  39517. * @param scene defines the hosting scene
  39518. * @param diameter defines the diameter of the torus
  39519. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39520. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39521. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39522. * @param mesh defines the hosting mesh (can be null)
  39523. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39524. */
  39525. function TorusGeometry(id, scene,
  39526. /**
  39527. * Defines the diameter of the torus
  39528. */
  39529. diameter,
  39530. /**
  39531. * Defines the thickness of the torus (ie. internal diameter)
  39532. */
  39533. thickness,
  39534. /**
  39535. * Defines the tesselation factor to apply to the torus
  39536. */
  39537. tessellation, canBeRegenerated, mesh,
  39538. /**
  39539. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39540. */
  39541. side) {
  39542. if (mesh === void 0) { mesh = null; }
  39543. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39544. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39545. _this.diameter = diameter;
  39546. _this.thickness = thickness;
  39547. _this.tessellation = tessellation;
  39548. _this.side = side;
  39549. return _this;
  39550. }
  39551. TorusGeometry.prototype._regenerateVertexData = function () {
  39552. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  39553. };
  39554. TorusGeometry.prototype.copy = function (id) {
  39555. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  39556. };
  39557. TorusGeometry.prototype.serialize = function () {
  39558. var serializationObject = _super.prototype.serialize.call(this);
  39559. serializationObject.diameter = this.diameter;
  39560. serializationObject.thickness = this.thickness;
  39561. serializationObject.tessellation = this.tessellation;
  39562. return serializationObject;
  39563. };
  39564. TorusGeometry.Parse = function (parsedTorus, scene) {
  39565. if (scene.getGeometryByID(parsedTorus.id)) {
  39566. return null; // null since geometry could be something else than a torus...
  39567. }
  39568. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  39569. if (BABYLON.Tags) {
  39570. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  39571. }
  39572. scene.pushGeometry(torus, true);
  39573. return torus;
  39574. };
  39575. return TorusGeometry;
  39576. }(_PrimitiveGeometry));
  39577. BABYLON.TorusGeometry = TorusGeometry;
  39578. /**
  39579. * Creates a new ground geometry
  39580. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  39581. */
  39582. var GroundGeometry = /** @class */ (function (_super) {
  39583. __extends(GroundGeometry, _super);
  39584. /**
  39585. * Creates a new ground geometry
  39586. * @param id defines the unique ID of the geometry
  39587. * @param scene defines the hosting scene
  39588. * @param width defines the width of the ground
  39589. * @param height defines the height of the ground
  39590. * @param subdivisions defines the subdivisions to apply to the ground
  39591. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39592. * @param mesh defines the hosting mesh (can be null)
  39593. */
  39594. function GroundGeometry(id, scene,
  39595. /**
  39596. * Defines the width of the ground
  39597. */
  39598. width,
  39599. /**
  39600. * Defines the height of the ground
  39601. */
  39602. height,
  39603. /**
  39604. * Defines the subdivisions to apply to the ground
  39605. */
  39606. subdivisions, canBeRegenerated, mesh) {
  39607. if (mesh === void 0) { mesh = null; }
  39608. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39609. _this.width = width;
  39610. _this.height = height;
  39611. _this.subdivisions = subdivisions;
  39612. return _this;
  39613. }
  39614. GroundGeometry.prototype._regenerateVertexData = function () {
  39615. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  39616. };
  39617. GroundGeometry.prototype.copy = function (id) {
  39618. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  39619. };
  39620. GroundGeometry.prototype.serialize = function () {
  39621. var serializationObject = _super.prototype.serialize.call(this);
  39622. serializationObject.width = this.width;
  39623. serializationObject.height = this.height;
  39624. serializationObject.subdivisions = this.subdivisions;
  39625. return serializationObject;
  39626. };
  39627. GroundGeometry.Parse = function (parsedGround, scene) {
  39628. if (scene.getGeometryByID(parsedGround.id)) {
  39629. return null; // null since geometry could be something else than a ground...
  39630. }
  39631. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  39632. if (BABYLON.Tags) {
  39633. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  39634. }
  39635. scene.pushGeometry(ground, true);
  39636. return ground;
  39637. };
  39638. return GroundGeometry;
  39639. }(_PrimitiveGeometry));
  39640. BABYLON.GroundGeometry = GroundGeometry;
  39641. /**
  39642. * Creates a tiled ground geometry
  39643. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  39644. */
  39645. var TiledGroundGeometry = /** @class */ (function (_super) {
  39646. __extends(TiledGroundGeometry, _super);
  39647. /**
  39648. * Creates a tiled ground geometry
  39649. * @param id defines the unique ID of the geometry
  39650. * @param scene defines the hosting scene
  39651. * @param xmin defines the minimum value on X axis
  39652. * @param zmin defines the minimum value on Z axis
  39653. * @param xmax defines the maximum value on X axis
  39654. * @param zmax defines the maximum value on Z axis
  39655. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  39656. * @param precision defines the precision to use when computing the tiles
  39657. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39658. * @param mesh defines the hosting mesh (can be null)
  39659. */
  39660. function TiledGroundGeometry(id, scene,
  39661. /**
  39662. * Defines the minimum value on X axis
  39663. */
  39664. xmin,
  39665. /**
  39666. * Defines the minimum value on Z axis
  39667. */
  39668. zmin,
  39669. /**
  39670. * Defines the maximum value on X axis
  39671. */
  39672. xmax,
  39673. /**
  39674. * Defines the maximum value on Z axis
  39675. */
  39676. zmax,
  39677. /**
  39678. * Defines the subdivisions to apply to the ground
  39679. */
  39680. subdivisions,
  39681. /**
  39682. * Defines the precision to use when computing the tiles
  39683. */
  39684. precision, canBeRegenerated, mesh) {
  39685. if (mesh === void 0) { mesh = null; }
  39686. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39687. _this.xmin = xmin;
  39688. _this.zmin = zmin;
  39689. _this.xmax = xmax;
  39690. _this.zmax = zmax;
  39691. _this.subdivisions = subdivisions;
  39692. _this.precision = precision;
  39693. return _this;
  39694. }
  39695. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  39696. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  39697. };
  39698. TiledGroundGeometry.prototype.copy = function (id) {
  39699. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  39700. };
  39701. return TiledGroundGeometry;
  39702. }(_PrimitiveGeometry));
  39703. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  39704. /**
  39705. * Creates a plane geometry
  39706. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  39707. */
  39708. var PlaneGeometry = /** @class */ (function (_super) {
  39709. __extends(PlaneGeometry, _super);
  39710. /**
  39711. * Creates a plane geometry
  39712. * @param id defines the unique ID of the geometry
  39713. * @param scene defines the hosting scene
  39714. * @param size defines the size of the plane (width === height)
  39715. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39716. * @param mesh defines the hosting mesh (can be null)
  39717. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39718. */
  39719. function PlaneGeometry(id, scene,
  39720. /**
  39721. * Defines the size of the plane (width === height)
  39722. */
  39723. size, canBeRegenerated, mesh,
  39724. /**
  39725. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39726. */
  39727. side) {
  39728. if (mesh === void 0) { mesh = null; }
  39729. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39730. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39731. _this.size = size;
  39732. _this.side = side;
  39733. return _this;
  39734. }
  39735. PlaneGeometry.prototype._regenerateVertexData = function () {
  39736. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  39737. };
  39738. PlaneGeometry.prototype.copy = function (id) {
  39739. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  39740. };
  39741. PlaneGeometry.prototype.serialize = function () {
  39742. var serializationObject = _super.prototype.serialize.call(this);
  39743. serializationObject.size = this.size;
  39744. return serializationObject;
  39745. };
  39746. PlaneGeometry.Parse = function (parsedPlane, scene) {
  39747. if (scene.getGeometryByID(parsedPlane.id)) {
  39748. return null; // null since geometry could be something else than a ground...
  39749. }
  39750. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  39751. if (BABYLON.Tags) {
  39752. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  39753. }
  39754. scene.pushGeometry(plane, true);
  39755. return plane;
  39756. };
  39757. return PlaneGeometry;
  39758. }(_PrimitiveGeometry));
  39759. BABYLON.PlaneGeometry = PlaneGeometry;
  39760. /**
  39761. * Creates a torus knot geometry
  39762. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  39763. */
  39764. var TorusKnotGeometry = /** @class */ (function (_super) {
  39765. __extends(TorusKnotGeometry, _super);
  39766. /**
  39767. * Creates a torus knot geometry
  39768. * @param id defines the unique ID of the geometry
  39769. * @param scene defines the hosting scene
  39770. * @param radius defines the radius of the torus knot
  39771. * @param tube defines the thickness of the torus knot tube
  39772. * @param radialSegments defines the number of radial segments
  39773. * @param tubularSegments defines the number of tubular segments
  39774. * @param p defines the first number of windings
  39775. * @param q defines the second number of windings
  39776. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39777. * @param mesh defines the hosting mesh (can be null)
  39778. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39779. */
  39780. function TorusKnotGeometry(id, scene,
  39781. /**
  39782. * Defines the radius of the torus knot
  39783. */
  39784. radius,
  39785. /**
  39786. * Defines the thickness of the torus knot tube
  39787. */
  39788. tube,
  39789. /**
  39790. * Defines the number of radial segments
  39791. */
  39792. radialSegments,
  39793. /**
  39794. * Defines the number of tubular segments
  39795. */
  39796. tubularSegments,
  39797. /**
  39798. * Defines the first number of windings
  39799. */
  39800. p,
  39801. /**
  39802. * Defines the second number of windings
  39803. */
  39804. q, canBeRegenerated, mesh,
  39805. /**
  39806. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39807. */
  39808. side) {
  39809. if (mesh === void 0) { mesh = null; }
  39810. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39811. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39812. _this.radius = radius;
  39813. _this.tube = tube;
  39814. _this.radialSegments = radialSegments;
  39815. _this.tubularSegments = tubularSegments;
  39816. _this.p = p;
  39817. _this.q = q;
  39818. _this.side = side;
  39819. return _this;
  39820. }
  39821. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  39822. 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 });
  39823. };
  39824. TorusKnotGeometry.prototype.copy = function (id) {
  39825. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  39826. };
  39827. TorusKnotGeometry.prototype.serialize = function () {
  39828. var serializationObject = _super.prototype.serialize.call(this);
  39829. serializationObject.radius = this.radius;
  39830. serializationObject.tube = this.tube;
  39831. serializationObject.radialSegments = this.radialSegments;
  39832. serializationObject.tubularSegments = this.tubularSegments;
  39833. serializationObject.p = this.p;
  39834. serializationObject.q = this.q;
  39835. return serializationObject;
  39836. };
  39837. ;
  39838. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  39839. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  39840. return null; // null since geometry could be something else than a ground...
  39841. }
  39842. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  39843. if (BABYLON.Tags) {
  39844. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  39845. }
  39846. scene.pushGeometry(torusKnot, true);
  39847. return torusKnot;
  39848. };
  39849. return TorusKnotGeometry;
  39850. }(_PrimitiveGeometry));
  39851. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  39852. //}
  39853. })(BABYLON || (BABYLON = {}));
  39854. //# sourceMappingURL=babylon.geometry.js.map
  39855. "use strict";
  39856. var BABYLON;
  39857. (function (BABYLON) {
  39858. /**
  39859. * PostProcessManager is used to manage one or more post processes or post process pipelines
  39860. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  39861. */
  39862. var PostProcessManager = /** @class */ (function () {
  39863. /**
  39864. * Creates a new instance PostProcess
  39865. * @param scene The scene that the post process is associated with.
  39866. */
  39867. function PostProcessManager(scene) {
  39868. this._vertexBuffers = {};
  39869. this._scene = scene;
  39870. }
  39871. PostProcessManager.prototype._prepareBuffers = function () {
  39872. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  39873. return;
  39874. }
  39875. // VBO
  39876. var vertices = [];
  39877. vertices.push(1, 1);
  39878. vertices.push(-1, 1);
  39879. vertices.push(-1, -1);
  39880. vertices.push(1, -1);
  39881. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  39882. this._buildIndexBuffer();
  39883. };
  39884. PostProcessManager.prototype._buildIndexBuffer = function () {
  39885. // Indices
  39886. var indices = [];
  39887. indices.push(0);
  39888. indices.push(1);
  39889. indices.push(2);
  39890. indices.push(0);
  39891. indices.push(2);
  39892. indices.push(3);
  39893. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  39894. };
  39895. /**
  39896. * Rebuilds the vertex buffers of the manager.
  39897. */
  39898. PostProcessManager.prototype._rebuild = function () {
  39899. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39900. if (!vb) {
  39901. return;
  39902. }
  39903. vb._rebuild();
  39904. this._buildIndexBuffer();
  39905. };
  39906. // Methods
  39907. /**
  39908. * Prepares a frame to be run through a post process.
  39909. * @param sourceTexture The input texture to the post procesess. (default: null)
  39910. * @param postProcesses An array of post processes to be run. (default: null)
  39911. * @returns True if the post processes were able to be run.
  39912. */
  39913. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  39914. if (sourceTexture === void 0) { sourceTexture = null; }
  39915. if (postProcesses === void 0) { postProcesses = null; }
  39916. var camera = this._scene.activeCamera;
  39917. if (!camera) {
  39918. return false;
  39919. }
  39920. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  39921. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  39922. return false;
  39923. }
  39924. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  39925. return true;
  39926. };
  39927. /**
  39928. * Manually render a set of post processes to a texture.
  39929. * @param postProcesses An array of post processes to be run.
  39930. * @param targetTexture The target texture to render to.
  39931. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  39932. */
  39933. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  39934. if (targetTexture === void 0) { targetTexture = null; }
  39935. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  39936. var engine = this._scene.getEngine();
  39937. for (var index = 0; index < postProcesses.length; index++) {
  39938. if (index < postProcesses.length - 1) {
  39939. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  39940. }
  39941. else {
  39942. if (targetTexture) {
  39943. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  39944. }
  39945. else {
  39946. engine.restoreDefaultFramebuffer();
  39947. }
  39948. }
  39949. var pp = postProcesses[index];
  39950. var effect = pp.apply();
  39951. if (effect) {
  39952. pp.onBeforeRenderObservable.notifyObservers(effect);
  39953. // VBOs
  39954. this._prepareBuffers();
  39955. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39956. // Draw order
  39957. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  39958. pp.onAfterRenderObservable.notifyObservers(effect);
  39959. }
  39960. }
  39961. // Restore depth buffer
  39962. engine.setDepthBuffer(true);
  39963. engine.setDepthWrite(true);
  39964. };
  39965. /**
  39966. * Finalize the result of the output of the postprocesses.
  39967. * @param doNotPresent If true the result will not be displayed to the screen.
  39968. * @param targetTexture The target texture to render to.
  39969. * @param faceIndex The index of the face to bind the target texture to.
  39970. * @param postProcesses The array of post processes to render.
  39971. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  39972. */
  39973. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  39974. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  39975. var camera = this._scene.activeCamera;
  39976. if (!camera) {
  39977. return;
  39978. }
  39979. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  39980. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  39981. return;
  39982. }
  39983. var engine = this._scene.getEngine();
  39984. for (var index = 0, len = postProcesses.length; index < len; index++) {
  39985. var pp = postProcesses[index];
  39986. if (index < len - 1) {
  39987. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  39988. }
  39989. else {
  39990. if (targetTexture) {
  39991. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  39992. pp._outputTexture = targetTexture;
  39993. }
  39994. else {
  39995. engine.restoreDefaultFramebuffer();
  39996. pp._outputTexture = null;
  39997. }
  39998. }
  39999. if (doNotPresent) {
  40000. break;
  40001. }
  40002. var effect = pp.apply();
  40003. if (effect) {
  40004. pp.onBeforeRenderObservable.notifyObservers(effect);
  40005. // VBOs
  40006. this._prepareBuffers();
  40007. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40008. // Draw order
  40009. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40010. pp.onAfterRenderObservable.notifyObservers(effect);
  40011. }
  40012. }
  40013. // Restore states
  40014. engine.setDepthBuffer(true);
  40015. engine.setDepthWrite(true);
  40016. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40017. };
  40018. /**
  40019. * Disposes of the post process manager.
  40020. */
  40021. PostProcessManager.prototype.dispose = function () {
  40022. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40023. if (buffer) {
  40024. buffer.dispose();
  40025. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40026. }
  40027. if (this._indexBuffer) {
  40028. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40029. this._indexBuffer = null;
  40030. }
  40031. };
  40032. return PostProcessManager;
  40033. }());
  40034. BABYLON.PostProcessManager = PostProcessManager;
  40035. })(BABYLON || (BABYLON = {}));
  40036. //# sourceMappingURL=babylon.postProcessManager.js.map
  40037. "use strict";
  40038. var BABYLON;
  40039. (function (BABYLON) {
  40040. /**
  40041. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40042. */
  40043. var PerformanceMonitor = /** @class */ (function () {
  40044. /**
  40045. * constructor
  40046. * @param frameSampleSize The number of samples required to saturate the sliding window
  40047. */
  40048. function PerformanceMonitor(frameSampleSize) {
  40049. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40050. this._enabled = true;
  40051. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40052. }
  40053. /**
  40054. * Samples current frame
  40055. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40056. */
  40057. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40058. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40059. if (!this._enabled)
  40060. return;
  40061. if (this._lastFrameTimeMs != null) {
  40062. var dt = timeMs - this._lastFrameTimeMs;
  40063. this._rollingFrameTime.add(dt);
  40064. }
  40065. this._lastFrameTimeMs = timeMs;
  40066. };
  40067. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40068. /**
  40069. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40070. * @return Average frame time in milliseconds
  40071. */
  40072. get: function () {
  40073. return this._rollingFrameTime.average;
  40074. },
  40075. enumerable: true,
  40076. configurable: true
  40077. });
  40078. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40079. /**
  40080. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40081. * @return Frame time variance in milliseconds squared
  40082. */
  40083. get: function () {
  40084. return this._rollingFrameTime.variance;
  40085. },
  40086. enumerable: true,
  40087. configurable: true
  40088. });
  40089. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40090. /**
  40091. * Returns the frame time of the most recent frame
  40092. * @return Frame time in milliseconds
  40093. */
  40094. get: function () {
  40095. return this._rollingFrameTime.history(0);
  40096. },
  40097. enumerable: true,
  40098. configurable: true
  40099. });
  40100. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40101. /**
  40102. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40103. * @return Framerate in frames per second
  40104. */
  40105. get: function () {
  40106. return 1000.0 / this._rollingFrameTime.average;
  40107. },
  40108. enumerable: true,
  40109. configurable: true
  40110. });
  40111. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40112. /**
  40113. * Returns the average framerate in frames per second using the most recent frame time
  40114. * @return Framerate in frames per second
  40115. */
  40116. get: function () {
  40117. var history = this._rollingFrameTime.history(0);
  40118. if (history === 0) {
  40119. return 0;
  40120. }
  40121. return 1000.0 / history;
  40122. },
  40123. enumerable: true,
  40124. configurable: true
  40125. });
  40126. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40127. /**
  40128. * Returns true if enough samples have been taken to completely fill the sliding window
  40129. * @return true if saturated
  40130. */
  40131. get: function () {
  40132. return this._rollingFrameTime.isSaturated();
  40133. },
  40134. enumerable: true,
  40135. configurable: true
  40136. });
  40137. /**
  40138. * Enables contributions to the sliding window sample set
  40139. */
  40140. PerformanceMonitor.prototype.enable = function () {
  40141. this._enabled = true;
  40142. };
  40143. /**
  40144. * Disables contributions to the sliding window sample set
  40145. * Samples will not be interpolated over the disabled period
  40146. */
  40147. PerformanceMonitor.prototype.disable = function () {
  40148. this._enabled = false;
  40149. //clear last sample to avoid interpolating over the disabled period when next enabled
  40150. this._lastFrameTimeMs = null;
  40151. };
  40152. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40153. /**
  40154. * Returns true if sampling is enabled
  40155. * @return true if enabled
  40156. */
  40157. get: function () {
  40158. return this._enabled;
  40159. },
  40160. enumerable: true,
  40161. configurable: true
  40162. });
  40163. /**
  40164. * Resets performance monitor
  40165. */
  40166. PerformanceMonitor.prototype.reset = function () {
  40167. //clear last sample to avoid interpolating over the disabled period when next enabled
  40168. this._lastFrameTimeMs = null;
  40169. //wipe record
  40170. this._rollingFrameTime.reset();
  40171. };
  40172. return PerformanceMonitor;
  40173. }());
  40174. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40175. /**
  40176. * RollingAverage
  40177. *
  40178. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40179. */
  40180. var RollingAverage = /** @class */ (function () {
  40181. /**
  40182. * constructor
  40183. * @param length The number of samples required to saturate the sliding window
  40184. */
  40185. function RollingAverage(length) {
  40186. this._samples = new Array(length);
  40187. this.reset();
  40188. }
  40189. /**
  40190. * Adds a sample to the sample set
  40191. * @param v The sample value
  40192. */
  40193. RollingAverage.prototype.add = function (v) {
  40194. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40195. var delta;
  40196. //we need to check if we've already wrapped round
  40197. if (this.isSaturated()) {
  40198. //remove bottom of stack from mean
  40199. var bottomValue = this._samples[this._pos];
  40200. delta = bottomValue - this.average;
  40201. this.average -= delta / (this._sampleCount - 1);
  40202. this._m2 -= delta * (bottomValue - this.average);
  40203. }
  40204. else {
  40205. this._sampleCount++;
  40206. }
  40207. //add new value to mean
  40208. delta = v - this.average;
  40209. this.average += delta / (this._sampleCount);
  40210. this._m2 += delta * (v - this.average);
  40211. //set the new variance
  40212. this.variance = this._m2 / (this._sampleCount - 1);
  40213. this._samples[this._pos] = v;
  40214. this._pos++;
  40215. this._pos %= this._samples.length; //positive wrap around
  40216. };
  40217. /**
  40218. * Returns previously added values or null if outside of history or outside the sliding window domain
  40219. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40220. * @return Value previously recorded with add() or null if outside of range
  40221. */
  40222. RollingAverage.prototype.history = function (i) {
  40223. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40224. return 0;
  40225. }
  40226. var i0 = this._wrapPosition(this._pos - 1.0);
  40227. return this._samples[this._wrapPosition(i0 - i)];
  40228. };
  40229. /**
  40230. * Returns true if enough samples have been taken to completely fill the sliding window
  40231. * @return true if sample-set saturated
  40232. */
  40233. RollingAverage.prototype.isSaturated = function () {
  40234. return this._sampleCount >= this._samples.length;
  40235. };
  40236. /**
  40237. * Resets the rolling average (equivalent to 0 samples taken so far)
  40238. */
  40239. RollingAverage.prototype.reset = function () {
  40240. this.average = 0;
  40241. this.variance = 0;
  40242. this._sampleCount = 0;
  40243. this._pos = 0;
  40244. this._m2 = 0;
  40245. };
  40246. /**
  40247. * Wraps a value around the sample range boundaries
  40248. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40249. * @return Wrapped position in sample range
  40250. */
  40251. RollingAverage.prototype._wrapPosition = function (i) {
  40252. var max = this._samples.length;
  40253. return ((i % max) + max) % max;
  40254. };
  40255. return RollingAverage;
  40256. }());
  40257. BABYLON.RollingAverage = RollingAverage;
  40258. })(BABYLON || (BABYLON = {}));
  40259. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40260. "use strict";
  40261. var BABYLON;
  40262. (function (BABYLON) {
  40263. /**
  40264. * This groups together the common properties used for image processing either in direct forward pass
  40265. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40266. * or not.
  40267. */
  40268. var ImageProcessingConfiguration = /** @class */ (function () {
  40269. function ImageProcessingConfiguration() {
  40270. /**
  40271. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40272. */
  40273. this.colorCurves = new BABYLON.ColorCurves();
  40274. this._colorCurvesEnabled = false;
  40275. this._colorGradingEnabled = false;
  40276. this._colorGradingWithGreenDepth = true;
  40277. this._colorGradingBGR = true;
  40278. this._exposure = 1.0;
  40279. this._toneMappingEnabled = false;
  40280. this._contrast = 1.0;
  40281. /**
  40282. * Vignette stretch size.
  40283. */
  40284. this.vignetteStretch = 0;
  40285. /**
  40286. * Vignette centre X Offset.
  40287. */
  40288. this.vignetteCentreX = 0;
  40289. /**
  40290. * Vignette centre Y Offset.
  40291. */
  40292. this.vignetteCentreY = 0;
  40293. /**
  40294. * Vignette weight or intensity of the vignette effect.
  40295. */
  40296. this.vignetteWeight = 1.5;
  40297. /**
  40298. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40299. * if vignetteEnabled is set to true.
  40300. */
  40301. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40302. /**
  40303. * Camera field of view used by the Vignette effect.
  40304. */
  40305. this.vignetteCameraFov = 0.5;
  40306. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40307. this._vignetteEnabled = false;
  40308. this._applyByPostProcess = false;
  40309. this._isEnabled = true;
  40310. /**
  40311. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40312. */
  40313. this.onUpdateParameters = new BABYLON.Observable();
  40314. }
  40315. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40316. /**
  40317. * Gets wether the color curves effect is enabled.
  40318. */
  40319. get: function () {
  40320. return this._colorCurvesEnabled;
  40321. },
  40322. /**
  40323. * Sets wether the color curves effect is enabled.
  40324. */
  40325. set: function (value) {
  40326. if (this._colorCurvesEnabled === value) {
  40327. return;
  40328. }
  40329. this._colorCurvesEnabled = value;
  40330. this._updateParameters();
  40331. },
  40332. enumerable: true,
  40333. configurable: true
  40334. });
  40335. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40336. /**
  40337. * Gets wether the color grading effect is enabled.
  40338. */
  40339. get: function () {
  40340. return this._colorGradingEnabled;
  40341. },
  40342. /**
  40343. * Sets wether the color grading effect is enabled.
  40344. */
  40345. set: function (value) {
  40346. if (this._colorGradingEnabled === value) {
  40347. return;
  40348. }
  40349. this._colorGradingEnabled = value;
  40350. this._updateParameters();
  40351. },
  40352. enumerable: true,
  40353. configurable: true
  40354. });
  40355. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40356. /**
  40357. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40358. */
  40359. get: function () {
  40360. return this._colorGradingWithGreenDepth;
  40361. },
  40362. /**
  40363. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40364. */
  40365. set: function (value) {
  40366. if (this._colorGradingWithGreenDepth === value) {
  40367. return;
  40368. }
  40369. this._colorGradingWithGreenDepth = value;
  40370. this._updateParameters();
  40371. },
  40372. enumerable: true,
  40373. configurable: true
  40374. });
  40375. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40376. /**
  40377. * Gets wether the color grading texture contains BGR values.
  40378. */
  40379. get: function () {
  40380. return this._colorGradingBGR;
  40381. },
  40382. /**
  40383. * Sets wether the color grading texture contains BGR values.
  40384. */
  40385. set: function (value) {
  40386. if (this._colorGradingBGR === value) {
  40387. return;
  40388. }
  40389. this._colorGradingBGR = value;
  40390. this._updateParameters();
  40391. },
  40392. enumerable: true,
  40393. configurable: true
  40394. });
  40395. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40396. /**
  40397. * Gets the Exposure used in the effect.
  40398. */
  40399. get: function () {
  40400. return this._exposure;
  40401. },
  40402. /**
  40403. * Sets the Exposure used in the effect.
  40404. */
  40405. set: function (value) {
  40406. if (this._exposure === value) {
  40407. return;
  40408. }
  40409. this._exposure = value;
  40410. this._updateParameters();
  40411. },
  40412. enumerable: true,
  40413. configurable: true
  40414. });
  40415. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40416. /**
  40417. * Gets wether the tone mapping effect is enabled.
  40418. */
  40419. get: function () {
  40420. return this._toneMappingEnabled;
  40421. },
  40422. /**
  40423. * Sets wether the tone mapping effect is enabled.
  40424. */
  40425. set: function (value) {
  40426. if (this._toneMappingEnabled === value) {
  40427. return;
  40428. }
  40429. this._toneMappingEnabled = value;
  40430. this._updateParameters();
  40431. },
  40432. enumerable: true,
  40433. configurable: true
  40434. });
  40435. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40436. /**
  40437. * Gets the contrast used in the effect.
  40438. */
  40439. get: function () {
  40440. return this._contrast;
  40441. },
  40442. /**
  40443. * Sets the contrast used in the effect.
  40444. */
  40445. set: function (value) {
  40446. if (this._contrast === value) {
  40447. return;
  40448. }
  40449. this._contrast = value;
  40450. this._updateParameters();
  40451. },
  40452. enumerable: true,
  40453. configurable: true
  40454. });
  40455. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40456. /**
  40457. * Gets the vignette blend mode allowing different kind of effect.
  40458. */
  40459. get: function () {
  40460. return this._vignetteBlendMode;
  40461. },
  40462. /**
  40463. * Sets the vignette blend mode allowing different kind of effect.
  40464. */
  40465. set: function (value) {
  40466. if (this._vignetteBlendMode === value) {
  40467. return;
  40468. }
  40469. this._vignetteBlendMode = value;
  40470. this._updateParameters();
  40471. },
  40472. enumerable: true,
  40473. configurable: true
  40474. });
  40475. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40476. /**
  40477. * Gets wether the vignette effect is enabled.
  40478. */
  40479. get: function () {
  40480. return this._vignetteEnabled;
  40481. },
  40482. /**
  40483. * Sets wether the vignette effect is enabled.
  40484. */
  40485. set: function (value) {
  40486. if (this._vignetteEnabled === value) {
  40487. return;
  40488. }
  40489. this._vignetteEnabled = value;
  40490. this._updateParameters();
  40491. },
  40492. enumerable: true,
  40493. configurable: true
  40494. });
  40495. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  40496. /**
  40497. * Gets wether the image processing is applied through a post process or not.
  40498. */
  40499. get: function () {
  40500. return this._applyByPostProcess;
  40501. },
  40502. /**
  40503. * Sets wether the image processing is applied through a post process or not.
  40504. */
  40505. set: function (value) {
  40506. if (this._applyByPostProcess === value) {
  40507. return;
  40508. }
  40509. this._applyByPostProcess = value;
  40510. this._updateParameters();
  40511. },
  40512. enumerable: true,
  40513. configurable: true
  40514. });
  40515. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  40516. /**
  40517. * Gets wether the image processing is enabled or not.
  40518. */
  40519. get: function () {
  40520. return this._isEnabled;
  40521. },
  40522. /**
  40523. * Sets wether the image processing is enabled or not.
  40524. */
  40525. set: function (value) {
  40526. if (this._isEnabled === value) {
  40527. return;
  40528. }
  40529. this._isEnabled = value;
  40530. this._updateParameters();
  40531. },
  40532. enumerable: true,
  40533. configurable: true
  40534. });
  40535. /**
  40536. * Method called each time the image processing information changes requires to recompile the effect.
  40537. */
  40538. ImageProcessingConfiguration.prototype._updateParameters = function () {
  40539. this.onUpdateParameters.notifyObservers(this);
  40540. };
  40541. ImageProcessingConfiguration.prototype.getClassName = function () {
  40542. return "ImageProcessingConfiguration";
  40543. };
  40544. /**
  40545. * Prepare the list of uniforms associated with the Image Processing effects.
  40546. * @param uniformsList The list of uniforms used in the effect
  40547. * @param defines the list of defines currently in use
  40548. */
  40549. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  40550. if (defines.EXPOSURE) {
  40551. uniforms.push("exposureLinear");
  40552. }
  40553. if (defines.CONTRAST) {
  40554. uniforms.push("contrast");
  40555. }
  40556. if (defines.COLORGRADING) {
  40557. uniforms.push("colorTransformSettings");
  40558. }
  40559. if (defines.VIGNETTE) {
  40560. uniforms.push("vInverseScreenSize");
  40561. uniforms.push("vignetteSettings1");
  40562. uniforms.push("vignetteSettings2");
  40563. }
  40564. if (defines.COLORCURVES) {
  40565. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  40566. }
  40567. };
  40568. /**
  40569. * Prepare the list of samplers associated with the Image Processing effects.
  40570. * @param uniformsList The list of uniforms used in the effect
  40571. * @param defines the list of defines currently in use
  40572. */
  40573. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  40574. if (defines.COLORGRADING) {
  40575. samplersList.push("txColorTransform");
  40576. }
  40577. };
  40578. /**
  40579. * Prepare the list of defines associated to the shader.
  40580. * @param defines the list of defines to complete
  40581. */
  40582. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  40583. if (forPostProcess === void 0) { forPostProcess = false; }
  40584. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  40585. defines.VIGNETTE = false;
  40586. defines.TONEMAPPING = false;
  40587. defines.CONTRAST = false;
  40588. defines.EXPOSURE = false;
  40589. defines.COLORCURVES = false;
  40590. defines.COLORGRADING = false;
  40591. defines.COLORGRADING3D = false;
  40592. defines.IMAGEPROCESSING = false;
  40593. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  40594. return;
  40595. }
  40596. defines.VIGNETTE = this.vignetteEnabled;
  40597. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  40598. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  40599. defines.TONEMAPPING = this.toneMappingEnabled;
  40600. defines.CONTRAST = (this.contrast !== 1.0);
  40601. defines.EXPOSURE = (this.exposure !== 1.0);
  40602. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  40603. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  40604. if (defines.COLORGRADING) {
  40605. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  40606. }
  40607. else {
  40608. defines.COLORGRADING3D = false;
  40609. }
  40610. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  40611. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  40612. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  40613. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  40614. };
  40615. /**
  40616. * Returns true if all the image processing information are ready.
  40617. */
  40618. ImageProcessingConfiguration.prototype.isReady = function () {
  40619. // Color Grading texure can not be none blocking.
  40620. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  40621. };
  40622. /**
  40623. * Binds the image processing to the shader.
  40624. * @param effect The effect to bind to
  40625. */
  40626. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  40627. if (aspectRatio === void 0) { aspectRatio = 1; }
  40628. // Color Curves
  40629. if (this._colorCurvesEnabled && this.colorCurves) {
  40630. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  40631. }
  40632. // Vignette
  40633. if (this._vignetteEnabled) {
  40634. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  40635. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  40636. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  40637. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  40638. var vignetteScaleX = vignetteScaleY * aspectRatio;
  40639. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  40640. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  40641. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  40642. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  40643. var vignettePower = -2.0 * this.vignetteWeight;
  40644. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  40645. }
  40646. // Exposure
  40647. effect.setFloat("exposureLinear", this.exposure);
  40648. // Contrast
  40649. effect.setFloat("contrast", this.contrast);
  40650. // Color transform settings
  40651. if (this.colorGradingTexture) {
  40652. effect.setTexture("txColorTransform", this.colorGradingTexture);
  40653. var textureSize = this.colorGradingTexture.getSize().height;
  40654. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  40655. 0.5 / textureSize, // textureOffset
  40656. textureSize, // textureSize
  40657. this.colorGradingTexture.level // weight
  40658. );
  40659. }
  40660. };
  40661. /**
  40662. * Clones the current image processing instance.
  40663. * @return The cloned image processing
  40664. */
  40665. ImageProcessingConfiguration.prototype.clone = function () {
  40666. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  40667. };
  40668. /**
  40669. * Serializes the current image processing instance to a json representation.
  40670. * @return a JSON representation
  40671. */
  40672. ImageProcessingConfiguration.prototype.serialize = function () {
  40673. return BABYLON.SerializationHelper.Serialize(this);
  40674. };
  40675. /**
  40676. * Parses the image processing from a json representation.
  40677. * @param source the JSON source to parse
  40678. * @return The parsed image processing
  40679. */
  40680. ImageProcessingConfiguration.Parse = function (source) {
  40681. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  40682. };
  40683. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  40684. /**
  40685. * Used to apply the vignette as a mix with the pixel color.
  40686. */
  40687. get: function () {
  40688. return this._VIGNETTEMODE_MULTIPLY;
  40689. },
  40690. enumerable: true,
  40691. configurable: true
  40692. });
  40693. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  40694. /**
  40695. * Used to apply the vignette as a replacement of the pixel color.
  40696. */
  40697. get: function () {
  40698. return this._VIGNETTEMODE_OPAQUE;
  40699. },
  40700. enumerable: true,
  40701. configurable: true
  40702. });
  40703. // Static constants associated to the image processing.
  40704. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  40705. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  40706. __decorate([
  40707. BABYLON.serializeAsColorCurves()
  40708. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  40709. __decorate([
  40710. BABYLON.serialize()
  40711. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  40712. __decorate([
  40713. BABYLON.serializeAsTexture()
  40714. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  40715. __decorate([
  40716. BABYLON.serialize()
  40717. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  40718. __decorate([
  40719. BABYLON.serialize()
  40720. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  40721. __decorate([
  40722. BABYLON.serialize()
  40723. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  40724. __decorate([
  40725. BABYLON.serialize()
  40726. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  40727. __decorate([
  40728. BABYLON.serialize()
  40729. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  40730. __decorate([
  40731. BABYLON.serialize()
  40732. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  40733. __decorate([
  40734. BABYLON.serialize()
  40735. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  40736. __decorate([
  40737. BABYLON.serialize()
  40738. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  40739. __decorate([
  40740. BABYLON.serialize()
  40741. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  40742. __decorate([
  40743. BABYLON.serialize()
  40744. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  40745. __decorate([
  40746. BABYLON.serializeAsColor4()
  40747. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  40748. __decorate([
  40749. BABYLON.serialize()
  40750. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  40751. __decorate([
  40752. BABYLON.serialize()
  40753. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  40754. __decorate([
  40755. BABYLON.serialize()
  40756. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  40757. __decorate([
  40758. BABYLON.serialize()
  40759. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  40760. __decorate([
  40761. BABYLON.serialize()
  40762. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  40763. return ImageProcessingConfiguration;
  40764. }());
  40765. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  40766. })(BABYLON || (BABYLON = {}));
  40767. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  40768. "use strict";
  40769. var BABYLON;
  40770. (function (BABYLON) {
  40771. /**
  40772. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  40773. * It can help converting any input color in a desired output one. This can then be used to create effects
  40774. * from sepia, black and white to sixties or futuristic rendering...
  40775. *
  40776. * The only supported format is currently 3dl.
  40777. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  40778. */
  40779. var ColorGradingTexture = /** @class */ (function (_super) {
  40780. __extends(ColorGradingTexture, _super);
  40781. /**
  40782. * Instantiates a ColorGradingTexture from the following parameters.
  40783. *
  40784. * @param url The location of the color gradind data (currently only supporting 3dl)
  40785. * @param scene The scene the texture will be used in
  40786. */
  40787. function ColorGradingTexture(url, scene) {
  40788. var _this = _super.call(this, scene) || this;
  40789. if (!url) {
  40790. return _this;
  40791. }
  40792. _this._engine = scene.getEngine();
  40793. _this._textureMatrix = BABYLON.Matrix.Identity();
  40794. _this.name = url;
  40795. _this.url = url;
  40796. _this.hasAlpha = false;
  40797. _this.isCube = false;
  40798. _this.is3D = _this._engine.webGLVersion > 1;
  40799. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40800. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40801. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40802. _this.anisotropicFilteringLevel = 1;
  40803. _this._texture = _this._getFromCache(url, true);
  40804. if (!_this._texture) {
  40805. if (!scene.useDelayedTextureLoading) {
  40806. _this.loadTexture();
  40807. }
  40808. else {
  40809. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40810. }
  40811. }
  40812. return _this;
  40813. }
  40814. /**
  40815. * Returns the texture matrix used in most of the material.
  40816. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  40817. */
  40818. ColorGradingTexture.prototype.getTextureMatrix = function () {
  40819. return this._textureMatrix;
  40820. };
  40821. /**
  40822. * Occurs when the file being loaded is a .3dl LUT file.
  40823. */
  40824. ColorGradingTexture.prototype.load3dlTexture = function () {
  40825. var engine = this._engine;
  40826. var texture;
  40827. if (engine.webGLVersion === 1) {
  40828. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40829. }
  40830. else {
  40831. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40832. }
  40833. this._texture = texture;
  40834. var callback = function (text) {
  40835. if (typeof text !== "string") {
  40836. return;
  40837. }
  40838. var data = null;
  40839. var tempData = null;
  40840. var line;
  40841. var lines = text.split('\n');
  40842. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  40843. var maxColor = 0;
  40844. for (var i = 0; i < lines.length; i++) {
  40845. line = lines[i];
  40846. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  40847. continue;
  40848. if (line.indexOf('#') === 0)
  40849. continue;
  40850. var words = line.split(" ");
  40851. if (size === 0) {
  40852. // Number of space + one
  40853. size = words.length;
  40854. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  40855. tempData = new Float32Array(size * size * size * 4);
  40856. continue;
  40857. }
  40858. if (size != 0) {
  40859. var r = Math.max(parseInt(words[0]), 0);
  40860. var g = Math.max(parseInt(words[1]), 0);
  40861. var b = Math.max(parseInt(words[2]), 0);
  40862. maxColor = Math.max(r, maxColor);
  40863. maxColor = Math.max(g, maxColor);
  40864. maxColor = Math.max(b, maxColor);
  40865. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  40866. if (tempData) {
  40867. tempData[pixelStorageIndex + 0] = r;
  40868. tempData[pixelStorageIndex + 1] = g;
  40869. tempData[pixelStorageIndex + 2] = b;
  40870. }
  40871. pixelIndexSlice++;
  40872. if (pixelIndexSlice % size == 0) {
  40873. pixelIndexH++;
  40874. pixelIndexSlice = 0;
  40875. if (pixelIndexH % size == 0) {
  40876. pixelIndexW++;
  40877. pixelIndexH = 0;
  40878. }
  40879. }
  40880. }
  40881. }
  40882. if (tempData && data) {
  40883. for (var i = 0; i < tempData.length; i++) {
  40884. if (i > 0 && (i + 1) % 4 === 0) {
  40885. data[i] = 255;
  40886. }
  40887. else {
  40888. var value = tempData[i];
  40889. data[i] = (value / maxColor * 255);
  40890. }
  40891. }
  40892. }
  40893. if (texture.is3D) {
  40894. texture.updateSize(size, size, size);
  40895. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  40896. }
  40897. else {
  40898. texture.updateSize(size * size, size);
  40899. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  40900. }
  40901. };
  40902. var scene = this.getScene();
  40903. if (scene) {
  40904. scene._loadFile(this.url, callback);
  40905. }
  40906. else {
  40907. this._engine._loadFile(this.url, callback);
  40908. }
  40909. return this._texture;
  40910. };
  40911. /**
  40912. * Starts the loading process of the texture.
  40913. */
  40914. ColorGradingTexture.prototype.loadTexture = function () {
  40915. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  40916. this.load3dlTexture();
  40917. }
  40918. };
  40919. /**
  40920. * Clones the color gradind texture.
  40921. */
  40922. ColorGradingTexture.prototype.clone = function () {
  40923. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  40924. // Base texture
  40925. newTexture.level = this.level;
  40926. return newTexture;
  40927. };
  40928. /**
  40929. * Called during delayed load for textures.
  40930. */
  40931. ColorGradingTexture.prototype.delayLoad = function () {
  40932. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  40933. return;
  40934. }
  40935. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40936. this._texture = this._getFromCache(this.url, true);
  40937. if (!this._texture) {
  40938. this.loadTexture();
  40939. }
  40940. };
  40941. /**
  40942. * Parses a color grading texture serialized by Babylon.
  40943. * @param parsedTexture The texture information being parsedTexture
  40944. * @param scene The scene to load the texture in
  40945. * @param rootUrl The root url of the data assets to load
  40946. * @return A color gradind texture
  40947. */
  40948. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  40949. var texture = null;
  40950. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  40951. texture = new ColorGradingTexture(parsedTexture.name, scene);
  40952. texture.name = parsedTexture.name;
  40953. texture.level = parsedTexture.level;
  40954. }
  40955. return texture;
  40956. };
  40957. /**
  40958. * Serializes the LUT texture to json format.
  40959. */
  40960. ColorGradingTexture.prototype.serialize = function () {
  40961. if (!this.name) {
  40962. return null;
  40963. }
  40964. var serializationObject = {};
  40965. serializationObject.name = this.name;
  40966. serializationObject.level = this.level;
  40967. serializationObject.customType = "BABYLON.ColorGradingTexture";
  40968. return serializationObject;
  40969. };
  40970. /**
  40971. * Empty line regex stored for GC.
  40972. */
  40973. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  40974. return ColorGradingTexture;
  40975. }(BABYLON.BaseTexture));
  40976. BABYLON.ColorGradingTexture = ColorGradingTexture;
  40977. })(BABYLON || (BABYLON = {}));
  40978. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  40979. "use strict";
  40980. var BABYLON;
  40981. (function (BABYLON) {
  40982. /**
  40983. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  40984. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  40985. * 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;
  40986. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  40987. */
  40988. var ColorCurves = /** @class */ (function () {
  40989. function ColorCurves() {
  40990. this._dirty = true;
  40991. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  40992. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  40993. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  40994. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  40995. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  40996. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  40997. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  40998. this._globalHue = 30;
  40999. this._globalDensity = 0;
  41000. this._globalSaturation = 0;
  41001. this._globalExposure = 0;
  41002. this._highlightsHue = 30;
  41003. this._highlightsDensity = 0;
  41004. this._highlightsSaturation = 0;
  41005. this._highlightsExposure = 0;
  41006. this._midtonesHue = 30;
  41007. this._midtonesDensity = 0;
  41008. this._midtonesSaturation = 0;
  41009. this._midtonesExposure = 0;
  41010. this._shadowsHue = 30;
  41011. this._shadowsDensity = 0;
  41012. this._shadowsSaturation = 0;
  41013. this._shadowsExposure = 0;
  41014. }
  41015. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41016. /**
  41017. * Gets the global Hue value.
  41018. * 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).
  41019. */
  41020. get: function () {
  41021. return this._globalHue;
  41022. },
  41023. /**
  41024. * Sets the global Hue value.
  41025. * 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).
  41026. */
  41027. set: function (value) {
  41028. this._globalHue = value;
  41029. this._dirty = true;
  41030. },
  41031. enumerable: true,
  41032. configurable: true
  41033. });
  41034. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41035. /**
  41036. * Gets the global Density value.
  41037. * 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.
  41038. * Values less than zero provide a filter of opposite hue.
  41039. */
  41040. get: function () {
  41041. return this._globalDensity;
  41042. },
  41043. /**
  41044. * Sets the global Density value.
  41045. * 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.
  41046. * Values less than zero provide a filter of opposite hue.
  41047. */
  41048. set: function (value) {
  41049. this._globalDensity = value;
  41050. this._dirty = true;
  41051. },
  41052. enumerable: true,
  41053. configurable: true
  41054. });
  41055. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41056. /**
  41057. * Gets the global Saturation value.
  41058. * 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.
  41059. */
  41060. get: function () {
  41061. return this._globalSaturation;
  41062. },
  41063. /**
  41064. * Sets the global Saturation value.
  41065. * 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.
  41066. */
  41067. set: function (value) {
  41068. this._globalSaturation = value;
  41069. this._dirty = true;
  41070. },
  41071. enumerable: true,
  41072. configurable: true
  41073. });
  41074. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41075. /**
  41076. * Gets the highlights Hue value.
  41077. * 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).
  41078. */
  41079. get: function () {
  41080. return this._highlightsHue;
  41081. },
  41082. /**
  41083. * Sets the highlights Hue value.
  41084. * 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).
  41085. */
  41086. set: function (value) {
  41087. this._highlightsHue = value;
  41088. this._dirty = true;
  41089. },
  41090. enumerable: true,
  41091. configurable: true
  41092. });
  41093. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41094. /**
  41095. * Gets the highlights Density value.
  41096. * 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.
  41097. * Values less than zero provide a filter of opposite hue.
  41098. */
  41099. get: function () {
  41100. return this._highlightsDensity;
  41101. },
  41102. /**
  41103. * Sets the highlights Density value.
  41104. * 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.
  41105. * Values less than zero provide a filter of opposite hue.
  41106. */
  41107. set: function (value) {
  41108. this._highlightsDensity = value;
  41109. this._dirty = true;
  41110. },
  41111. enumerable: true,
  41112. configurable: true
  41113. });
  41114. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41115. /**
  41116. * Gets the highlights Saturation 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 saturation and negative values decrease saturation.
  41118. */
  41119. get: function () {
  41120. return this._highlightsSaturation;
  41121. },
  41122. /**
  41123. * Sets the highlights Saturation 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 saturation and negative values decrease saturation.
  41125. */
  41126. set: function (value) {
  41127. this._highlightsSaturation = value;
  41128. this._dirty = true;
  41129. },
  41130. enumerable: true,
  41131. configurable: true
  41132. });
  41133. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41134. /**
  41135. * Gets the highlights Exposure value.
  41136. * 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.
  41137. */
  41138. get: function () {
  41139. return this._highlightsExposure;
  41140. },
  41141. /**
  41142. * Sets the highlights Exposure value.
  41143. * 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.
  41144. */
  41145. set: function (value) {
  41146. this._highlightsExposure = value;
  41147. this._dirty = true;
  41148. },
  41149. enumerable: true,
  41150. configurable: true
  41151. });
  41152. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41153. /**
  41154. * Gets the midtones Hue value.
  41155. * 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).
  41156. */
  41157. get: function () {
  41158. return this._midtonesHue;
  41159. },
  41160. /**
  41161. * Sets the midtones Hue value.
  41162. * 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).
  41163. */
  41164. set: function (value) {
  41165. this._midtonesHue = value;
  41166. this._dirty = true;
  41167. },
  41168. enumerable: true,
  41169. configurable: true
  41170. });
  41171. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41172. /**
  41173. * Gets the midtones Density value.
  41174. * 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.
  41175. * Values less than zero provide a filter of opposite hue.
  41176. */
  41177. get: function () {
  41178. return this._midtonesDensity;
  41179. },
  41180. /**
  41181. * Sets the midtones Density value.
  41182. * 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.
  41183. * Values less than zero provide a filter of opposite hue.
  41184. */
  41185. set: function (value) {
  41186. this._midtonesDensity = value;
  41187. this._dirty = true;
  41188. },
  41189. enumerable: true,
  41190. configurable: true
  41191. });
  41192. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41193. /**
  41194. * Gets the midtones Saturation 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 saturation and negative values decrease saturation.
  41196. */
  41197. get: function () {
  41198. return this._midtonesSaturation;
  41199. },
  41200. /**
  41201. * Sets the midtones Saturation 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 saturation and negative values decrease saturation.
  41203. */
  41204. set: function (value) {
  41205. this._midtonesSaturation = value;
  41206. this._dirty = true;
  41207. },
  41208. enumerable: true,
  41209. configurable: true
  41210. });
  41211. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41212. /**
  41213. * Gets the midtones Exposure value.
  41214. * 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.
  41215. */
  41216. get: function () {
  41217. return this._midtonesExposure;
  41218. },
  41219. /**
  41220. * Sets the midtones Exposure value.
  41221. * 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.
  41222. */
  41223. set: function (value) {
  41224. this._midtonesExposure = value;
  41225. this._dirty = true;
  41226. },
  41227. enumerable: true,
  41228. configurable: true
  41229. });
  41230. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41231. /**
  41232. * Gets the shadows Hue value.
  41233. * 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).
  41234. */
  41235. get: function () {
  41236. return this._shadowsHue;
  41237. },
  41238. /**
  41239. * Sets the shadows Hue value.
  41240. * 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).
  41241. */
  41242. set: function (value) {
  41243. this._shadowsHue = value;
  41244. this._dirty = true;
  41245. },
  41246. enumerable: true,
  41247. configurable: true
  41248. });
  41249. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41250. /**
  41251. * Gets the shadows Density value.
  41252. * 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.
  41253. * Values less than zero provide a filter of opposite hue.
  41254. */
  41255. get: function () {
  41256. return this._shadowsDensity;
  41257. },
  41258. /**
  41259. * Sets the shadows Density value.
  41260. * 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.
  41261. * Values less than zero provide a filter of opposite hue.
  41262. */
  41263. set: function (value) {
  41264. this._shadowsDensity = value;
  41265. this._dirty = true;
  41266. },
  41267. enumerable: true,
  41268. configurable: true
  41269. });
  41270. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41271. /**
  41272. * Gets the shadows Saturation value.
  41273. * 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.
  41274. */
  41275. get: function () {
  41276. return this._shadowsSaturation;
  41277. },
  41278. /**
  41279. * Sets the shadows Saturation value.
  41280. * 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.
  41281. */
  41282. set: function (value) {
  41283. this._shadowsSaturation = value;
  41284. this._dirty = true;
  41285. },
  41286. enumerable: true,
  41287. configurable: true
  41288. });
  41289. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41290. /**
  41291. * Gets the shadows Exposure value.
  41292. * 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.
  41293. */
  41294. get: function () {
  41295. return this._shadowsExposure;
  41296. },
  41297. /**
  41298. * Sets the shadows Exposure value.
  41299. * 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.
  41300. */
  41301. set: function (value) {
  41302. this._shadowsExposure = value;
  41303. this._dirty = true;
  41304. },
  41305. enumerable: true,
  41306. configurable: true
  41307. });
  41308. ColorCurves.prototype.getClassName = function () {
  41309. return "ColorCurves";
  41310. };
  41311. /**
  41312. * Binds the color curves to the shader.
  41313. * @param colorCurves The color curve to bind
  41314. * @param effect The effect to bind to
  41315. */
  41316. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41317. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41318. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41319. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41320. if (colorCurves._dirty) {
  41321. colorCurves._dirty = false;
  41322. // Fill in global info.
  41323. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41324. // Compute highlights info.
  41325. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41326. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41327. // Compute midtones info.
  41328. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41329. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41330. // Compute shadows info.
  41331. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41332. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41333. // Compute deltas (neutral is midtones).
  41334. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41335. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41336. }
  41337. if (effect) {
  41338. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41339. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41340. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41341. }
  41342. };
  41343. /**
  41344. * Prepare the list of uniforms associated with the ColorCurves effects.
  41345. * @param uniformsList The list of uniforms used in the effect
  41346. */
  41347. ColorCurves.PrepareUniforms = function (uniformsList) {
  41348. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41349. };
  41350. /**
  41351. * Returns color grading data based on a hue, density, saturation and exposure value.
  41352. * @param filterHue The hue of the color filter.
  41353. * @param filterDensity The density of the color filter.
  41354. * @param saturation The saturation.
  41355. * @param exposure The exposure.
  41356. * @param result The result data container.
  41357. */
  41358. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41359. if (hue == null) {
  41360. return;
  41361. }
  41362. hue = ColorCurves.clamp(hue, 0, 360);
  41363. density = ColorCurves.clamp(density, -100, 100);
  41364. saturation = ColorCurves.clamp(saturation, -100, 100);
  41365. exposure = ColorCurves.clamp(exposure, -100, 100);
  41366. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41367. // so that the maximum filter density is only 50% control. This provides fine control
  41368. // for small values and reasonable range.
  41369. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41370. density *= 0.5;
  41371. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41372. if (density < 0) {
  41373. density *= -1;
  41374. hue = (hue + 180) % 360;
  41375. }
  41376. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41377. result.scaleToRef(2, result);
  41378. result.a = 1 + 0.01 * saturation;
  41379. };
  41380. /**
  41381. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41382. * @param value The input slider value in range [-100,100].
  41383. * @returns Adjusted value.
  41384. */
  41385. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41386. value /= 100;
  41387. var x = Math.abs(value);
  41388. x = Math.pow(x, 2);
  41389. if (value < 0) {
  41390. x *= -1;
  41391. }
  41392. x *= 100;
  41393. return x;
  41394. };
  41395. /**
  41396. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41397. * @param hue The hue (H) input.
  41398. * @param saturation The saturation (S) input.
  41399. * @param brightness The brightness (B) input.
  41400. * @result An RGBA color represented as Vector4.
  41401. */
  41402. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41403. var h = ColorCurves.clamp(hue, 0, 360);
  41404. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41405. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41406. if (s === 0) {
  41407. result.r = v;
  41408. result.g = v;
  41409. result.b = v;
  41410. }
  41411. else {
  41412. // sector 0 to 5
  41413. h /= 60;
  41414. var i = Math.floor(h);
  41415. // fractional part of h
  41416. var f = h - i;
  41417. var p = v * (1 - s);
  41418. var q = v * (1 - s * f);
  41419. var t = v * (1 - s * (1 - f));
  41420. switch (i) {
  41421. case 0:
  41422. result.r = v;
  41423. result.g = t;
  41424. result.b = p;
  41425. break;
  41426. case 1:
  41427. result.r = q;
  41428. result.g = v;
  41429. result.b = p;
  41430. break;
  41431. case 2:
  41432. result.r = p;
  41433. result.g = v;
  41434. result.b = t;
  41435. break;
  41436. case 3:
  41437. result.r = p;
  41438. result.g = q;
  41439. result.b = v;
  41440. break;
  41441. case 4:
  41442. result.r = t;
  41443. result.g = p;
  41444. result.b = v;
  41445. break;
  41446. default:// case 5:
  41447. result.r = v;
  41448. result.g = p;
  41449. result.b = q;
  41450. break;
  41451. }
  41452. }
  41453. result.a = 1;
  41454. };
  41455. /**
  41456. * Returns a value clamped between min and max
  41457. * @param value The value to clamp
  41458. * @param min The minimum of value
  41459. * @param max The maximum of value
  41460. * @returns The clamped value.
  41461. */
  41462. ColorCurves.clamp = function (value, min, max) {
  41463. return Math.min(Math.max(value, min), max);
  41464. };
  41465. /**
  41466. * Clones the current color curve instance.
  41467. * @return The cloned curves
  41468. */
  41469. ColorCurves.prototype.clone = function () {
  41470. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41471. };
  41472. /**
  41473. * Serializes the current color curve instance to a json representation.
  41474. * @return a JSON representation
  41475. */
  41476. ColorCurves.prototype.serialize = function () {
  41477. return BABYLON.SerializationHelper.Serialize(this);
  41478. };
  41479. /**
  41480. * Parses the color curve from a json representation.
  41481. * @param source the JSON source to parse
  41482. * @return The parsed curves
  41483. */
  41484. ColorCurves.Parse = function (source) {
  41485. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41486. };
  41487. __decorate([
  41488. BABYLON.serialize()
  41489. ], ColorCurves.prototype, "_globalHue", void 0);
  41490. __decorate([
  41491. BABYLON.serialize()
  41492. ], ColorCurves.prototype, "_globalDensity", void 0);
  41493. __decorate([
  41494. BABYLON.serialize()
  41495. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41496. __decorate([
  41497. BABYLON.serialize()
  41498. ], ColorCurves.prototype, "_globalExposure", void 0);
  41499. __decorate([
  41500. BABYLON.serialize()
  41501. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41502. __decorate([
  41503. BABYLON.serialize()
  41504. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41505. __decorate([
  41506. BABYLON.serialize()
  41507. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41508. __decorate([
  41509. BABYLON.serialize()
  41510. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41511. __decorate([
  41512. BABYLON.serialize()
  41513. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41514. __decorate([
  41515. BABYLON.serialize()
  41516. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41517. __decorate([
  41518. BABYLON.serialize()
  41519. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41520. __decorate([
  41521. BABYLON.serialize()
  41522. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41523. return ColorCurves;
  41524. }());
  41525. BABYLON.ColorCurves = ColorCurves;
  41526. })(BABYLON || (BABYLON = {}));
  41527. //# sourceMappingURL=babylon.colorCurves.js.map
  41528. "use strict";
  41529. //# sourceMappingURL=babylon.behavior.js.map
  41530. "use strict";
  41531. var BABYLON;
  41532. (function (BABYLON) {
  41533. /**
  41534. * "Static Class" containing the most commonly used helper while dealing with material for
  41535. * rendering purpose.
  41536. *
  41537. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41538. *
  41539. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41540. */
  41541. var MaterialHelper = /** @class */ (function () {
  41542. function MaterialHelper() {
  41543. }
  41544. /**
  41545. * Bind the current view position to an effect.
  41546. * @param effect The effect to be bound
  41547. * @param scene The scene the eyes position is used from
  41548. */
  41549. MaterialHelper.BindEyePosition = function (effect, scene) {
  41550. if (scene._forcedViewPosition) {
  41551. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41552. return;
  41553. }
  41554. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41555. };
  41556. /**
  41557. * Helps preparing the defines values about the UVs in used in the effect.
  41558. * UVs are shared as much as we can accross chanels in the shaders.
  41559. * @param texture The texture we are preparing the UVs for
  41560. * @param defines The defines to update
  41561. * @param key The chanel key "diffuse", "specular"... used in the shader
  41562. */
  41563. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41564. defines._needUVs = true;
  41565. defines[key] = true;
  41566. if (texture.getTextureMatrix().isIdentity(true)) {
  41567. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41568. if (texture.coordinatesIndex === 0) {
  41569. defines["MAINUV1"] = true;
  41570. }
  41571. else {
  41572. defines["MAINUV2"] = true;
  41573. }
  41574. }
  41575. else {
  41576. defines[key + "DIRECTUV"] = 0;
  41577. }
  41578. };
  41579. /**
  41580. * Binds a texture matrix value to its corrsponding uniform
  41581. * @param texture The texture to bind the matrix for
  41582. * @param uniformBuffer The uniform buffer receivin the data
  41583. * @param key The chanel key "diffuse", "specular"... used in the shader
  41584. */
  41585. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41586. var matrix = texture.getTextureMatrix();
  41587. if (!matrix.isIdentity(true)) {
  41588. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41589. }
  41590. };
  41591. /**
  41592. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41593. * @param mesh defines the current mesh
  41594. * @param scene defines the current scene
  41595. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41596. * @param pointsCloud defines if point cloud rendering has to be turned on
  41597. * @param fogEnabled defines if fog has to be turned on
  41598. * @param alphaTest defines if alpha testing has to be turned on
  41599. * @param defines defines the current list of defines
  41600. */
  41601. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41602. if (defines._areMiscDirty) {
  41603. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41604. defines["POINTSIZE"] = pointsCloud;
  41605. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41606. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41607. defines["ALPHATEST"] = alphaTest;
  41608. }
  41609. };
  41610. /**
  41611. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41612. * @param scene defines the current scene
  41613. * @param engine defines the current engine
  41614. * @param defines specifies the list of active defines
  41615. * @param useInstances defines if instances have to be turned on
  41616. * @param useClipPlane defines if clip plane have to be turned on
  41617. */
  41618. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41619. if (useClipPlane === void 0) { useClipPlane = null; }
  41620. var changed = false;
  41621. if (useClipPlane == null) {
  41622. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41623. }
  41624. if (defines["CLIPPLANE"] !== useClipPlane) {
  41625. defines["CLIPPLANE"] = useClipPlane;
  41626. changed = true;
  41627. }
  41628. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41629. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41630. changed = true;
  41631. }
  41632. if (defines["INSTANCES"] !== useInstances) {
  41633. defines["INSTANCES"] = useInstances;
  41634. changed = true;
  41635. }
  41636. if (changed) {
  41637. defines.markAsUnprocessed();
  41638. }
  41639. };
  41640. /**
  41641. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41642. * @param mesh The mesh containing the geometry data we will draw
  41643. * @param defines The defines to update
  41644. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41645. * @param useBones Precise whether bones should be used or not (override mesh info)
  41646. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41647. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41648. * @returns false if defines are considered not dirty and have not been checked
  41649. */
  41650. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41651. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41652. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41653. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41654. return false;
  41655. }
  41656. defines._normals = defines._needNormals;
  41657. defines._uvs = defines._needUVs;
  41658. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41659. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41660. defines["TANGENT"] = true;
  41661. }
  41662. if (defines._needUVs) {
  41663. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41664. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41665. }
  41666. else {
  41667. defines["UV1"] = false;
  41668. defines["UV2"] = false;
  41669. }
  41670. if (useVertexColor) {
  41671. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41672. defines["VERTEXCOLOR"] = hasVertexColors;
  41673. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41674. }
  41675. if (useBones) {
  41676. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41677. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41678. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41679. }
  41680. else {
  41681. defines["NUM_BONE_INFLUENCERS"] = 0;
  41682. defines["BonesPerMesh"] = 0;
  41683. }
  41684. }
  41685. if (useMorphTargets) {
  41686. var manager = mesh.morphTargetManager;
  41687. if (manager) {
  41688. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41689. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41690. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41691. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41692. }
  41693. else {
  41694. defines["MORPHTARGETS_TANGENT"] = false;
  41695. defines["MORPHTARGETS_NORMAL"] = false;
  41696. defines["MORPHTARGETS"] = false;
  41697. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41698. }
  41699. }
  41700. return true;
  41701. };
  41702. /**
  41703. * Prepares the defines related to the light information passed in parameter
  41704. * @param scene The scene we are intending to draw
  41705. * @param mesh The mesh the effect is compiling for
  41706. * @param defines The defines to update
  41707. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41708. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41709. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41710. * @returns true if normals will be required for the rest of the effect
  41711. */
  41712. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41713. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41714. if (disableLighting === void 0) { disableLighting = false; }
  41715. if (!defines._areLightsDirty) {
  41716. return defines._needNormals;
  41717. }
  41718. var lightIndex = 0;
  41719. var needNormals = false;
  41720. var needRebuild = false;
  41721. var lightmapMode = false;
  41722. var shadowEnabled = false;
  41723. var specularEnabled = false;
  41724. if (scene.lightsEnabled && !disableLighting) {
  41725. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41726. var light = _a[_i];
  41727. needNormals = true;
  41728. if (defines["LIGHT" + lightIndex] === undefined) {
  41729. needRebuild = true;
  41730. }
  41731. defines["LIGHT" + lightIndex] = true;
  41732. defines["SPOTLIGHT" + lightIndex] = false;
  41733. defines["HEMILIGHT" + lightIndex] = false;
  41734. defines["POINTLIGHT" + lightIndex] = false;
  41735. defines["DIRLIGHT" + lightIndex] = false;
  41736. var type;
  41737. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41738. type = "SPOTLIGHT" + lightIndex;
  41739. var spotLight = light;
  41740. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  41741. }
  41742. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41743. type = "HEMILIGHT" + lightIndex;
  41744. }
  41745. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41746. type = "POINTLIGHT" + lightIndex;
  41747. }
  41748. else {
  41749. type = "DIRLIGHT" + lightIndex;
  41750. }
  41751. defines[type] = true;
  41752. // Specular
  41753. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41754. specularEnabled = true;
  41755. }
  41756. // Shadows
  41757. defines["SHADOW" + lightIndex] = false;
  41758. defines["SHADOWPCF" + lightIndex] = false;
  41759. defines["SHADOWPCSS" + lightIndex] = false;
  41760. defines["SHADOWPOISSON" + lightIndex] = false;
  41761. defines["SHADOWESM" + lightIndex] = false;
  41762. defines["SHADOWCUBE" + lightIndex] = false;
  41763. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41764. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41765. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41766. var shadowGenerator = light.getShadowGenerator();
  41767. if (shadowGenerator) {
  41768. shadowEnabled = true;
  41769. shadowGenerator.prepareDefines(defines, lightIndex);
  41770. }
  41771. }
  41772. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41773. lightmapMode = true;
  41774. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41775. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41776. }
  41777. else {
  41778. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41779. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41780. }
  41781. lightIndex++;
  41782. if (lightIndex === maxSimultaneousLights)
  41783. break;
  41784. }
  41785. }
  41786. defines["SPECULARTERM"] = specularEnabled;
  41787. defines["SHADOWS"] = shadowEnabled;
  41788. // Resetting all other lights if any
  41789. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41790. if (defines["LIGHT" + index] !== undefined) {
  41791. defines["LIGHT" + index] = false;
  41792. defines["HEMILIGHT" + lightIndex] = false;
  41793. defines["POINTLIGHT" + lightIndex] = false;
  41794. defines["DIRLIGHT" + lightIndex] = false;
  41795. defines["SPOTLIGHT" + lightIndex] = false;
  41796. defines["SHADOW" + lightIndex] = false;
  41797. }
  41798. }
  41799. var caps = scene.getEngine().getCaps();
  41800. if (defines["SHADOWFLOAT"] === undefined) {
  41801. needRebuild = true;
  41802. }
  41803. defines["SHADOWFLOAT"] = shadowEnabled &&
  41804. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41805. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41806. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41807. if (needRebuild) {
  41808. defines.rebuild();
  41809. }
  41810. return needNormals;
  41811. };
  41812. /**
  41813. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41814. * that won t be acctive due to defines being turned off.
  41815. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41816. * @param samplersList The samplers list
  41817. * @param defines The defines helping in the list generation
  41818. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41819. */
  41820. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41821. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41822. var uniformsList;
  41823. var uniformBuffersList = null;
  41824. if (uniformsListOrOptions.uniformsNames) {
  41825. var options = uniformsListOrOptions;
  41826. uniformsList = options.uniformsNames;
  41827. uniformBuffersList = options.uniformBuffersNames;
  41828. samplersList = options.samplers;
  41829. defines = options.defines;
  41830. maxSimultaneousLights = options.maxSimultaneousLights;
  41831. }
  41832. else {
  41833. uniformsList = uniformsListOrOptions;
  41834. if (!samplersList) {
  41835. samplersList = [];
  41836. }
  41837. }
  41838. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41839. if (!defines["LIGHT" + lightIndex]) {
  41840. break;
  41841. }
  41842. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41843. if (uniformBuffersList) {
  41844. uniformBuffersList.push("Light" + lightIndex);
  41845. }
  41846. samplersList.push("shadowSampler" + lightIndex);
  41847. samplersList.push("depthSampler" + lightIndex);
  41848. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41849. samplersList.push("projectionLightSampler" + lightIndex);
  41850. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41851. }
  41852. }
  41853. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41854. uniformsList.push("morphTargetInfluences");
  41855. }
  41856. };
  41857. /**
  41858. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41859. * @param defines The defines to update while falling back
  41860. * @param fallbacks The authorized effect fallbacks
  41861. * @param maxSimultaneousLights The maximum number of lights allowed
  41862. * @param rank the current rank of the Effect
  41863. * @returns The newly affected rank
  41864. */
  41865. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41866. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41867. if (rank === void 0) { rank = 0; }
  41868. var lightFallbackRank = 0;
  41869. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41870. if (!defines["LIGHT" + lightIndex]) {
  41871. break;
  41872. }
  41873. if (lightIndex > 0) {
  41874. lightFallbackRank = rank + lightIndex;
  41875. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41876. }
  41877. if (!defines["SHADOWS"]) {
  41878. if (defines["SHADOW" + lightIndex]) {
  41879. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41880. }
  41881. if (defines["SHADOWPCF" + lightIndex]) {
  41882. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41883. }
  41884. if (defines["SHADOWPCSS" + lightIndex]) {
  41885. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41886. }
  41887. if (defines["SHADOWPOISSON" + lightIndex]) {
  41888. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41889. }
  41890. if (defines["SHADOWESM" + lightIndex]) {
  41891. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41892. }
  41893. }
  41894. }
  41895. return lightFallbackRank++;
  41896. };
  41897. /**
  41898. * Prepares the list of attributes required for morph targets according to the effect defines.
  41899. * @param attribs The current list of supported attribs
  41900. * @param mesh The mesh to prepare the morph targets attributes for
  41901. * @param defines The current Defines of the effect
  41902. */
  41903. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41904. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41905. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41906. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41907. var manager = mesh.morphTargetManager;
  41908. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41909. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41910. for (var index = 0; index < influencers; index++) {
  41911. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41912. if (normal) {
  41913. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41914. }
  41915. if (tangent) {
  41916. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41917. }
  41918. if (attribs.length > maxAttributesCount) {
  41919. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41920. }
  41921. }
  41922. }
  41923. };
  41924. /**
  41925. * Prepares the list of attributes required for bones according to the effect defines.
  41926. * @param attribs The current list of supported attribs
  41927. * @param mesh The mesh to prepare the bones attributes for
  41928. * @param defines The current Defines of the effect
  41929. * @param fallbacks The current efffect fallback strategy
  41930. */
  41931. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41932. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41933. fallbacks.addCPUSkinningFallback(0, mesh);
  41934. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41935. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41936. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41937. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41938. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41939. }
  41940. }
  41941. };
  41942. /**
  41943. * Prepares the list of attributes required for instances according to the effect defines.
  41944. * @param attribs The current list of supported attribs
  41945. * @param defines The current Defines of the effect
  41946. */
  41947. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41948. if (defines["INSTANCES"]) {
  41949. attribs.push("world0");
  41950. attribs.push("world1");
  41951. attribs.push("world2");
  41952. attribs.push("world3");
  41953. }
  41954. };
  41955. /**
  41956. * Binds the light shadow information to the effect for the given mesh.
  41957. * @param light The light containing the generator
  41958. * @param scene The scene the lights belongs to
  41959. * @param mesh The mesh we are binding the information to render
  41960. * @param lightIndex The light index in the effect used to render the mesh
  41961. * @param effect The effect we are binding the data to
  41962. */
  41963. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41964. if (light.shadowEnabled && mesh.receiveShadows) {
  41965. var shadowGenerator = light.getShadowGenerator();
  41966. if (shadowGenerator) {
  41967. shadowGenerator.bindShadowLight(lightIndex, effect);
  41968. }
  41969. }
  41970. };
  41971. /**
  41972. * Binds the light information to the effect.
  41973. * @param light The light containing the generator
  41974. * @param effect The effect we are binding the data to
  41975. * @param lightIndex The light index in the effect used to render
  41976. */
  41977. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41978. light.transferToEffect(effect, lightIndex + "");
  41979. };
  41980. /**
  41981. * Binds the lights information from the scene to the effect for the given mesh.
  41982. * @param scene The scene the lights belongs to
  41983. * @param mesh The mesh we are binding the information to render
  41984. * @param effect The effect we are binding the data to
  41985. * @param defines The generated defines for the effect
  41986. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41987. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41988. */
  41989. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41990. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41991. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41992. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41993. for (var i = 0; i < len; i++) {
  41994. var light = mesh._lightSources[i];
  41995. var iAsString = i.toString();
  41996. var scaledIntensity = light.getScaledIntensity();
  41997. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41998. MaterialHelper.BindLightProperties(light, effect, i);
  41999. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42000. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42001. if (defines["SPECULARTERM"]) {
  42002. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42003. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42004. }
  42005. // Shadows
  42006. if (scene.shadowsEnabled) {
  42007. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42008. }
  42009. light._uniformBuffer.update();
  42010. }
  42011. };
  42012. /**
  42013. * Binds the fog information from the scene to the effect for the given mesh.
  42014. * @param scene The scene the lights belongs to
  42015. * @param mesh The mesh we are binding the information to render
  42016. * @param effect The effect we are binding the data to
  42017. */
  42018. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42019. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42020. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42021. effect.setColor3("vFogColor", scene.fogColor);
  42022. }
  42023. };
  42024. /**
  42025. * Binds the bones information from the mesh to the effect.
  42026. * @param mesh The mesh we are binding the information to render
  42027. * @param effect The effect we are binding the data to
  42028. */
  42029. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42030. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42031. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42032. if (matrices && effect) {
  42033. effect.setMatrices("mBones", matrices);
  42034. }
  42035. }
  42036. };
  42037. /**
  42038. * Binds the morph targets information from the mesh to the effect.
  42039. * @param abstractMesh The mesh we are binding the information to render
  42040. * @param effect The effect we are binding the data to
  42041. */
  42042. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42043. var manager = abstractMesh.morphTargetManager;
  42044. if (!abstractMesh || !manager) {
  42045. return;
  42046. }
  42047. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42048. };
  42049. /**
  42050. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42051. * @param defines The generated defines used in the effect
  42052. * @param effect The effect we are binding the data to
  42053. * @param scene The scene we are willing to render with logarithmic scale for
  42054. */
  42055. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42056. if (defines["LOGARITHMICDEPTH"]) {
  42057. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42058. }
  42059. };
  42060. /**
  42061. * Binds the clip plane information from the scene to the effect.
  42062. * @param scene The scene the clip plane information are extracted from
  42063. * @param effect The effect we are binding the data to
  42064. */
  42065. MaterialHelper.BindClipPlane = function (effect, scene) {
  42066. if (scene.clipPlane) {
  42067. var clipPlane = scene.clipPlane;
  42068. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42069. }
  42070. };
  42071. return MaterialHelper;
  42072. }());
  42073. BABYLON.MaterialHelper = MaterialHelper;
  42074. })(BABYLON || (BABYLON = {}));
  42075. //# sourceMappingURL=babylon.materialHelper.js.map
  42076. "use strict";
  42077. var BABYLON;
  42078. (function (BABYLON) {
  42079. var PushMaterial = /** @class */ (function (_super) {
  42080. __extends(PushMaterial, _super);
  42081. function PushMaterial(name, scene) {
  42082. var _this = _super.call(this, name, scene) || this;
  42083. _this._normalMatrix = new BABYLON.Matrix();
  42084. _this.storeEffectOnSubMeshes = true;
  42085. return _this;
  42086. }
  42087. PushMaterial.prototype.getEffect = function () {
  42088. return this._activeEffect;
  42089. };
  42090. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42091. if (!mesh) {
  42092. return false;
  42093. }
  42094. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42095. return true;
  42096. }
  42097. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42098. };
  42099. /**
  42100. * Binds the given world matrix to the active effect
  42101. *
  42102. * @param world the matrix to bind
  42103. */
  42104. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42105. this._activeEffect.setMatrix("world", world);
  42106. };
  42107. /**
  42108. * Binds the given normal matrix to the active effect
  42109. *
  42110. * @param normalMatrix the matrix to bind
  42111. */
  42112. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42113. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42114. };
  42115. PushMaterial.prototype.bind = function (world, mesh) {
  42116. if (!mesh) {
  42117. return;
  42118. }
  42119. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42120. };
  42121. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42122. if (effect === void 0) { effect = null; }
  42123. _super.prototype._afterBind.call(this, mesh);
  42124. this.getScene()._cachedEffect = effect;
  42125. };
  42126. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42127. if (visibility === void 0) { visibility = 1; }
  42128. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42129. };
  42130. return PushMaterial;
  42131. }(BABYLON.Material));
  42132. BABYLON.PushMaterial = PushMaterial;
  42133. })(BABYLON || (BABYLON = {}));
  42134. //# sourceMappingURL=babylon.pushMaterial.js.map
  42135. "use strict";
  42136. var BABYLON;
  42137. (function (BABYLON) {
  42138. /** @ignore */
  42139. var StandardMaterialDefines = /** @class */ (function (_super) {
  42140. __extends(StandardMaterialDefines, _super);
  42141. function StandardMaterialDefines() {
  42142. var _this = _super.call(this) || this;
  42143. _this.MAINUV1 = false;
  42144. _this.MAINUV2 = false;
  42145. _this.DIFFUSE = false;
  42146. _this.DIFFUSEDIRECTUV = 0;
  42147. _this.AMBIENT = false;
  42148. _this.AMBIENTDIRECTUV = 0;
  42149. _this.OPACITY = false;
  42150. _this.OPACITYDIRECTUV = 0;
  42151. _this.OPACITYRGB = false;
  42152. _this.REFLECTION = false;
  42153. _this.EMISSIVE = false;
  42154. _this.EMISSIVEDIRECTUV = 0;
  42155. _this.SPECULAR = false;
  42156. _this.SPECULARDIRECTUV = 0;
  42157. _this.BUMP = false;
  42158. _this.BUMPDIRECTUV = 0;
  42159. _this.PARALLAX = false;
  42160. _this.PARALLAXOCCLUSION = false;
  42161. _this.SPECULAROVERALPHA = false;
  42162. _this.CLIPPLANE = false;
  42163. _this.ALPHATEST = false;
  42164. _this.DEPTHPREPASS = false;
  42165. _this.ALPHAFROMDIFFUSE = false;
  42166. _this.POINTSIZE = false;
  42167. _this.FOG = false;
  42168. _this.SPECULARTERM = false;
  42169. _this.DIFFUSEFRESNEL = false;
  42170. _this.OPACITYFRESNEL = false;
  42171. _this.REFLECTIONFRESNEL = false;
  42172. _this.REFRACTIONFRESNEL = false;
  42173. _this.EMISSIVEFRESNEL = false;
  42174. _this.FRESNEL = false;
  42175. _this.NORMAL = false;
  42176. _this.UV1 = false;
  42177. _this.UV2 = false;
  42178. _this.VERTEXCOLOR = false;
  42179. _this.VERTEXALPHA = false;
  42180. _this.NUM_BONE_INFLUENCERS = 0;
  42181. _this.BonesPerMesh = 0;
  42182. _this.INSTANCES = false;
  42183. _this.GLOSSINESS = false;
  42184. _this.ROUGHNESS = false;
  42185. _this.EMISSIVEASILLUMINATION = false;
  42186. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42187. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42188. _this.LIGHTMAP = false;
  42189. _this.LIGHTMAPDIRECTUV = 0;
  42190. _this.OBJECTSPACE_NORMALMAP = false;
  42191. _this.USELIGHTMAPASSHADOWMAP = false;
  42192. _this.REFLECTIONMAP_3D = false;
  42193. _this.REFLECTIONMAP_SPHERICAL = false;
  42194. _this.REFLECTIONMAP_PLANAR = false;
  42195. _this.REFLECTIONMAP_CUBIC = false;
  42196. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42197. _this.REFLECTIONMAP_PROJECTION = false;
  42198. _this.REFLECTIONMAP_SKYBOX = false;
  42199. _this.REFLECTIONMAP_EXPLICIT = false;
  42200. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42201. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42202. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42203. _this.INVERTCUBICMAP = false;
  42204. _this.LOGARITHMICDEPTH = false;
  42205. _this.REFRACTION = false;
  42206. _this.REFRACTIONMAP_3D = false;
  42207. _this.REFLECTIONOVERALPHA = false;
  42208. _this.TWOSIDEDLIGHTING = false;
  42209. _this.SHADOWFLOAT = false;
  42210. _this.MORPHTARGETS = false;
  42211. _this.MORPHTARGETS_NORMAL = false;
  42212. _this.MORPHTARGETS_TANGENT = false;
  42213. _this.NUM_MORPH_INFLUENCERS = 0;
  42214. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42215. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42216. _this.IMAGEPROCESSING = false;
  42217. _this.VIGNETTE = false;
  42218. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42219. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42220. _this.TONEMAPPING = false;
  42221. _this.CONTRAST = false;
  42222. _this.COLORCURVES = false;
  42223. _this.COLORGRADING = false;
  42224. _this.COLORGRADING3D = false;
  42225. _this.SAMPLER3DGREENDEPTH = false;
  42226. _this.SAMPLER3DBGRMAP = false;
  42227. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42228. /**
  42229. * If the reflection texture on this material is in linear color space
  42230. * @ignore
  42231. */
  42232. _this.IS_REFLECTION_LINEAR = false;
  42233. /**
  42234. * If the refraction texture on this material is in linear color space
  42235. * @ignore
  42236. */
  42237. _this.IS_REFRACTION_LINEAR = false;
  42238. _this.EXPOSURE = false;
  42239. _this.rebuild();
  42240. return _this;
  42241. }
  42242. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42243. var modes = [
  42244. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42245. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42246. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42247. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42248. ];
  42249. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42250. var mode = modes_1[_i];
  42251. this[mode] = (mode === modeToEnable);
  42252. }
  42253. };
  42254. return StandardMaterialDefines;
  42255. }(BABYLON.MaterialDefines));
  42256. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42257. var StandardMaterial = /** @class */ (function (_super) {
  42258. __extends(StandardMaterial, _super);
  42259. function StandardMaterial(name, scene) {
  42260. var _this = _super.call(this, name, scene) || this;
  42261. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42262. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42263. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42264. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42265. _this.specularPower = 64;
  42266. _this._useAlphaFromDiffuseTexture = false;
  42267. _this._useEmissiveAsIllumination = false;
  42268. _this._linkEmissiveWithDiffuse = false;
  42269. _this._useSpecularOverAlpha = false;
  42270. _this._useReflectionOverAlpha = false;
  42271. _this._disableLighting = false;
  42272. _this._useObjectSpaceNormalMap = false;
  42273. _this._useParallax = false;
  42274. _this._useParallaxOcclusion = false;
  42275. _this.parallaxScaleBias = 0.05;
  42276. _this._roughness = 0;
  42277. _this.indexOfRefraction = 0.98;
  42278. _this.invertRefractionY = true;
  42279. _this._useLightmapAsShadowmap = false;
  42280. _this._useReflectionFresnelFromSpecular = false;
  42281. _this._useGlossinessFromSpecularMapAlpha = false;
  42282. _this._maxSimultaneousLights = 4;
  42283. /**
  42284. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42285. */
  42286. _this._invertNormalMapX = false;
  42287. /**
  42288. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42289. */
  42290. _this._invertNormalMapY = false;
  42291. /**
  42292. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42293. */
  42294. _this._twoSidedLighting = false;
  42295. _this._renderTargets = new BABYLON.SmartArray(16);
  42296. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42297. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42298. // Setup the default processing configuration to the scene.
  42299. _this._attachImageProcessingConfiguration(null);
  42300. _this.getRenderTargetTextures = function () {
  42301. _this._renderTargets.reset();
  42302. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42303. _this._renderTargets.push(_this._reflectionTexture);
  42304. }
  42305. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42306. _this._renderTargets.push(_this._refractionTexture);
  42307. }
  42308. return _this._renderTargets;
  42309. };
  42310. return _this;
  42311. }
  42312. ;
  42313. ;
  42314. ;
  42315. ;
  42316. ;
  42317. ;
  42318. ;
  42319. ;
  42320. ;
  42321. ;
  42322. ;
  42323. ;
  42324. ;
  42325. ;
  42326. ;
  42327. ;
  42328. ;
  42329. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42330. /**
  42331. * Gets the image processing configuration used either in this material.
  42332. */
  42333. get: function () {
  42334. return this._imageProcessingConfiguration;
  42335. },
  42336. /**
  42337. * Sets the Default image processing configuration used either in the this material.
  42338. *
  42339. * If sets to null, the scene one is in use.
  42340. */
  42341. set: function (value) {
  42342. this._attachImageProcessingConfiguration(value);
  42343. // Ensure the effect will be rebuilt.
  42344. this._markAllSubMeshesAsTexturesDirty();
  42345. },
  42346. enumerable: true,
  42347. configurable: true
  42348. });
  42349. /**
  42350. * Attaches a new image processing configuration to the Standard Material.
  42351. * @param configuration
  42352. */
  42353. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42354. var _this = this;
  42355. if (configuration === this._imageProcessingConfiguration) {
  42356. return;
  42357. }
  42358. // Detaches observer.
  42359. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42360. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42361. }
  42362. // Pick the scene configuration if needed.
  42363. if (!configuration) {
  42364. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42365. }
  42366. else {
  42367. this._imageProcessingConfiguration = configuration;
  42368. }
  42369. // Attaches observer.
  42370. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42371. _this._markAllSubMeshesAsImageProcessingDirty();
  42372. });
  42373. };
  42374. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42375. /**
  42376. * Gets wether the color curves effect is enabled.
  42377. */
  42378. get: function () {
  42379. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42380. },
  42381. /**
  42382. * Sets wether the color curves effect is enabled.
  42383. */
  42384. set: function (value) {
  42385. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42386. },
  42387. enumerable: true,
  42388. configurable: true
  42389. });
  42390. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42391. /**
  42392. * Gets wether the color grading effect is enabled.
  42393. */
  42394. get: function () {
  42395. return this.imageProcessingConfiguration.colorGradingEnabled;
  42396. },
  42397. /**
  42398. * Gets wether the color grading effect is enabled.
  42399. */
  42400. set: function (value) {
  42401. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42402. },
  42403. enumerable: true,
  42404. configurable: true
  42405. });
  42406. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42407. /**
  42408. * Gets wether tonemapping is enabled or not.
  42409. */
  42410. get: function () {
  42411. return this._imageProcessingConfiguration.toneMappingEnabled;
  42412. },
  42413. /**
  42414. * Sets wether tonemapping is enabled or not
  42415. */
  42416. set: function (value) {
  42417. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42418. },
  42419. enumerable: true,
  42420. configurable: true
  42421. });
  42422. ;
  42423. ;
  42424. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42425. /**
  42426. * The camera exposure used on this material.
  42427. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42428. * This corresponds to a photographic exposure.
  42429. */
  42430. get: function () {
  42431. return this._imageProcessingConfiguration.exposure;
  42432. },
  42433. /**
  42434. * The camera exposure used on this material.
  42435. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42436. * This corresponds to a photographic exposure.
  42437. */
  42438. set: function (value) {
  42439. this._imageProcessingConfiguration.exposure = value;
  42440. },
  42441. enumerable: true,
  42442. configurable: true
  42443. });
  42444. ;
  42445. ;
  42446. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42447. /**
  42448. * Gets The camera contrast used on this material.
  42449. */
  42450. get: function () {
  42451. return this._imageProcessingConfiguration.contrast;
  42452. },
  42453. /**
  42454. * Sets The camera contrast used on this material.
  42455. */
  42456. set: function (value) {
  42457. this._imageProcessingConfiguration.contrast = value;
  42458. },
  42459. enumerable: true,
  42460. configurable: true
  42461. });
  42462. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42463. /**
  42464. * Gets the Color Grading 2D Lookup Texture.
  42465. */
  42466. get: function () {
  42467. return this._imageProcessingConfiguration.colorGradingTexture;
  42468. },
  42469. /**
  42470. * Sets the Color Grading 2D Lookup Texture.
  42471. */
  42472. set: function (value) {
  42473. this._imageProcessingConfiguration.colorGradingTexture = value;
  42474. },
  42475. enumerable: true,
  42476. configurable: true
  42477. });
  42478. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42479. /**
  42480. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42481. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42482. * 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;
  42483. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42484. */
  42485. get: function () {
  42486. return this._imageProcessingConfiguration.colorCurves;
  42487. },
  42488. /**
  42489. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42490. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42491. * 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;
  42492. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42493. */
  42494. set: function (value) {
  42495. this._imageProcessingConfiguration.colorCurves = value;
  42496. },
  42497. enumerable: true,
  42498. configurable: true
  42499. });
  42500. StandardMaterial.prototype.getClassName = function () {
  42501. return "StandardMaterial";
  42502. };
  42503. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42504. get: function () {
  42505. return this._useLogarithmicDepth;
  42506. },
  42507. set: function (value) {
  42508. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42509. this._markAllSubMeshesAsMiscDirty();
  42510. },
  42511. enumerable: true,
  42512. configurable: true
  42513. });
  42514. StandardMaterial.prototype.needAlphaBlending = function () {
  42515. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42516. };
  42517. StandardMaterial.prototype.needAlphaTesting = function () {
  42518. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42519. };
  42520. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42521. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42522. };
  42523. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42524. return this._diffuseTexture;
  42525. };
  42526. /**
  42527. * Child classes can use it to update shaders
  42528. */
  42529. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42530. if (useInstances === void 0) { useInstances = false; }
  42531. if (subMesh.effect && this.isFrozen) {
  42532. if (this._wasPreviouslyReady && subMesh.effect) {
  42533. return true;
  42534. }
  42535. }
  42536. if (!subMesh._materialDefines) {
  42537. subMesh._materialDefines = new StandardMaterialDefines();
  42538. }
  42539. var scene = this.getScene();
  42540. var defines = subMesh._materialDefines;
  42541. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42542. if (defines._renderId === scene.getRenderId()) {
  42543. return true;
  42544. }
  42545. }
  42546. var engine = scene.getEngine();
  42547. // Lights
  42548. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42549. // Textures
  42550. if (defines._areTexturesDirty) {
  42551. defines._needUVs = false;
  42552. defines.MAINUV1 = false;
  42553. defines.MAINUV2 = false;
  42554. if (scene.texturesEnabled) {
  42555. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42556. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42557. return false;
  42558. }
  42559. else {
  42560. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42561. }
  42562. }
  42563. else {
  42564. defines.DIFFUSE = false;
  42565. }
  42566. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42567. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42568. return false;
  42569. }
  42570. else {
  42571. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42572. }
  42573. }
  42574. else {
  42575. defines.AMBIENT = false;
  42576. }
  42577. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42578. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42579. return false;
  42580. }
  42581. else {
  42582. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42583. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42584. }
  42585. }
  42586. else {
  42587. defines.OPACITY = false;
  42588. }
  42589. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42590. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42591. return false;
  42592. }
  42593. else {
  42594. defines._needNormals = true;
  42595. defines.REFLECTION = true;
  42596. defines.ROUGHNESS = (this._roughness > 0);
  42597. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42598. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42599. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42600. switch (this._reflectionTexture.coordinatesMode) {
  42601. case BABYLON.Texture.CUBIC_MODE:
  42602. case BABYLON.Texture.INVCUBIC_MODE:
  42603. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42604. break;
  42605. case BABYLON.Texture.EXPLICIT_MODE:
  42606. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42607. break;
  42608. case BABYLON.Texture.PLANAR_MODE:
  42609. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42610. break;
  42611. case BABYLON.Texture.PROJECTION_MODE:
  42612. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42613. break;
  42614. case BABYLON.Texture.SKYBOX_MODE:
  42615. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42616. break;
  42617. case BABYLON.Texture.SPHERICAL_MODE:
  42618. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42619. break;
  42620. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42621. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42622. break;
  42623. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42624. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42625. break;
  42626. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42627. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42628. break;
  42629. }
  42630. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42631. }
  42632. }
  42633. else {
  42634. defines.REFLECTION = false;
  42635. }
  42636. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42637. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42638. return false;
  42639. }
  42640. else {
  42641. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42642. }
  42643. }
  42644. else {
  42645. defines.EMISSIVE = false;
  42646. }
  42647. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42648. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42649. return false;
  42650. }
  42651. else {
  42652. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42653. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42654. }
  42655. }
  42656. else {
  42657. defines.LIGHTMAP = false;
  42658. }
  42659. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42660. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42661. return false;
  42662. }
  42663. else {
  42664. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42665. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42666. }
  42667. }
  42668. else {
  42669. defines.SPECULAR = false;
  42670. }
  42671. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42672. // Bump texure can not be not blocking.
  42673. if (!this._bumpTexture.isReady()) {
  42674. return false;
  42675. }
  42676. else {
  42677. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42678. defines.PARALLAX = this._useParallax;
  42679. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42680. }
  42681. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42682. }
  42683. else {
  42684. defines.BUMP = false;
  42685. }
  42686. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42687. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42688. return false;
  42689. }
  42690. else {
  42691. defines._needUVs = true;
  42692. defines.REFRACTION = true;
  42693. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42694. }
  42695. }
  42696. else {
  42697. defines.REFRACTION = false;
  42698. }
  42699. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42700. }
  42701. else {
  42702. defines.DIFFUSE = false;
  42703. defines.AMBIENT = false;
  42704. defines.OPACITY = false;
  42705. defines.REFLECTION = false;
  42706. defines.EMISSIVE = false;
  42707. defines.LIGHTMAP = false;
  42708. defines.BUMP = false;
  42709. defines.REFRACTION = false;
  42710. }
  42711. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42712. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42713. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42714. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42715. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42716. }
  42717. if (defines._areImageProcessingDirty) {
  42718. if (!this._imageProcessingConfiguration.isReady()) {
  42719. return false;
  42720. }
  42721. this._imageProcessingConfiguration.prepareDefines(defines);
  42722. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42723. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42724. }
  42725. if (defines._areFresnelDirty) {
  42726. if (StandardMaterial.FresnelEnabled) {
  42727. // Fresnel
  42728. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42729. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42730. this._reflectionFresnelParameters) {
  42731. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42732. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42733. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42734. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42735. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42736. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42737. defines._needNormals = true;
  42738. defines.FRESNEL = true;
  42739. }
  42740. }
  42741. else {
  42742. defines.FRESNEL = false;
  42743. }
  42744. }
  42745. // Misc.
  42746. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42747. // Attribs
  42748. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42749. // Values that need to be evaluated on every frame
  42750. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42751. // Get correct effect
  42752. if (defines.isDirty) {
  42753. defines.markAsProcessed();
  42754. scene.resetCachedMaterial();
  42755. // Fallbacks
  42756. var fallbacks = new BABYLON.EffectFallbacks();
  42757. if (defines.REFLECTION) {
  42758. fallbacks.addFallback(0, "REFLECTION");
  42759. }
  42760. if (defines.SPECULAR) {
  42761. fallbacks.addFallback(0, "SPECULAR");
  42762. }
  42763. if (defines.BUMP) {
  42764. fallbacks.addFallback(0, "BUMP");
  42765. }
  42766. if (defines.PARALLAX) {
  42767. fallbacks.addFallback(1, "PARALLAX");
  42768. }
  42769. if (defines.PARALLAXOCCLUSION) {
  42770. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42771. }
  42772. if (defines.SPECULAROVERALPHA) {
  42773. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42774. }
  42775. if (defines.FOG) {
  42776. fallbacks.addFallback(1, "FOG");
  42777. }
  42778. if (defines.POINTSIZE) {
  42779. fallbacks.addFallback(0, "POINTSIZE");
  42780. }
  42781. if (defines.LOGARITHMICDEPTH) {
  42782. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42783. }
  42784. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42785. if (defines.SPECULARTERM) {
  42786. fallbacks.addFallback(0, "SPECULARTERM");
  42787. }
  42788. if (defines.DIFFUSEFRESNEL) {
  42789. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42790. }
  42791. if (defines.OPACITYFRESNEL) {
  42792. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42793. }
  42794. if (defines.REFLECTIONFRESNEL) {
  42795. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42796. }
  42797. if (defines.EMISSIVEFRESNEL) {
  42798. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42799. }
  42800. if (defines.FRESNEL) {
  42801. fallbacks.addFallback(4, "FRESNEL");
  42802. }
  42803. //Attributes
  42804. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42805. if (defines.NORMAL) {
  42806. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42807. }
  42808. if (defines.UV1) {
  42809. attribs.push(BABYLON.VertexBuffer.UVKind);
  42810. }
  42811. if (defines.UV2) {
  42812. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42813. }
  42814. if (defines.VERTEXCOLOR) {
  42815. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42816. }
  42817. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42818. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42819. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42820. var shaderName = "default";
  42821. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42822. "vFogInfos", "vFogColor", "pointSize",
  42823. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42824. "mBones",
  42825. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42826. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42827. "vReflectionPosition", "vReflectionSize",
  42828. "logarithmicDepthConstant", "vTangentSpaceParams"
  42829. ];
  42830. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42831. var uniformBuffers = ["Material", "Scene"];
  42832. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42833. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42834. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42835. uniformsNames: uniforms,
  42836. uniformBuffersNames: uniformBuffers,
  42837. samplers: samplers,
  42838. defines: defines,
  42839. maxSimultaneousLights: this._maxSimultaneousLights
  42840. });
  42841. if (this.customShaderNameResolve) {
  42842. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42843. }
  42844. var join = defines.toString();
  42845. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42846. attributes: attribs,
  42847. uniformsNames: uniforms,
  42848. uniformBuffersNames: uniformBuffers,
  42849. samplers: samplers,
  42850. defines: join,
  42851. fallbacks: fallbacks,
  42852. onCompiled: this.onCompiled,
  42853. onError: this.onError,
  42854. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42855. }, engine), defines);
  42856. this.buildUniformLayout();
  42857. }
  42858. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42859. return false;
  42860. }
  42861. defines._renderId = scene.getRenderId();
  42862. this._wasPreviouslyReady = true;
  42863. return true;
  42864. };
  42865. StandardMaterial.prototype.buildUniformLayout = function () {
  42866. // Order is important !
  42867. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42868. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42869. this._uniformBuffer.addUniform("opacityParts", 4);
  42870. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42871. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42872. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42873. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42874. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42875. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42876. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42877. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42878. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42879. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42880. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42881. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42882. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42883. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42884. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42885. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42886. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42887. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42888. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42889. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42890. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42891. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42892. this._uniformBuffer.addUniform("specularMatrix", 16);
  42893. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42894. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42895. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42896. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42897. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42898. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42899. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42900. this._uniformBuffer.addUniform("pointSize", 1);
  42901. this._uniformBuffer.create();
  42902. };
  42903. StandardMaterial.prototype.unbind = function () {
  42904. if (this._activeEffect) {
  42905. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42906. this._activeEffect.setTexture("reflection2DSampler", null);
  42907. }
  42908. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42909. this._activeEffect.setTexture("refraction2DSampler", null);
  42910. }
  42911. }
  42912. _super.prototype.unbind.call(this);
  42913. };
  42914. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42915. var scene = this.getScene();
  42916. var defines = subMesh._materialDefines;
  42917. if (!defines) {
  42918. return;
  42919. }
  42920. var effect = subMesh.effect;
  42921. if (!effect) {
  42922. return;
  42923. }
  42924. this._activeEffect = effect;
  42925. // Matrices
  42926. this.bindOnlyWorldMatrix(world);
  42927. // Normal Matrix
  42928. if (defines.OBJECTSPACE_NORMALMAP) {
  42929. world.toNormalMatrix(this._normalMatrix);
  42930. this.bindOnlyNormalMatrix(this._normalMatrix);
  42931. }
  42932. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42933. // Bones
  42934. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42935. if (mustRebind) {
  42936. this._uniformBuffer.bindToEffect(effect, "Material");
  42937. this.bindViewProjection(effect);
  42938. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42939. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42940. // Fresnel
  42941. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42942. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42943. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42944. }
  42945. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42946. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42947. }
  42948. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42949. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42950. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42951. }
  42952. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42953. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42954. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42955. }
  42956. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42957. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42958. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42959. }
  42960. }
  42961. // Textures
  42962. if (scene.texturesEnabled) {
  42963. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42964. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42965. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42966. }
  42967. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42968. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42969. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42970. }
  42971. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42972. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42973. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42974. }
  42975. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42976. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42977. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42978. if (this._reflectionTexture.boundingBoxSize) {
  42979. var cubeTexture = this._reflectionTexture;
  42980. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42981. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42982. }
  42983. }
  42984. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42985. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42986. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42987. }
  42988. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42989. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42990. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42991. }
  42992. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42993. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42994. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42995. }
  42996. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42997. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42998. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42999. if (scene._mirroredCameraPosition) {
  43000. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43001. }
  43002. else {
  43003. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43004. }
  43005. }
  43006. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43007. var depth = 1.0;
  43008. if (!this._refractionTexture.isCube) {
  43009. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43010. if (this._refractionTexture.depth) {
  43011. depth = this._refractionTexture.depth;
  43012. }
  43013. }
  43014. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43015. }
  43016. }
  43017. // Point size
  43018. if (this.pointsCloud) {
  43019. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43020. }
  43021. if (defines.SPECULARTERM) {
  43022. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43023. }
  43024. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43025. // Diffuse
  43026. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43027. }
  43028. // Textures
  43029. if (scene.texturesEnabled) {
  43030. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43031. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43032. }
  43033. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43034. effect.setTexture("ambientSampler", this._ambientTexture);
  43035. }
  43036. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43037. effect.setTexture("opacitySampler", this._opacityTexture);
  43038. }
  43039. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43040. if (this._reflectionTexture.isCube) {
  43041. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43042. }
  43043. else {
  43044. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43045. }
  43046. }
  43047. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43048. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43049. }
  43050. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43051. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43052. }
  43053. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43054. effect.setTexture("specularSampler", this._specularTexture);
  43055. }
  43056. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43057. effect.setTexture("bumpSampler", this._bumpTexture);
  43058. }
  43059. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43060. var depth = 1.0;
  43061. if (this._refractionTexture.isCube) {
  43062. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43063. }
  43064. else {
  43065. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43066. }
  43067. }
  43068. }
  43069. // Clip plane
  43070. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43071. // Colors
  43072. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43073. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43074. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43075. }
  43076. if (mustRebind || !this.isFrozen) {
  43077. // Lights
  43078. if (scene.lightsEnabled && !this._disableLighting) {
  43079. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43080. }
  43081. // View
  43082. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43083. this.bindView(effect);
  43084. }
  43085. // Fog
  43086. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43087. // Morph targets
  43088. if (defines.NUM_MORPH_INFLUENCERS) {
  43089. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43090. }
  43091. // Log. depth
  43092. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43093. // image processing
  43094. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43095. this._imageProcessingConfiguration.bind(this._activeEffect);
  43096. }
  43097. }
  43098. this._uniformBuffer.update();
  43099. this._afterBind(mesh, this._activeEffect);
  43100. };
  43101. StandardMaterial.prototype.getAnimatables = function () {
  43102. var results = [];
  43103. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43104. results.push(this._diffuseTexture);
  43105. }
  43106. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43107. results.push(this._ambientTexture);
  43108. }
  43109. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43110. results.push(this._opacityTexture);
  43111. }
  43112. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43113. results.push(this._reflectionTexture);
  43114. }
  43115. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43116. results.push(this._emissiveTexture);
  43117. }
  43118. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43119. results.push(this._specularTexture);
  43120. }
  43121. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43122. results.push(this._bumpTexture);
  43123. }
  43124. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43125. results.push(this._lightmapTexture);
  43126. }
  43127. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43128. results.push(this._refractionTexture);
  43129. }
  43130. return results;
  43131. };
  43132. StandardMaterial.prototype.getActiveTextures = function () {
  43133. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43134. if (this._diffuseTexture) {
  43135. activeTextures.push(this._diffuseTexture);
  43136. }
  43137. if (this._ambientTexture) {
  43138. activeTextures.push(this._ambientTexture);
  43139. }
  43140. if (this._opacityTexture) {
  43141. activeTextures.push(this._opacityTexture);
  43142. }
  43143. if (this._reflectionTexture) {
  43144. activeTextures.push(this._reflectionTexture);
  43145. }
  43146. if (this._emissiveTexture) {
  43147. activeTextures.push(this._emissiveTexture);
  43148. }
  43149. if (this._specularTexture) {
  43150. activeTextures.push(this._specularTexture);
  43151. }
  43152. if (this._bumpTexture) {
  43153. activeTextures.push(this._bumpTexture);
  43154. }
  43155. if (this._lightmapTexture) {
  43156. activeTextures.push(this._lightmapTexture);
  43157. }
  43158. if (this._refractionTexture) {
  43159. activeTextures.push(this._refractionTexture);
  43160. }
  43161. return activeTextures;
  43162. };
  43163. StandardMaterial.prototype.hasTexture = function (texture) {
  43164. if (_super.prototype.hasTexture.call(this, texture)) {
  43165. return true;
  43166. }
  43167. if (this._diffuseTexture === texture) {
  43168. return true;
  43169. }
  43170. if (this._ambientTexture === texture) {
  43171. return true;
  43172. }
  43173. if (this._opacityTexture === texture) {
  43174. return true;
  43175. }
  43176. if (this._reflectionTexture === texture) {
  43177. return true;
  43178. }
  43179. if (this._emissiveTexture === texture) {
  43180. return true;
  43181. }
  43182. if (this._specularTexture === texture) {
  43183. return true;
  43184. }
  43185. if (this._bumpTexture === texture) {
  43186. return true;
  43187. }
  43188. if (this._lightmapTexture === texture) {
  43189. return true;
  43190. }
  43191. if (this._refractionTexture === texture) {
  43192. return true;
  43193. }
  43194. return false;
  43195. };
  43196. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43197. if (forceDisposeTextures) {
  43198. if (this._diffuseTexture) {
  43199. this._diffuseTexture.dispose();
  43200. }
  43201. if (this._ambientTexture) {
  43202. this._ambientTexture.dispose();
  43203. }
  43204. if (this._opacityTexture) {
  43205. this._opacityTexture.dispose();
  43206. }
  43207. if (this._reflectionTexture) {
  43208. this._reflectionTexture.dispose();
  43209. }
  43210. if (this._emissiveTexture) {
  43211. this._emissiveTexture.dispose();
  43212. }
  43213. if (this._specularTexture) {
  43214. this._specularTexture.dispose();
  43215. }
  43216. if (this._bumpTexture) {
  43217. this._bumpTexture.dispose();
  43218. }
  43219. if (this._lightmapTexture) {
  43220. this._lightmapTexture.dispose();
  43221. }
  43222. if (this._refractionTexture) {
  43223. this._refractionTexture.dispose();
  43224. }
  43225. }
  43226. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43227. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43228. }
  43229. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43230. };
  43231. StandardMaterial.prototype.clone = function (name) {
  43232. var _this = this;
  43233. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43234. result.name = name;
  43235. result.id = name;
  43236. return result;
  43237. };
  43238. StandardMaterial.prototype.serialize = function () {
  43239. return BABYLON.SerializationHelper.Serialize(this);
  43240. };
  43241. // Statics
  43242. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43243. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43244. };
  43245. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43246. get: function () {
  43247. return StandardMaterial._DiffuseTextureEnabled;
  43248. },
  43249. set: function (value) {
  43250. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43251. return;
  43252. }
  43253. StandardMaterial._DiffuseTextureEnabled = value;
  43254. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43255. },
  43256. enumerable: true,
  43257. configurable: true
  43258. });
  43259. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43260. get: function () {
  43261. return StandardMaterial._AmbientTextureEnabled;
  43262. },
  43263. set: function (value) {
  43264. if (StandardMaterial._AmbientTextureEnabled === value) {
  43265. return;
  43266. }
  43267. StandardMaterial._AmbientTextureEnabled = value;
  43268. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43269. },
  43270. enumerable: true,
  43271. configurable: true
  43272. });
  43273. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43274. get: function () {
  43275. return StandardMaterial._OpacityTextureEnabled;
  43276. },
  43277. set: function (value) {
  43278. if (StandardMaterial._OpacityTextureEnabled === value) {
  43279. return;
  43280. }
  43281. StandardMaterial._OpacityTextureEnabled = value;
  43282. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43283. },
  43284. enumerable: true,
  43285. configurable: true
  43286. });
  43287. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43288. get: function () {
  43289. return StandardMaterial._ReflectionTextureEnabled;
  43290. },
  43291. set: function (value) {
  43292. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43293. return;
  43294. }
  43295. StandardMaterial._ReflectionTextureEnabled = value;
  43296. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43297. },
  43298. enumerable: true,
  43299. configurable: true
  43300. });
  43301. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43302. get: function () {
  43303. return StandardMaterial._EmissiveTextureEnabled;
  43304. },
  43305. set: function (value) {
  43306. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43307. return;
  43308. }
  43309. StandardMaterial._EmissiveTextureEnabled = value;
  43310. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43311. },
  43312. enumerable: true,
  43313. configurable: true
  43314. });
  43315. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43316. get: function () {
  43317. return StandardMaterial._SpecularTextureEnabled;
  43318. },
  43319. set: function (value) {
  43320. if (StandardMaterial._SpecularTextureEnabled === value) {
  43321. return;
  43322. }
  43323. StandardMaterial._SpecularTextureEnabled = value;
  43324. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43325. },
  43326. enumerable: true,
  43327. configurable: true
  43328. });
  43329. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43330. get: function () {
  43331. return StandardMaterial._BumpTextureEnabled;
  43332. },
  43333. set: function (value) {
  43334. if (StandardMaterial._BumpTextureEnabled === value) {
  43335. return;
  43336. }
  43337. StandardMaterial._BumpTextureEnabled = value;
  43338. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43339. },
  43340. enumerable: true,
  43341. configurable: true
  43342. });
  43343. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43344. get: function () {
  43345. return StandardMaterial._LightmapTextureEnabled;
  43346. },
  43347. set: function (value) {
  43348. if (StandardMaterial._LightmapTextureEnabled === value) {
  43349. return;
  43350. }
  43351. StandardMaterial._LightmapTextureEnabled = value;
  43352. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43353. },
  43354. enumerable: true,
  43355. configurable: true
  43356. });
  43357. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43358. get: function () {
  43359. return StandardMaterial._RefractionTextureEnabled;
  43360. },
  43361. set: function (value) {
  43362. if (StandardMaterial._RefractionTextureEnabled === value) {
  43363. return;
  43364. }
  43365. StandardMaterial._RefractionTextureEnabled = value;
  43366. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43367. },
  43368. enumerable: true,
  43369. configurable: true
  43370. });
  43371. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43372. get: function () {
  43373. return StandardMaterial._ColorGradingTextureEnabled;
  43374. },
  43375. set: function (value) {
  43376. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43377. return;
  43378. }
  43379. StandardMaterial._ColorGradingTextureEnabled = value;
  43380. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43381. },
  43382. enumerable: true,
  43383. configurable: true
  43384. });
  43385. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43386. get: function () {
  43387. return StandardMaterial._FresnelEnabled;
  43388. },
  43389. set: function (value) {
  43390. if (StandardMaterial._FresnelEnabled === value) {
  43391. return;
  43392. }
  43393. StandardMaterial._FresnelEnabled = value;
  43394. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43395. },
  43396. enumerable: true,
  43397. configurable: true
  43398. });
  43399. // Flags used to enable or disable a type of texture for all Standard Materials
  43400. StandardMaterial._DiffuseTextureEnabled = true;
  43401. StandardMaterial._AmbientTextureEnabled = true;
  43402. StandardMaterial._OpacityTextureEnabled = true;
  43403. StandardMaterial._ReflectionTextureEnabled = true;
  43404. StandardMaterial._EmissiveTextureEnabled = true;
  43405. StandardMaterial._SpecularTextureEnabled = true;
  43406. StandardMaterial._BumpTextureEnabled = true;
  43407. StandardMaterial._LightmapTextureEnabled = true;
  43408. StandardMaterial._RefractionTextureEnabled = true;
  43409. StandardMaterial._ColorGradingTextureEnabled = true;
  43410. StandardMaterial._FresnelEnabled = true;
  43411. __decorate([
  43412. BABYLON.serializeAsTexture("diffuseTexture")
  43413. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43414. __decorate([
  43415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43416. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43417. __decorate([
  43418. BABYLON.serializeAsTexture("ambientTexture")
  43419. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43420. __decorate([
  43421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43422. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43423. __decorate([
  43424. BABYLON.serializeAsTexture("opacityTexture")
  43425. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43426. __decorate([
  43427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43428. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43429. __decorate([
  43430. BABYLON.serializeAsTexture("reflectionTexture")
  43431. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43432. __decorate([
  43433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43434. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43435. __decorate([
  43436. BABYLON.serializeAsTexture("emissiveTexture")
  43437. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43438. __decorate([
  43439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43440. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43441. __decorate([
  43442. BABYLON.serializeAsTexture("specularTexture")
  43443. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43444. __decorate([
  43445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43446. ], StandardMaterial.prototype, "specularTexture", void 0);
  43447. __decorate([
  43448. BABYLON.serializeAsTexture("bumpTexture")
  43449. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43450. __decorate([
  43451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43452. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43453. __decorate([
  43454. BABYLON.serializeAsTexture("lightmapTexture")
  43455. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43456. __decorate([
  43457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43458. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43459. __decorate([
  43460. BABYLON.serializeAsTexture("refractionTexture")
  43461. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43462. __decorate([
  43463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43464. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43465. __decorate([
  43466. BABYLON.serializeAsColor3("ambient")
  43467. ], StandardMaterial.prototype, "ambientColor", void 0);
  43468. __decorate([
  43469. BABYLON.serializeAsColor3("diffuse")
  43470. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43471. __decorate([
  43472. BABYLON.serializeAsColor3("specular")
  43473. ], StandardMaterial.prototype, "specularColor", void 0);
  43474. __decorate([
  43475. BABYLON.serializeAsColor3("emissive")
  43476. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43477. __decorate([
  43478. BABYLON.serialize()
  43479. ], StandardMaterial.prototype, "specularPower", void 0);
  43480. __decorate([
  43481. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43482. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43483. __decorate([
  43484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43485. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43486. __decorate([
  43487. BABYLON.serialize("useEmissiveAsIllumination")
  43488. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43489. __decorate([
  43490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43491. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43492. __decorate([
  43493. BABYLON.serialize("linkEmissiveWithDiffuse")
  43494. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43495. __decorate([
  43496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43497. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43498. __decorate([
  43499. BABYLON.serialize("useSpecularOverAlpha")
  43500. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43501. __decorate([
  43502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43503. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43504. __decorate([
  43505. BABYLON.serialize("useReflectionOverAlpha")
  43506. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43507. __decorate([
  43508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43509. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43510. __decorate([
  43511. BABYLON.serialize("disableLighting")
  43512. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43513. __decorate([
  43514. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43515. ], StandardMaterial.prototype, "disableLighting", void 0);
  43516. __decorate([
  43517. BABYLON.serialize("useObjectSpaceNormalMap")
  43518. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43519. __decorate([
  43520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43521. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43522. __decorate([
  43523. BABYLON.serialize("useParallax")
  43524. ], StandardMaterial.prototype, "_useParallax", void 0);
  43525. __decorate([
  43526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43527. ], StandardMaterial.prototype, "useParallax", void 0);
  43528. __decorate([
  43529. BABYLON.serialize("useParallaxOcclusion")
  43530. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43531. __decorate([
  43532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43533. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43534. __decorate([
  43535. BABYLON.serialize()
  43536. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43537. __decorate([
  43538. BABYLON.serialize("roughness")
  43539. ], StandardMaterial.prototype, "_roughness", void 0);
  43540. __decorate([
  43541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43542. ], StandardMaterial.prototype, "roughness", void 0);
  43543. __decorate([
  43544. BABYLON.serialize()
  43545. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43546. __decorate([
  43547. BABYLON.serialize()
  43548. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43549. __decorate([
  43550. BABYLON.serialize("useLightmapAsShadowmap")
  43551. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43552. __decorate([
  43553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43554. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43555. __decorate([
  43556. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43557. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43558. __decorate([
  43559. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43560. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43561. __decorate([
  43562. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43563. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43564. __decorate([
  43565. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43566. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43567. __decorate([
  43568. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43569. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43570. __decorate([
  43571. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43572. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43573. __decorate([
  43574. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43575. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43576. __decorate([
  43577. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43578. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43579. __decorate([
  43580. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43581. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43582. __decorate([
  43583. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43584. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43585. __decorate([
  43586. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43587. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43588. __decorate([
  43589. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43590. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43591. __decorate([
  43592. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43593. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43594. __decorate([
  43595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43596. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43597. __decorate([
  43598. BABYLON.serialize("maxSimultaneousLights")
  43599. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43600. __decorate([
  43601. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43602. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43603. __decorate([
  43604. BABYLON.serialize("invertNormalMapX")
  43605. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43606. __decorate([
  43607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43608. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43609. __decorate([
  43610. BABYLON.serialize("invertNormalMapY")
  43611. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43612. __decorate([
  43613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43614. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43615. __decorate([
  43616. BABYLON.serialize("twoSidedLighting")
  43617. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43618. __decorate([
  43619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43620. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43621. __decorate([
  43622. BABYLON.serialize()
  43623. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43624. return StandardMaterial;
  43625. }(BABYLON.PushMaterial));
  43626. BABYLON.StandardMaterial = StandardMaterial;
  43627. })(BABYLON || (BABYLON = {}));
  43628. //# sourceMappingURL=babylon.standardMaterial.js.map
  43629. "use strict";
  43630. var BABYLON;
  43631. (function (BABYLON) {
  43632. /**
  43633. * Manages the defines for the PBR Material.
  43634. * @ignoreChildren
  43635. */
  43636. var PBRMaterialDefines = /** @class */ (function (_super) {
  43637. __extends(PBRMaterialDefines, _super);
  43638. /**
  43639. * Initializes the PBR Material defines.
  43640. */
  43641. function PBRMaterialDefines() {
  43642. var _this = _super.call(this) || this;
  43643. _this.PBR = true;
  43644. _this.MAINUV1 = false;
  43645. _this.MAINUV2 = false;
  43646. _this.UV1 = false;
  43647. _this.UV2 = false;
  43648. _this.ALBEDO = false;
  43649. _this.ALBEDODIRECTUV = 0;
  43650. _this.VERTEXCOLOR = false;
  43651. _this.AMBIENT = false;
  43652. _this.AMBIENTDIRECTUV = 0;
  43653. _this.AMBIENTINGRAYSCALE = false;
  43654. _this.OPACITY = false;
  43655. _this.VERTEXALPHA = false;
  43656. _this.OPACITYDIRECTUV = 0;
  43657. _this.OPACITYRGB = false;
  43658. _this.ALPHATEST = false;
  43659. _this.DEPTHPREPASS = false;
  43660. _this.ALPHABLEND = false;
  43661. _this.ALPHAFROMALBEDO = false;
  43662. _this.ALPHATESTVALUE = "0.5";
  43663. _this.SPECULAROVERALPHA = false;
  43664. _this.RADIANCEOVERALPHA = false;
  43665. _this.ALPHAFRESNEL = false;
  43666. _this.LINEARALPHAFRESNEL = false;
  43667. _this.PREMULTIPLYALPHA = false;
  43668. _this.EMISSIVE = false;
  43669. _this.EMISSIVEDIRECTUV = 0;
  43670. _this.REFLECTIVITY = false;
  43671. _this.REFLECTIVITYDIRECTUV = 0;
  43672. _this.SPECULARTERM = false;
  43673. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43674. _this.MICROSURFACEAUTOMATIC = false;
  43675. _this.LODBASEDMICROSFURACE = false;
  43676. _this.MICROSURFACEMAP = false;
  43677. _this.MICROSURFACEMAPDIRECTUV = 0;
  43678. _this.METALLICWORKFLOW = false;
  43679. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43680. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43681. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43682. _this.AOSTOREINMETALMAPRED = false;
  43683. _this.ENVIRONMENTBRDF = false;
  43684. _this.NORMAL = false;
  43685. _this.TANGENT = false;
  43686. _this.BUMP = false;
  43687. _this.BUMPDIRECTUV = 0;
  43688. _this.OBJECTSPACE_NORMALMAP = false;
  43689. _this.PARALLAX = false;
  43690. _this.PARALLAXOCCLUSION = false;
  43691. _this.NORMALXYSCALE = true;
  43692. _this.LIGHTMAP = false;
  43693. _this.LIGHTMAPDIRECTUV = 0;
  43694. _this.USELIGHTMAPASSHADOWMAP = false;
  43695. _this.GAMMALIGHTMAP = false;
  43696. _this.REFLECTION = false;
  43697. _this.REFLECTIONMAP_3D = false;
  43698. _this.REFLECTIONMAP_SPHERICAL = false;
  43699. _this.REFLECTIONMAP_PLANAR = false;
  43700. _this.REFLECTIONMAP_CUBIC = false;
  43701. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43702. _this.REFLECTIONMAP_PROJECTION = false;
  43703. _this.REFLECTIONMAP_SKYBOX = false;
  43704. _this.REFLECTIONMAP_EXPLICIT = false;
  43705. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43706. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43707. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43708. _this.INVERTCUBICMAP = false;
  43709. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43710. _this.USESPHERICALINVERTEX = false;
  43711. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43712. _this.LODINREFLECTIONALPHA = false;
  43713. _this.GAMMAREFLECTION = false;
  43714. _this.RADIANCEOCCLUSION = false;
  43715. _this.HORIZONOCCLUSION = false;
  43716. _this.REFRACTION = false;
  43717. _this.REFRACTIONMAP_3D = false;
  43718. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43719. _this.LODINREFRACTIONALPHA = false;
  43720. _this.GAMMAREFRACTION = false;
  43721. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43722. _this.INSTANCES = false;
  43723. _this.NUM_BONE_INFLUENCERS = 0;
  43724. _this.BonesPerMesh = 0;
  43725. _this.NONUNIFORMSCALING = false;
  43726. _this.MORPHTARGETS = false;
  43727. _this.MORPHTARGETS_NORMAL = false;
  43728. _this.MORPHTARGETS_TANGENT = false;
  43729. _this.NUM_MORPH_INFLUENCERS = 0;
  43730. _this.IMAGEPROCESSING = false;
  43731. _this.VIGNETTE = false;
  43732. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43733. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43734. _this.TONEMAPPING = false;
  43735. _this.CONTRAST = false;
  43736. _this.COLORCURVES = false;
  43737. _this.COLORGRADING = false;
  43738. _this.COLORGRADING3D = false;
  43739. _this.SAMPLER3DGREENDEPTH = false;
  43740. _this.SAMPLER3DBGRMAP = false;
  43741. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43742. _this.EXPOSURE = false;
  43743. _this.USEPHYSICALLIGHTFALLOFF = false;
  43744. _this.TWOSIDEDLIGHTING = false;
  43745. _this.SHADOWFLOAT = false;
  43746. _this.CLIPPLANE = false;
  43747. _this.POINTSIZE = false;
  43748. _this.FOG = false;
  43749. _this.LOGARITHMICDEPTH = false;
  43750. _this.FORCENORMALFORWARD = false;
  43751. _this.GEOMETRYAA = false;
  43752. _this.UNLIT = false;
  43753. _this.rebuild();
  43754. return _this;
  43755. }
  43756. /**
  43757. * Resets the PBR Material defines.
  43758. */
  43759. PBRMaterialDefines.prototype.reset = function () {
  43760. _super.prototype.reset.call(this);
  43761. this.ALPHATESTVALUE = "0.5";
  43762. this.PBR = true;
  43763. };
  43764. return PBRMaterialDefines;
  43765. }(BABYLON.MaterialDefines));
  43766. /**
  43767. * The Physically based material base class of BJS.
  43768. *
  43769. * This offers the main features of a standard PBR material.
  43770. * For more information, please refer to the documentation :
  43771. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43772. */
  43773. var PBRBaseMaterial = /** @class */ (function (_super) {
  43774. __extends(PBRBaseMaterial, _super);
  43775. /**
  43776. * Instantiates a new PBRMaterial instance.
  43777. *
  43778. * @param name The material name
  43779. * @param scene The scene the material will be use in.
  43780. */
  43781. function PBRBaseMaterial(name, scene) {
  43782. var _this = _super.call(this, name, scene) || this;
  43783. /**
  43784. * Intensity of the direct lights e.g. the four lights available in your scene.
  43785. * This impacts both the direct diffuse and specular highlights.
  43786. */
  43787. _this._directIntensity = 1.0;
  43788. /**
  43789. * Intensity of the emissive part of the material.
  43790. * This helps controlling the emissive effect without modifying the emissive color.
  43791. */
  43792. _this._emissiveIntensity = 1.0;
  43793. /**
  43794. * Intensity of the environment e.g. how much the environment will light the object
  43795. * either through harmonics for rough material or through the refelction for shiny ones.
  43796. */
  43797. _this._environmentIntensity = 1.0;
  43798. /**
  43799. * This is a special control allowing the reduction of the specular highlights coming from the
  43800. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43801. */
  43802. _this._specularIntensity = 1.0;
  43803. /**
  43804. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43805. */
  43806. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43807. /**
  43808. * Debug Control allowing disabling the bump map on this material.
  43809. */
  43810. _this._disableBumpMap = false;
  43811. /**
  43812. * AKA Occlusion Texture Intensity in other nomenclature.
  43813. */
  43814. _this._ambientTextureStrength = 1.0;
  43815. /**
  43816. * The color of a material in ambient lighting.
  43817. */
  43818. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43819. /**
  43820. * AKA Diffuse Color in other nomenclature.
  43821. */
  43822. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43823. /**
  43824. * AKA Specular Color in other nomenclature.
  43825. */
  43826. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43827. /**
  43828. * The color applied when light is reflected from a material.
  43829. */
  43830. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43831. /**
  43832. * The color applied when light is emitted from a material.
  43833. */
  43834. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43835. /**
  43836. * AKA Glossiness in other nomenclature.
  43837. */
  43838. _this._microSurface = 0.9;
  43839. /**
  43840. * source material index of refraction (IOR)' / 'destination material IOR.
  43841. */
  43842. _this._indexOfRefraction = 0.66;
  43843. /**
  43844. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43845. */
  43846. _this._invertRefractionY = false;
  43847. /**
  43848. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43849. * Materials half opaque for instance using refraction could benefit from this control.
  43850. */
  43851. _this._linkRefractionWithTransparency = false;
  43852. /**
  43853. * Specifies that the material will use the light map as a show map.
  43854. */
  43855. _this._useLightmapAsShadowmap = false;
  43856. /**
  43857. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43858. * makes the reflect vector face the model (under horizon).
  43859. */
  43860. _this._useHorizonOcclusion = true;
  43861. /**
  43862. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43863. * too much the area relying on ambient texture to define their ambient occlusion.
  43864. */
  43865. _this._useRadianceOcclusion = true;
  43866. /**
  43867. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43868. */
  43869. _this._useAlphaFromAlbedoTexture = false;
  43870. /**
  43871. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43872. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43873. */
  43874. _this._useSpecularOverAlpha = true;
  43875. /**
  43876. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43877. */
  43878. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43879. /**
  43880. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43881. */
  43882. _this._useRoughnessFromMetallicTextureAlpha = true;
  43883. /**
  43884. * Specifies if the metallic texture contains the roughness information in its green channel.
  43885. */
  43886. _this._useRoughnessFromMetallicTextureGreen = false;
  43887. /**
  43888. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43889. */
  43890. _this._useMetallnessFromMetallicTextureBlue = false;
  43891. /**
  43892. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43893. */
  43894. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43895. /**
  43896. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43897. */
  43898. _this._useAmbientInGrayScale = false;
  43899. /**
  43900. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43901. * The material will try to infer what glossiness each pixel should be.
  43902. */
  43903. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43904. /**
  43905. * BJS is using an harcoded light falloff based on a manually sets up range.
  43906. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43907. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43908. */
  43909. _this._usePhysicalLightFalloff = true;
  43910. /**
  43911. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43912. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43913. */
  43914. _this._useRadianceOverAlpha = true;
  43915. /**
  43916. * Allows using an object space normal map (instead of tangent space).
  43917. */
  43918. _this._useObjectSpaceNormalMap = false;
  43919. /**
  43920. * Allows using the bump map in parallax mode.
  43921. */
  43922. _this._useParallax = false;
  43923. /**
  43924. * Allows using the bump map in parallax occlusion mode.
  43925. */
  43926. _this._useParallaxOcclusion = false;
  43927. /**
  43928. * Controls the scale bias of the parallax mode.
  43929. */
  43930. _this._parallaxScaleBias = 0.05;
  43931. /**
  43932. * If sets to true, disables all the lights affecting the material.
  43933. */
  43934. _this._disableLighting = false;
  43935. /**
  43936. * Number of Simultaneous lights allowed on the material.
  43937. */
  43938. _this._maxSimultaneousLights = 4;
  43939. /**
  43940. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43941. */
  43942. _this._invertNormalMapX = false;
  43943. /**
  43944. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43945. */
  43946. _this._invertNormalMapY = false;
  43947. /**
  43948. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43949. */
  43950. _this._twoSidedLighting = false;
  43951. /**
  43952. * Defines the alpha limits in alpha test mode.
  43953. */
  43954. _this._alphaCutOff = 0.4;
  43955. /**
  43956. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43957. */
  43958. _this._forceAlphaTest = false;
  43959. /**
  43960. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43961. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43962. */
  43963. _this._useAlphaFresnel = false;
  43964. /**
  43965. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43966. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43967. */
  43968. _this._useLinearAlphaFresnel = false;
  43969. /**
  43970. * The transparency mode of the material.
  43971. */
  43972. _this._transparencyMode = null;
  43973. /**
  43974. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43975. * from cos thetav and roughness:
  43976. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43977. */
  43978. _this._environmentBRDFTexture = null;
  43979. /**
  43980. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43981. */
  43982. _this._forceIrradianceInFragment = false;
  43983. /**
  43984. * Force normal to face away from face.
  43985. */
  43986. _this._forceNormalForward = false;
  43987. /**
  43988. * Enables specular anti aliasing in the PBR shader.
  43989. * It will both interacts on the Geometry for analytical and IBL lighting.
  43990. * It also prefilter the roughness map based on the bump values.
  43991. */
  43992. _this._enableSpecularAntiAliasing = false;
  43993. /**
  43994. * Stores the available render targets.
  43995. */
  43996. _this._renderTargets = new BABYLON.SmartArray(16);
  43997. /**
  43998. * Sets the global ambient color for the material used in lighting calculations.
  43999. */
  44000. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44001. /**
  44002. * If set to true, no lighting calculations will be applied.
  44003. */
  44004. _this._unlit = false;
  44005. // Setup the default processing configuration to the scene.
  44006. _this._attachImageProcessingConfiguration(null);
  44007. _this.getRenderTargetTextures = function () {
  44008. _this._renderTargets.reset();
  44009. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44010. _this._renderTargets.push(_this._reflectionTexture);
  44011. }
  44012. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44013. _this._renderTargets.push(_this._refractionTexture);
  44014. }
  44015. return _this._renderTargets;
  44016. };
  44017. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44018. return _this;
  44019. }
  44020. /**
  44021. * Attaches a new image processing configuration to the PBR Material.
  44022. * @param configuration
  44023. */
  44024. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44025. var _this = this;
  44026. if (configuration === this._imageProcessingConfiguration) {
  44027. return;
  44028. }
  44029. // Detaches observer.
  44030. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44031. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44032. }
  44033. // Pick the scene configuration if needed.
  44034. if (!configuration) {
  44035. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44036. }
  44037. else {
  44038. this._imageProcessingConfiguration = configuration;
  44039. }
  44040. // Attaches observer.
  44041. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44042. _this._markAllSubMeshesAsImageProcessingDirty();
  44043. });
  44044. };
  44045. /**
  44046. * Gets the name of the material class.
  44047. */
  44048. PBRBaseMaterial.prototype.getClassName = function () {
  44049. return "PBRBaseMaterial";
  44050. };
  44051. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44052. /**
  44053. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44054. */
  44055. get: function () {
  44056. return this._useLogarithmicDepth;
  44057. },
  44058. /**
  44059. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44060. */
  44061. set: function (value) {
  44062. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44063. },
  44064. enumerable: true,
  44065. configurable: true
  44066. });
  44067. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44068. /**
  44069. * Gets the current transparency mode.
  44070. */
  44071. get: function () {
  44072. return this._transparencyMode;
  44073. },
  44074. /**
  44075. * Sets the transparency mode of the material.
  44076. */
  44077. set: function (value) {
  44078. if (this._transparencyMode === value) {
  44079. return;
  44080. }
  44081. this._transparencyMode = value;
  44082. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44083. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44084. },
  44085. enumerable: true,
  44086. configurable: true
  44087. });
  44088. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44089. /**
  44090. * Returns true if alpha blending should be disabled.
  44091. */
  44092. get: function () {
  44093. return (this._linkRefractionWithTransparency ||
  44094. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44095. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44096. },
  44097. enumerable: true,
  44098. configurable: true
  44099. });
  44100. /**
  44101. * Specifies whether or not this material should be rendered in alpha blend mode.
  44102. */
  44103. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44104. if (this._disableAlphaBlending) {
  44105. return false;
  44106. }
  44107. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44108. };
  44109. /**
  44110. * Specifies if the mesh will require alpha blending.
  44111. * @param mesh - BJS mesh.
  44112. */
  44113. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44114. if (this._disableAlphaBlending) {
  44115. return false;
  44116. }
  44117. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44118. };
  44119. /**
  44120. * Specifies whether or not this material should be rendered in alpha test mode.
  44121. */
  44122. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44123. if (this._forceAlphaTest) {
  44124. return true;
  44125. }
  44126. if (this._linkRefractionWithTransparency) {
  44127. return false;
  44128. }
  44129. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44130. };
  44131. /**
  44132. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44133. */
  44134. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44135. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44136. };
  44137. /**
  44138. * Gets the texture used for the alpha test.
  44139. */
  44140. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44141. return this._albedoTexture;
  44142. };
  44143. /**
  44144. * Specifies that the submesh is ready to be used.
  44145. * @param mesh - BJS mesh.
  44146. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44147. * @param useInstances - Specifies that instances should be used.
  44148. * @returns - boolean indicating that the submesh is ready or not.
  44149. */
  44150. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44151. if (subMesh.effect && this.isFrozen) {
  44152. if (this._wasPreviouslyReady) {
  44153. return true;
  44154. }
  44155. }
  44156. if (!subMesh._materialDefines) {
  44157. subMesh._materialDefines = new PBRMaterialDefines();
  44158. }
  44159. var defines = subMesh._materialDefines;
  44160. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44161. if (defines._renderId === this.getScene().getRenderId()) {
  44162. return true;
  44163. }
  44164. }
  44165. var scene = this.getScene();
  44166. var engine = scene.getEngine();
  44167. if (defines._areTexturesDirty) {
  44168. if (scene.texturesEnabled) {
  44169. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44170. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44171. return false;
  44172. }
  44173. }
  44174. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44175. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44176. return false;
  44177. }
  44178. }
  44179. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44180. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44181. return false;
  44182. }
  44183. }
  44184. var reflectionTexture = this._getReflectionTexture();
  44185. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44186. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44187. return false;
  44188. }
  44189. }
  44190. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44191. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44192. return false;
  44193. }
  44194. }
  44195. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44196. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44197. return false;
  44198. }
  44199. }
  44200. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44201. if (this._metallicTexture) {
  44202. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44203. return false;
  44204. }
  44205. }
  44206. else if (this._reflectivityTexture) {
  44207. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44208. return false;
  44209. }
  44210. }
  44211. if (this._microSurfaceTexture) {
  44212. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44213. return false;
  44214. }
  44215. }
  44216. }
  44217. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44218. // Bump texture cannot be not blocking.
  44219. if (!this._bumpTexture.isReady()) {
  44220. return false;
  44221. }
  44222. }
  44223. var refractionTexture = this._getRefractionTexture();
  44224. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44225. if (!refractionTexture.isReadyOrNotBlocking()) {
  44226. return false;
  44227. }
  44228. }
  44229. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44230. // This is blocking.
  44231. if (!this._environmentBRDFTexture.isReady()) {
  44232. return false;
  44233. }
  44234. }
  44235. }
  44236. }
  44237. if (defines._areImageProcessingDirty) {
  44238. if (!this._imageProcessingConfiguration.isReady()) {
  44239. return false;
  44240. }
  44241. }
  44242. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44243. mesh.createNormals(true);
  44244. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44245. }
  44246. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44247. if (effect) {
  44248. scene.resetCachedMaterial();
  44249. subMesh.setEffect(effect, defines);
  44250. this.buildUniformLayout();
  44251. }
  44252. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44253. return false;
  44254. }
  44255. defines._renderId = scene.getRenderId();
  44256. this._wasPreviouslyReady = true;
  44257. return true;
  44258. };
  44259. /**
  44260. * Specifies if the material uses metallic roughness workflow.
  44261. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44262. */
  44263. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44264. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44265. return true;
  44266. }
  44267. return false;
  44268. };
  44269. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44270. if (onCompiled === void 0) { onCompiled = null; }
  44271. if (onError === void 0) { onError = null; }
  44272. if (useInstances === void 0) { useInstances = null; }
  44273. if (useClipPlane === void 0) { useClipPlane = null; }
  44274. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44275. if (!defines.isDirty) {
  44276. return null;
  44277. }
  44278. defines.markAsProcessed();
  44279. var scene = this.getScene();
  44280. var engine = scene.getEngine();
  44281. // Fallbacks
  44282. var fallbacks = new BABYLON.EffectFallbacks();
  44283. var fallbackRank = 0;
  44284. if (defines.USESPHERICALINVERTEX) {
  44285. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44286. }
  44287. if (defines.FOG) {
  44288. fallbacks.addFallback(fallbackRank, "FOG");
  44289. }
  44290. if (defines.POINTSIZE) {
  44291. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44292. }
  44293. if (defines.LOGARITHMICDEPTH) {
  44294. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44295. }
  44296. if (defines.PARALLAX) {
  44297. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44298. }
  44299. if (defines.PARALLAXOCCLUSION) {
  44300. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44301. }
  44302. if (defines.ENVIRONMENTBRDF) {
  44303. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44304. }
  44305. if (defines.TANGENT) {
  44306. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44307. }
  44308. if (defines.BUMP) {
  44309. fallbacks.addFallback(fallbackRank++, "BUMP");
  44310. }
  44311. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44312. if (defines.SPECULARTERM) {
  44313. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44314. }
  44315. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44316. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44317. }
  44318. if (defines.LIGHTMAP) {
  44319. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44320. }
  44321. if (defines.NORMAL) {
  44322. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44323. }
  44324. if (defines.AMBIENT) {
  44325. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44326. }
  44327. if (defines.EMISSIVE) {
  44328. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44329. }
  44330. if (defines.VERTEXCOLOR) {
  44331. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44332. }
  44333. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44334. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44335. }
  44336. if (defines.MORPHTARGETS) {
  44337. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44338. }
  44339. //Attributes
  44340. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44341. if (defines.NORMAL) {
  44342. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44343. }
  44344. if (defines.TANGENT) {
  44345. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44346. }
  44347. if (defines.UV1) {
  44348. attribs.push(BABYLON.VertexBuffer.UVKind);
  44349. }
  44350. if (defines.UV2) {
  44351. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44352. }
  44353. if (defines.VERTEXCOLOR) {
  44354. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44355. }
  44356. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44357. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44358. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44359. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44360. "vFogInfos", "vFogColor", "pointSize",
  44361. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44362. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44363. "mBones",
  44364. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44365. "vLightingIntensity",
  44366. "logarithmicDepthConstant",
  44367. "vSphericalX", "vSphericalY", "vSphericalZ",
  44368. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44369. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44370. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44371. "vTangentSpaceParams"
  44372. ];
  44373. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44374. "bumpSampler", "lightmapSampler", "opacitySampler",
  44375. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44376. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44377. "microSurfaceSampler", "environmentBrdfSampler"];
  44378. var uniformBuffers = ["Material", "Scene"];
  44379. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44380. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44381. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44382. uniformsNames: uniforms,
  44383. uniformBuffersNames: uniformBuffers,
  44384. samplers: samplers,
  44385. defines: defines,
  44386. maxSimultaneousLights: this._maxSimultaneousLights
  44387. });
  44388. var join = defines.toString();
  44389. return engine.createEffect("pbr", {
  44390. attributes: attribs,
  44391. uniformsNames: uniforms,
  44392. uniformBuffersNames: uniformBuffers,
  44393. samplers: samplers,
  44394. defines: join,
  44395. fallbacks: fallbacks,
  44396. onCompiled: onCompiled,
  44397. onError: onError,
  44398. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44399. }, engine);
  44400. };
  44401. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44402. if (useInstances === void 0) { useInstances = null; }
  44403. if (useClipPlane === void 0) { useClipPlane = null; }
  44404. var scene = this.getScene();
  44405. var engine = scene.getEngine();
  44406. // Lights
  44407. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44408. defines._needNormals = true;
  44409. // Textures
  44410. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44411. if (defines._areTexturesDirty) {
  44412. defines._needUVs = false;
  44413. if (scene.texturesEnabled) {
  44414. if (scene.getEngine().getCaps().textureLOD) {
  44415. defines.LODBASEDMICROSFURACE = true;
  44416. }
  44417. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44418. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44419. }
  44420. else {
  44421. defines.ALBEDO = false;
  44422. }
  44423. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44424. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44425. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44426. }
  44427. else {
  44428. defines.AMBIENT = false;
  44429. }
  44430. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44431. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44432. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44433. }
  44434. else {
  44435. defines.OPACITY = false;
  44436. }
  44437. var reflectionTexture = this._getReflectionTexture();
  44438. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44439. defines.REFLECTION = true;
  44440. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44441. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44442. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44443. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44444. defines.INVERTCUBICMAP = true;
  44445. }
  44446. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44447. switch (reflectionTexture.coordinatesMode) {
  44448. case BABYLON.Texture.CUBIC_MODE:
  44449. case BABYLON.Texture.INVCUBIC_MODE:
  44450. defines.REFLECTIONMAP_CUBIC = true;
  44451. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44452. break;
  44453. case BABYLON.Texture.EXPLICIT_MODE:
  44454. defines.REFLECTIONMAP_EXPLICIT = true;
  44455. break;
  44456. case BABYLON.Texture.PLANAR_MODE:
  44457. defines.REFLECTIONMAP_PLANAR = true;
  44458. break;
  44459. case BABYLON.Texture.PROJECTION_MODE:
  44460. defines.REFLECTIONMAP_PROJECTION = true;
  44461. break;
  44462. case BABYLON.Texture.SKYBOX_MODE:
  44463. defines.REFLECTIONMAP_SKYBOX = true;
  44464. break;
  44465. case BABYLON.Texture.SPHERICAL_MODE:
  44466. defines.REFLECTIONMAP_SPHERICAL = true;
  44467. break;
  44468. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44469. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44470. break;
  44471. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44472. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44473. break;
  44474. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44475. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44476. break;
  44477. }
  44478. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44479. if (reflectionTexture.sphericalPolynomial) {
  44480. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44481. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44482. defines.USESPHERICALINVERTEX = false;
  44483. }
  44484. else {
  44485. defines.USESPHERICALINVERTEX = true;
  44486. }
  44487. }
  44488. }
  44489. }
  44490. else {
  44491. defines.REFLECTION = false;
  44492. defines.REFLECTIONMAP_3D = false;
  44493. defines.REFLECTIONMAP_SPHERICAL = false;
  44494. defines.REFLECTIONMAP_PLANAR = false;
  44495. defines.REFLECTIONMAP_CUBIC = false;
  44496. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44497. defines.REFLECTIONMAP_PROJECTION = false;
  44498. defines.REFLECTIONMAP_SKYBOX = false;
  44499. defines.REFLECTIONMAP_EXPLICIT = false;
  44500. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44501. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44502. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44503. defines.INVERTCUBICMAP = false;
  44504. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44505. defines.USESPHERICALINVERTEX = false;
  44506. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44507. defines.LODINREFLECTIONALPHA = false;
  44508. defines.GAMMAREFLECTION = false;
  44509. }
  44510. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44511. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44512. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44513. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44514. }
  44515. else {
  44516. defines.LIGHTMAP = false;
  44517. }
  44518. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44519. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44520. }
  44521. else {
  44522. defines.EMISSIVE = false;
  44523. }
  44524. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44525. if (this._metallicTexture) {
  44526. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44527. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44528. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44529. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44530. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44531. }
  44532. else if (this._reflectivityTexture) {
  44533. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44534. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44535. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44536. }
  44537. else {
  44538. defines.REFLECTIVITY = false;
  44539. }
  44540. if (this._microSurfaceTexture) {
  44541. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44542. }
  44543. else {
  44544. defines.MICROSURFACEMAP = false;
  44545. }
  44546. }
  44547. else {
  44548. defines.REFLECTIVITY = false;
  44549. defines.MICROSURFACEMAP = false;
  44550. }
  44551. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44552. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44553. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44554. defines.PARALLAX = true;
  44555. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44556. }
  44557. else {
  44558. defines.PARALLAX = false;
  44559. }
  44560. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44561. }
  44562. else {
  44563. defines.BUMP = false;
  44564. }
  44565. var refractionTexture = this._getRefractionTexture();
  44566. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44567. defines.REFRACTION = true;
  44568. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44569. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44570. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44571. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44572. if (this._linkRefractionWithTransparency) {
  44573. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44574. }
  44575. }
  44576. else {
  44577. defines.REFRACTION = false;
  44578. }
  44579. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44580. defines.ENVIRONMENTBRDF = true;
  44581. }
  44582. else {
  44583. defines.ENVIRONMENTBRDF = false;
  44584. }
  44585. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44586. defines.ALPHAFROMALBEDO = true;
  44587. }
  44588. else {
  44589. defines.ALPHAFROMALBEDO = false;
  44590. }
  44591. }
  44592. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44593. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44594. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44595. if (!this.backFaceCulling && this._twoSidedLighting) {
  44596. defines.TWOSIDEDLIGHTING = true;
  44597. }
  44598. else {
  44599. defines.TWOSIDEDLIGHTING = false;
  44600. }
  44601. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44602. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44603. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44604. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44605. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44606. defines.GEOMETRYAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44607. }
  44608. if (defines._areImageProcessingDirty) {
  44609. this._imageProcessingConfiguration.prepareDefines(defines);
  44610. }
  44611. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44612. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44613. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44614. // Misc.
  44615. if (defines._areMiscDirty) {
  44616. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44617. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44618. }
  44619. // Values that need to be evaluated on every frame
  44620. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44621. // Attribs
  44622. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44623. };
  44624. /**
  44625. * Force shader compilation
  44626. */
  44627. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44628. var _this = this;
  44629. var localOptions = __assign({ clipPlane: false }, options);
  44630. var defines = new PBRMaterialDefines();
  44631. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44632. if (effect.isReady()) {
  44633. if (onCompiled) {
  44634. onCompiled(this);
  44635. }
  44636. }
  44637. else {
  44638. effect.onCompileObservable.add(function () {
  44639. if (onCompiled) {
  44640. onCompiled(_this);
  44641. }
  44642. });
  44643. }
  44644. };
  44645. /**
  44646. * Initializes the uniform buffer layout for the shader.
  44647. */
  44648. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44649. // Order is important !
  44650. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44651. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44652. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44653. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44654. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44655. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44656. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44657. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44658. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44659. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44660. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44661. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44662. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44663. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44664. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44665. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44666. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44667. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44668. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44669. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44670. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44671. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44672. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44673. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44674. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44675. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44676. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44677. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44678. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44679. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44680. this._uniformBuffer.addUniform("pointSize", 1);
  44681. this._uniformBuffer.create();
  44682. };
  44683. /**
  44684. * Unbinds the textures.
  44685. */
  44686. PBRBaseMaterial.prototype.unbind = function () {
  44687. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44688. this._uniformBuffer.setTexture("reflectionSampler", null);
  44689. }
  44690. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44691. this._uniformBuffer.setTexture("refractionSampler", null);
  44692. }
  44693. _super.prototype.unbind.call(this);
  44694. };
  44695. /**
  44696. * Binds the submesh data.
  44697. * @param world - The world matrix.
  44698. * @param mesh - The BJS mesh.
  44699. * @param subMesh - A submesh of the BJS mesh.
  44700. */
  44701. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44702. var scene = this.getScene();
  44703. var defines = subMesh._materialDefines;
  44704. if (!defines) {
  44705. return;
  44706. }
  44707. var effect = subMesh.effect;
  44708. if (!effect) {
  44709. return;
  44710. }
  44711. this._activeEffect = effect;
  44712. // Matrices
  44713. this.bindOnlyWorldMatrix(world);
  44714. // Normal Matrix
  44715. if (defines.OBJECTSPACE_NORMALMAP) {
  44716. world.toNormalMatrix(this._normalMatrix);
  44717. this.bindOnlyNormalMatrix(this._normalMatrix);
  44718. }
  44719. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44720. // Bones
  44721. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44722. var reflectionTexture = null;
  44723. if (mustRebind) {
  44724. this._uniformBuffer.bindToEffect(effect, "Material");
  44725. this.bindViewProjection(effect);
  44726. reflectionTexture = this._getReflectionTexture();
  44727. var refractionTexture = this._getRefractionTexture();
  44728. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44729. // Texture uniforms
  44730. if (scene.texturesEnabled) {
  44731. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44732. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44733. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44734. }
  44735. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44736. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44737. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44738. }
  44739. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44740. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44741. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44742. }
  44743. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44744. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44745. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44746. if (reflectionTexture.boundingBoxSize) {
  44747. var cubeTexture = reflectionTexture;
  44748. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44749. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44750. }
  44751. var polynomials = reflectionTexture.sphericalPolynomial;
  44752. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44753. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44754. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44755. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44756. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44757. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44758. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44759. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44760. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44761. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44762. }
  44763. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44764. }
  44765. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44766. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44767. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44768. }
  44769. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44770. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44771. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44772. }
  44773. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44774. if (this._metallicTexture) {
  44775. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44776. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44777. }
  44778. else if (this._reflectivityTexture) {
  44779. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44780. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44781. }
  44782. if (this._microSurfaceTexture) {
  44783. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44784. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44785. }
  44786. }
  44787. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44788. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44789. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44790. if (scene._mirroredCameraPosition) {
  44791. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44792. }
  44793. else {
  44794. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44795. }
  44796. }
  44797. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44798. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44799. var depth = 1.0;
  44800. if (!refractionTexture.isCube) {
  44801. if (refractionTexture.depth) {
  44802. depth = refractionTexture.depth;
  44803. }
  44804. }
  44805. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44806. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44807. }
  44808. }
  44809. // Point size
  44810. if (this.pointsCloud) {
  44811. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44812. }
  44813. // Colors
  44814. if (defines.METALLICWORKFLOW) {
  44815. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44816. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44817. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44818. }
  44819. else {
  44820. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44821. }
  44822. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44823. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44824. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44825. // Misc
  44826. this._lightingInfos.x = this._directIntensity;
  44827. this._lightingInfos.y = this._emissiveIntensity;
  44828. this._lightingInfos.z = this._environmentIntensity;
  44829. this._lightingInfos.w = this._specularIntensity;
  44830. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44831. }
  44832. // Textures
  44833. if (scene.texturesEnabled) {
  44834. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44835. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44836. }
  44837. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44838. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44839. }
  44840. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44841. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44842. }
  44843. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44844. if (defines.LODBASEDMICROSFURACE) {
  44845. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44846. }
  44847. else {
  44848. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44849. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44850. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44851. }
  44852. }
  44853. if (defines.ENVIRONMENTBRDF) {
  44854. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44855. }
  44856. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44857. if (defines.LODBASEDMICROSFURACE) {
  44858. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44859. }
  44860. else {
  44861. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44862. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44863. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44864. }
  44865. }
  44866. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44867. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44868. }
  44869. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44870. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44871. }
  44872. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44873. if (this._metallicTexture) {
  44874. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44875. }
  44876. else if (this._reflectivityTexture) {
  44877. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44878. }
  44879. if (this._microSurfaceTexture) {
  44880. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44881. }
  44882. }
  44883. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44884. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44885. }
  44886. }
  44887. // Clip plane
  44888. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44889. // Colors
  44890. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44891. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44892. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44893. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44894. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44895. }
  44896. if (mustRebind || !this.isFrozen) {
  44897. // Lights
  44898. if (scene.lightsEnabled && !this._disableLighting) {
  44899. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44900. }
  44901. // View
  44902. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44903. this.bindView(effect);
  44904. }
  44905. // Fog
  44906. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44907. // Morph targets
  44908. if (defines.NUM_MORPH_INFLUENCERS) {
  44909. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44910. }
  44911. // image processing
  44912. this._imageProcessingConfiguration.bind(this._activeEffect);
  44913. // Log. depth
  44914. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44915. }
  44916. this._uniformBuffer.update();
  44917. this._afterBind(mesh);
  44918. };
  44919. /**
  44920. * Returns the animatable textures.
  44921. * @returns - Array of animatable textures.
  44922. */
  44923. PBRBaseMaterial.prototype.getAnimatables = function () {
  44924. var results = [];
  44925. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44926. results.push(this._albedoTexture);
  44927. }
  44928. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44929. results.push(this._ambientTexture);
  44930. }
  44931. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44932. results.push(this._opacityTexture);
  44933. }
  44934. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44935. results.push(this._reflectionTexture);
  44936. }
  44937. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44938. results.push(this._emissiveTexture);
  44939. }
  44940. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44941. results.push(this._metallicTexture);
  44942. }
  44943. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44944. results.push(this._reflectivityTexture);
  44945. }
  44946. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44947. results.push(this._bumpTexture);
  44948. }
  44949. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44950. results.push(this._lightmapTexture);
  44951. }
  44952. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44953. results.push(this._refractionTexture);
  44954. }
  44955. return results;
  44956. };
  44957. /**
  44958. * Returns the texture used for reflections.
  44959. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44960. */
  44961. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44962. if (this._reflectionTexture) {
  44963. return this._reflectionTexture;
  44964. }
  44965. return this.getScene().environmentTexture;
  44966. };
  44967. /**
  44968. * Returns the texture used for refraction or null if none is used.
  44969. * @returns - Refection texture if present. If no refraction texture and refraction
  44970. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44971. */
  44972. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44973. if (this._refractionTexture) {
  44974. return this._refractionTexture;
  44975. }
  44976. if (this._linkRefractionWithTransparency) {
  44977. return this.getScene().environmentTexture;
  44978. }
  44979. return null;
  44980. };
  44981. /**
  44982. * Disposes the resources of the material.
  44983. * @param forceDisposeEffect - Forces the disposal of effects.
  44984. * @param forceDisposeTextures - Forces the disposal of all textures.
  44985. */
  44986. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44987. if (forceDisposeTextures) {
  44988. if (this._albedoTexture) {
  44989. this._albedoTexture.dispose();
  44990. }
  44991. if (this._ambientTexture) {
  44992. this._ambientTexture.dispose();
  44993. }
  44994. if (this._opacityTexture) {
  44995. this._opacityTexture.dispose();
  44996. }
  44997. if (this._reflectionTexture) {
  44998. this._reflectionTexture.dispose();
  44999. }
  45000. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45001. this._environmentBRDFTexture.dispose();
  45002. }
  45003. if (this._emissiveTexture) {
  45004. this._emissiveTexture.dispose();
  45005. }
  45006. if (this._metallicTexture) {
  45007. this._metallicTexture.dispose();
  45008. }
  45009. if (this._reflectivityTexture) {
  45010. this._reflectivityTexture.dispose();
  45011. }
  45012. if (this._bumpTexture) {
  45013. this._bumpTexture.dispose();
  45014. }
  45015. if (this._lightmapTexture) {
  45016. this._lightmapTexture.dispose();
  45017. }
  45018. if (this._refractionTexture) {
  45019. this._refractionTexture.dispose();
  45020. }
  45021. }
  45022. this._renderTargets.dispose();
  45023. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45024. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45025. }
  45026. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45027. };
  45028. /**
  45029. * Stores the reflectivity values based on metallic roughness workflow.
  45030. */
  45031. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45032. __decorate([
  45033. BABYLON.serializeAsImageProcessingConfiguration()
  45034. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45035. __decorate([
  45036. BABYLON.serialize()
  45037. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45038. __decorate([
  45039. BABYLON.serialize()
  45040. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45041. return PBRBaseMaterial;
  45042. }(BABYLON.PushMaterial));
  45043. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45044. })(BABYLON || (BABYLON = {}));
  45045. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45046. "use strict";
  45047. var BABYLON;
  45048. (function (BABYLON) {
  45049. /**
  45050. * The Physically based simple base material of BJS.
  45051. *
  45052. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45053. * It is used as the base class for both the specGloss and metalRough conventions.
  45054. */
  45055. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45056. __extends(PBRBaseSimpleMaterial, _super);
  45057. /**
  45058. * Instantiates a new PBRMaterial instance.
  45059. *
  45060. * @param name The material name
  45061. * @param scene The scene the material will be use in.
  45062. */
  45063. function PBRBaseSimpleMaterial(name, scene) {
  45064. var _this = _super.call(this, name, scene) || this;
  45065. /**
  45066. * Number of Simultaneous lights allowed on the material.
  45067. */
  45068. _this.maxSimultaneousLights = 4;
  45069. /**
  45070. * If sets to true, disables all the lights affecting the material.
  45071. */
  45072. _this.disableLighting = false;
  45073. /**
  45074. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45075. */
  45076. _this.invertNormalMapX = false;
  45077. /**
  45078. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45079. */
  45080. _this.invertNormalMapY = false;
  45081. /**
  45082. * Emissivie color used to self-illuminate the model.
  45083. */
  45084. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45085. /**
  45086. * Occlusion Channel Strenght.
  45087. */
  45088. _this.occlusionStrength = 1.0;
  45089. _this.useLightmapAsShadowmap = false;
  45090. _this._useAlphaFromAlbedoTexture = true;
  45091. _this._useAmbientInGrayScale = true;
  45092. return _this;
  45093. }
  45094. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45095. /**
  45096. * Gets the current double sided mode.
  45097. */
  45098. get: function () {
  45099. return this._twoSidedLighting;
  45100. },
  45101. /**
  45102. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45103. */
  45104. set: function (value) {
  45105. if (this._twoSidedLighting === value) {
  45106. return;
  45107. }
  45108. this._twoSidedLighting = value;
  45109. this.backFaceCulling = !value;
  45110. this._markAllSubMeshesAsTexturesDirty();
  45111. },
  45112. enumerable: true,
  45113. configurable: true
  45114. });
  45115. /**
  45116. * Return the active textures of the material.
  45117. */
  45118. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45119. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45120. if (this.environmentTexture) {
  45121. activeTextures.push(this.environmentTexture);
  45122. }
  45123. if (this.normalTexture) {
  45124. activeTextures.push(this.normalTexture);
  45125. }
  45126. if (this.emissiveTexture) {
  45127. activeTextures.push(this.emissiveTexture);
  45128. }
  45129. if (this.occlusionTexture) {
  45130. activeTextures.push(this.occlusionTexture);
  45131. }
  45132. if (this.lightmapTexture) {
  45133. activeTextures.push(this.lightmapTexture);
  45134. }
  45135. return activeTextures;
  45136. };
  45137. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45138. if (_super.prototype.hasTexture.call(this, texture)) {
  45139. return true;
  45140. }
  45141. if (this.lightmapTexture === texture) {
  45142. return true;
  45143. }
  45144. return false;
  45145. };
  45146. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45147. return "PBRBaseSimpleMaterial";
  45148. };
  45149. __decorate([
  45150. BABYLON.serialize(),
  45151. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45152. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45153. __decorate([
  45154. BABYLON.serialize(),
  45155. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45156. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45157. __decorate([
  45158. BABYLON.serializeAsTexture(),
  45159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45160. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45161. __decorate([
  45162. BABYLON.serialize(),
  45163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45164. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45165. __decorate([
  45166. BABYLON.serialize(),
  45167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45168. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45169. __decorate([
  45170. BABYLON.serializeAsTexture(),
  45171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45172. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45173. __decorate([
  45174. BABYLON.serializeAsColor3("emissive"),
  45175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45176. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45177. __decorate([
  45178. BABYLON.serializeAsTexture(),
  45179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45180. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45181. __decorate([
  45182. BABYLON.serialize(),
  45183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45184. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45185. __decorate([
  45186. BABYLON.serializeAsTexture(),
  45187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45188. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45189. __decorate([
  45190. BABYLON.serialize(),
  45191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45192. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45193. __decorate([
  45194. BABYLON.serialize()
  45195. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45196. __decorate([
  45197. BABYLON.serializeAsTexture(),
  45198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45199. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45200. __decorate([
  45201. BABYLON.serialize(),
  45202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45203. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45204. return PBRBaseSimpleMaterial;
  45205. }(BABYLON.PBRBaseMaterial));
  45206. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45207. })(BABYLON || (BABYLON = {}));
  45208. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45209. "use strict";
  45210. var BABYLON;
  45211. (function (BABYLON) {
  45212. /**
  45213. * The Physically based material of BJS.
  45214. *
  45215. * This offers the main features of a standard PBR material.
  45216. * For more information, please refer to the documentation :
  45217. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45218. */
  45219. var PBRMaterial = /** @class */ (function (_super) {
  45220. __extends(PBRMaterial, _super);
  45221. /**
  45222. * Instantiates a new PBRMaterial instance.
  45223. *
  45224. * @param name The material name
  45225. * @param scene The scene the material will be use in.
  45226. */
  45227. function PBRMaterial(name, scene) {
  45228. var _this = _super.call(this, name, scene) || this;
  45229. /**
  45230. * Intensity of the direct lights e.g. the four lights available in your scene.
  45231. * This impacts both the direct diffuse and specular highlights.
  45232. */
  45233. _this.directIntensity = 1.0;
  45234. /**
  45235. * Intensity of the emissive part of the material.
  45236. * This helps controlling the emissive effect without modifying the emissive color.
  45237. */
  45238. _this.emissiveIntensity = 1.0;
  45239. /**
  45240. * Intensity of the environment e.g. how much the environment will light the object
  45241. * either through harmonics for rough material or through the refelction for shiny ones.
  45242. */
  45243. _this.environmentIntensity = 1.0;
  45244. /**
  45245. * This is a special control allowing the reduction of the specular highlights coming from the
  45246. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45247. */
  45248. _this.specularIntensity = 1.0;
  45249. /**
  45250. * Debug Control allowing disabling the bump map on this material.
  45251. */
  45252. _this.disableBumpMap = false;
  45253. /**
  45254. * AKA Occlusion Texture Intensity in other nomenclature.
  45255. */
  45256. _this.ambientTextureStrength = 1.0;
  45257. /**
  45258. * The color of a material in ambient lighting.
  45259. */
  45260. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45261. /**
  45262. * AKA Diffuse Color in other nomenclature.
  45263. */
  45264. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45265. /**
  45266. * AKA Specular Color in other nomenclature.
  45267. */
  45268. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45269. /**
  45270. * The color reflected from the material.
  45271. */
  45272. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45273. /**
  45274. * The color emitted from the material.
  45275. */
  45276. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45277. /**
  45278. * AKA Glossiness in other nomenclature.
  45279. */
  45280. _this.microSurface = 1.0;
  45281. /**
  45282. * source material index of refraction (IOR)' / 'destination material IOR.
  45283. */
  45284. _this.indexOfRefraction = 0.66;
  45285. /**
  45286. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45287. */
  45288. _this.invertRefractionY = false;
  45289. /**
  45290. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45291. * Materials half opaque for instance using refraction could benefit from this control.
  45292. */
  45293. _this.linkRefractionWithTransparency = false;
  45294. _this.useLightmapAsShadowmap = false;
  45295. /**
  45296. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45297. */
  45298. _this.useAlphaFromAlbedoTexture = false;
  45299. /**
  45300. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45301. */
  45302. _this.forceAlphaTest = false;
  45303. /**
  45304. * Defines the alpha limits in alpha test mode.
  45305. */
  45306. _this.alphaCutOff = 0.4;
  45307. /**
  45308. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45309. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45310. */
  45311. _this.useSpecularOverAlpha = true;
  45312. /**
  45313. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45314. */
  45315. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45316. /**
  45317. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45318. */
  45319. _this.useRoughnessFromMetallicTextureAlpha = true;
  45320. /**
  45321. * Specifies if the metallic texture contains the roughness information in its green channel.
  45322. */
  45323. _this.useRoughnessFromMetallicTextureGreen = false;
  45324. /**
  45325. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45326. */
  45327. _this.useMetallnessFromMetallicTextureBlue = false;
  45328. /**
  45329. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45330. */
  45331. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45332. /**
  45333. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45334. */
  45335. _this.useAmbientInGrayScale = false;
  45336. /**
  45337. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45338. * The material will try to infer what glossiness each pixel should be.
  45339. */
  45340. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45341. /**
  45342. * BJS is using an harcoded light falloff based on a manually sets up range.
  45343. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45344. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45345. */
  45346. _this.usePhysicalLightFalloff = true;
  45347. /**
  45348. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45349. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45350. */
  45351. _this.useRadianceOverAlpha = true;
  45352. /**
  45353. * Allows using an object space normal map (instead of tangent space).
  45354. */
  45355. _this.useObjectSpaceNormalMap = false;
  45356. /**
  45357. * Allows using the bump map in parallax mode.
  45358. */
  45359. _this.useParallax = false;
  45360. /**
  45361. * Allows using the bump map in parallax occlusion mode.
  45362. */
  45363. _this.useParallaxOcclusion = false;
  45364. /**
  45365. * Controls the scale bias of the parallax mode.
  45366. */
  45367. _this.parallaxScaleBias = 0.05;
  45368. /**
  45369. * If sets to true, disables all the lights affecting the material.
  45370. */
  45371. _this.disableLighting = false;
  45372. /**
  45373. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45374. */
  45375. _this.forceIrradianceInFragment = false;
  45376. /**
  45377. * Number of Simultaneous lights allowed on the material.
  45378. */
  45379. _this.maxSimultaneousLights = 4;
  45380. /**
  45381. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45382. */
  45383. _this.invertNormalMapX = false;
  45384. /**
  45385. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45386. */
  45387. _this.invertNormalMapY = false;
  45388. /**
  45389. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45390. */
  45391. _this.twoSidedLighting = false;
  45392. /**
  45393. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45394. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45395. */
  45396. _this.useAlphaFresnel = false;
  45397. /**
  45398. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45399. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45400. */
  45401. _this.useLinearAlphaFresnel = false;
  45402. /**
  45403. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45404. * And/Or occlude the blended part.
  45405. */
  45406. _this.environmentBRDFTexture = null;
  45407. /**
  45408. * Force normal to face away from face.
  45409. */
  45410. _this.forceNormalForward = false;
  45411. /**
  45412. * Enables specular anti aliasing in the PBR shader.
  45413. * It will both interacts on the Geometry for analytical and IBL lighting.
  45414. * It also prefilter the roughness map based on the bump values.
  45415. */
  45416. _this.enableSpecularAntiAliasing = false;
  45417. /**
  45418. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45419. * makes the reflect vector face the model (under horizon).
  45420. */
  45421. _this.useHorizonOcclusion = true;
  45422. /**
  45423. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45424. * too much the area relying on ambient texture to define their ambient occlusion.
  45425. */
  45426. _this.useRadianceOcclusion = true;
  45427. /**
  45428. * If set to true, no lighting calculations will be applied.
  45429. */
  45430. _this.unlit = false;
  45431. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45432. return _this;
  45433. }
  45434. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45435. /**
  45436. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45437. */
  45438. get: function () {
  45439. return this._PBRMATERIAL_OPAQUE;
  45440. },
  45441. enumerable: true,
  45442. configurable: true
  45443. });
  45444. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45445. /**
  45446. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45447. */
  45448. get: function () {
  45449. return this._PBRMATERIAL_ALPHATEST;
  45450. },
  45451. enumerable: true,
  45452. configurable: true
  45453. });
  45454. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45455. /**
  45456. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45457. */
  45458. get: function () {
  45459. return this._PBRMATERIAL_ALPHABLEND;
  45460. },
  45461. enumerable: true,
  45462. configurable: true
  45463. });
  45464. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45465. /**
  45466. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45467. * They are also discarded below the alpha cutoff threshold to improve performances.
  45468. */
  45469. get: function () {
  45470. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45471. },
  45472. enumerable: true,
  45473. configurable: true
  45474. });
  45475. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45476. /**
  45477. * Gets the image processing configuration used either in this material.
  45478. */
  45479. get: function () {
  45480. return this._imageProcessingConfiguration;
  45481. },
  45482. /**
  45483. * Sets the Default image processing configuration used either in the this material.
  45484. *
  45485. * If sets to null, the scene one is in use.
  45486. */
  45487. set: function (value) {
  45488. this._attachImageProcessingConfiguration(value);
  45489. // Ensure the effect will be rebuilt.
  45490. this._markAllSubMeshesAsTexturesDirty();
  45491. },
  45492. enumerable: true,
  45493. configurable: true
  45494. });
  45495. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45496. /**
  45497. * Gets wether the color curves effect is enabled.
  45498. */
  45499. get: function () {
  45500. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45501. },
  45502. /**
  45503. * Sets wether the color curves effect is enabled.
  45504. */
  45505. set: function (value) {
  45506. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45507. },
  45508. enumerable: true,
  45509. configurable: true
  45510. });
  45511. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45512. /**
  45513. * Gets wether the color grading effect is enabled.
  45514. */
  45515. get: function () {
  45516. return this.imageProcessingConfiguration.colorGradingEnabled;
  45517. },
  45518. /**
  45519. * Gets wether the color grading effect is enabled.
  45520. */
  45521. set: function (value) {
  45522. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45523. },
  45524. enumerable: true,
  45525. configurable: true
  45526. });
  45527. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45528. /**
  45529. * Gets wether tonemapping is enabled or not.
  45530. */
  45531. get: function () {
  45532. return this._imageProcessingConfiguration.toneMappingEnabled;
  45533. },
  45534. /**
  45535. * Sets wether tonemapping is enabled or not
  45536. */
  45537. set: function (value) {
  45538. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45539. },
  45540. enumerable: true,
  45541. configurable: true
  45542. });
  45543. ;
  45544. ;
  45545. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45546. /**
  45547. * The camera exposure used on this material.
  45548. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45549. * This corresponds to a photographic exposure.
  45550. */
  45551. get: function () {
  45552. return this._imageProcessingConfiguration.exposure;
  45553. },
  45554. /**
  45555. * The camera exposure used on this material.
  45556. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45557. * This corresponds to a photographic exposure.
  45558. */
  45559. set: function (value) {
  45560. this._imageProcessingConfiguration.exposure = value;
  45561. },
  45562. enumerable: true,
  45563. configurable: true
  45564. });
  45565. ;
  45566. ;
  45567. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45568. /**
  45569. * Gets The camera contrast used on this material.
  45570. */
  45571. get: function () {
  45572. return this._imageProcessingConfiguration.contrast;
  45573. },
  45574. /**
  45575. * Sets The camera contrast used on this material.
  45576. */
  45577. set: function (value) {
  45578. this._imageProcessingConfiguration.contrast = value;
  45579. },
  45580. enumerable: true,
  45581. configurable: true
  45582. });
  45583. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45584. /**
  45585. * Gets the Color Grading 2D Lookup Texture.
  45586. */
  45587. get: function () {
  45588. return this._imageProcessingConfiguration.colorGradingTexture;
  45589. },
  45590. /**
  45591. * Sets the Color Grading 2D Lookup Texture.
  45592. */
  45593. set: function (value) {
  45594. this._imageProcessingConfiguration.colorGradingTexture = value;
  45595. },
  45596. enumerable: true,
  45597. configurable: true
  45598. });
  45599. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45600. /**
  45601. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45602. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45603. * 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;
  45604. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45605. */
  45606. get: function () {
  45607. return this._imageProcessingConfiguration.colorCurves;
  45608. },
  45609. /**
  45610. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45611. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45612. * 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;
  45613. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45614. */
  45615. set: function (value) {
  45616. this._imageProcessingConfiguration.colorCurves = value;
  45617. },
  45618. enumerable: true,
  45619. configurable: true
  45620. });
  45621. /**
  45622. * Returns the name of this material class.
  45623. */
  45624. PBRMaterial.prototype.getClassName = function () {
  45625. return "PBRMaterial";
  45626. };
  45627. /**
  45628. * Returns an array of the actively used textures.
  45629. * @returns - Array of BaseTextures
  45630. */
  45631. PBRMaterial.prototype.getActiveTextures = function () {
  45632. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45633. if (this._albedoTexture) {
  45634. activeTextures.push(this._albedoTexture);
  45635. }
  45636. if (this._ambientTexture) {
  45637. activeTextures.push(this._ambientTexture);
  45638. }
  45639. if (this._opacityTexture) {
  45640. activeTextures.push(this._opacityTexture);
  45641. }
  45642. if (this._reflectionTexture) {
  45643. activeTextures.push(this._reflectionTexture);
  45644. }
  45645. if (this._emissiveTexture) {
  45646. activeTextures.push(this._emissiveTexture);
  45647. }
  45648. if (this._reflectivityTexture) {
  45649. activeTextures.push(this._reflectivityTexture);
  45650. }
  45651. if (this._metallicTexture) {
  45652. activeTextures.push(this._metallicTexture);
  45653. }
  45654. if (this._microSurfaceTexture) {
  45655. activeTextures.push(this._microSurfaceTexture);
  45656. }
  45657. if (this._bumpTexture) {
  45658. activeTextures.push(this._bumpTexture);
  45659. }
  45660. if (this._lightmapTexture) {
  45661. activeTextures.push(this._lightmapTexture);
  45662. }
  45663. if (this._refractionTexture) {
  45664. activeTextures.push(this._refractionTexture);
  45665. }
  45666. return activeTextures;
  45667. };
  45668. /**
  45669. * Checks to see if a texture is used in the material.
  45670. * @param texture - Base texture to use.
  45671. * @returns - Boolean specifying if a texture is used in the material.
  45672. */
  45673. PBRMaterial.prototype.hasTexture = function (texture) {
  45674. if (_super.prototype.hasTexture.call(this, texture)) {
  45675. return true;
  45676. }
  45677. if (this._albedoTexture === texture) {
  45678. return true;
  45679. }
  45680. if (this._ambientTexture === texture) {
  45681. return true;
  45682. }
  45683. if (this._opacityTexture === texture) {
  45684. return true;
  45685. }
  45686. if (this._reflectionTexture === texture) {
  45687. return true;
  45688. }
  45689. if (this._reflectivityTexture === texture) {
  45690. return true;
  45691. }
  45692. if (this._metallicTexture === texture) {
  45693. return true;
  45694. }
  45695. if (this._microSurfaceTexture === texture) {
  45696. return true;
  45697. }
  45698. if (this._bumpTexture === texture) {
  45699. return true;
  45700. }
  45701. if (this._lightmapTexture === texture) {
  45702. return true;
  45703. }
  45704. if (this._refractionTexture === texture) {
  45705. return true;
  45706. }
  45707. return false;
  45708. };
  45709. /**
  45710. * Makes a duplicate of the current material.
  45711. * @param name - name to use for the new material.
  45712. */
  45713. PBRMaterial.prototype.clone = function (name) {
  45714. var _this = this;
  45715. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45716. clone.id = name;
  45717. clone.name = name;
  45718. return clone;
  45719. };
  45720. /**
  45721. * Serializes this PBR Material.
  45722. * @returns - An object with the serialized material.
  45723. */
  45724. PBRMaterial.prototype.serialize = function () {
  45725. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45726. serializationObject.customType = "BABYLON.PBRMaterial";
  45727. return serializationObject;
  45728. };
  45729. // Statics
  45730. /**
  45731. * Parses a PBR Material from a serialized object.
  45732. * @param source - Serialized object.
  45733. * @param scene - BJS scene instance.
  45734. * @param rootUrl - url for the scene object
  45735. * @returns - PBRMaterial
  45736. */
  45737. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45738. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45739. };
  45740. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45741. /**
  45742. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45743. */
  45744. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45745. /**
  45746. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45747. */
  45748. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45749. /**
  45750. * 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.
  45751. * They are also discarded below the alpha cutoff threshold to improve performances.
  45752. */
  45753. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45754. __decorate([
  45755. BABYLON.serialize(),
  45756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45757. ], PBRMaterial.prototype, "directIntensity", void 0);
  45758. __decorate([
  45759. BABYLON.serialize(),
  45760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45761. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45762. __decorate([
  45763. BABYLON.serialize(),
  45764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45765. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45766. __decorate([
  45767. BABYLON.serialize(),
  45768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45769. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45770. __decorate([
  45771. BABYLON.serialize(),
  45772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45773. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45774. __decorate([
  45775. BABYLON.serializeAsTexture(),
  45776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45777. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45778. __decorate([
  45779. BABYLON.serializeAsTexture(),
  45780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45781. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45782. __decorate([
  45783. BABYLON.serialize(),
  45784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45785. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45786. __decorate([
  45787. BABYLON.serializeAsTexture(),
  45788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45789. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45790. __decorate([
  45791. BABYLON.serializeAsTexture(),
  45792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45793. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45794. __decorate([
  45795. BABYLON.serializeAsTexture(),
  45796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45797. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45798. __decorate([
  45799. BABYLON.serializeAsTexture(),
  45800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45801. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45802. __decorate([
  45803. BABYLON.serializeAsTexture(),
  45804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45805. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45806. __decorate([
  45807. BABYLON.serialize(),
  45808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45809. ], PBRMaterial.prototype, "metallic", void 0);
  45810. __decorate([
  45811. BABYLON.serialize(),
  45812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45813. ], PBRMaterial.prototype, "roughness", void 0);
  45814. __decorate([
  45815. BABYLON.serializeAsTexture(),
  45816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45817. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45818. __decorate([
  45819. BABYLON.serializeAsTexture(),
  45820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45821. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45822. __decorate([
  45823. BABYLON.serializeAsTexture(),
  45824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45825. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45826. __decorate([
  45827. BABYLON.serializeAsTexture(),
  45828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45829. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45830. __decorate([
  45831. BABYLON.serializeAsColor3("ambient"),
  45832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45833. ], PBRMaterial.prototype, "ambientColor", void 0);
  45834. __decorate([
  45835. BABYLON.serializeAsColor3("albedo"),
  45836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45837. ], PBRMaterial.prototype, "albedoColor", void 0);
  45838. __decorate([
  45839. BABYLON.serializeAsColor3("reflectivity"),
  45840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45841. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45842. __decorate([
  45843. BABYLON.serializeAsColor3("reflection"),
  45844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45845. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45846. __decorate([
  45847. BABYLON.serializeAsColor3("emissive"),
  45848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45849. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45850. __decorate([
  45851. BABYLON.serialize(),
  45852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45853. ], PBRMaterial.prototype, "microSurface", void 0);
  45854. __decorate([
  45855. BABYLON.serialize(),
  45856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45857. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45858. __decorate([
  45859. BABYLON.serialize(),
  45860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45861. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45862. __decorate([
  45863. BABYLON.serialize(),
  45864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45865. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45866. __decorate([
  45867. BABYLON.serialize(),
  45868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45869. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45870. __decorate([
  45871. BABYLON.serialize(),
  45872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45873. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45874. __decorate([
  45875. BABYLON.serialize(),
  45876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45877. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45878. __decorate([
  45879. BABYLON.serialize(),
  45880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45881. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45882. __decorate([
  45883. BABYLON.serialize(),
  45884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45885. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45886. __decorate([
  45887. BABYLON.serialize(),
  45888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45889. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45890. __decorate([
  45891. BABYLON.serialize(),
  45892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45893. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45894. __decorate([
  45895. BABYLON.serialize(),
  45896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45897. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45898. __decorate([
  45899. BABYLON.serialize(),
  45900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45901. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45902. __decorate([
  45903. BABYLON.serialize(),
  45904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45905. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45906. __decorate([
  45907. BABYLON.serialize(),
  45908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45909. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45910. __decorate([
  45911. BABYLON.serialize(),
  45912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45913. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45914. __decorate([
  45915. BABYLON.serialize(),
  45916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45917. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45918. __decorate([
  45919. BABYLON.serialize(),
  45920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45921. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45922. __decorate([
  45923. BABYLON.serialize(),
  45924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45925. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45926. __decorate([
  45927. BABYLON.serialize(),
  45928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45929. ], PBRMaterial.prototype, "useParallax", void 0);
  45930. __decorate([
  45931. BABYLON.serialize(),
  45932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45933. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45934. __decorate([
  45935. BABYLON.serialize(),
  45936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45937. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45938. __decorate([
  45939. BABYLON.serialize(),
  45940. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45941. ], PBRMaterial.prototype, "disableLighting", void 0);
  45942. __decorate([
  45943. BABYLON.serialize(),
  45944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45945. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45946. __decorate([
  45947. BABYLON.serialize(),
  45948. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45949. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45950. __decorate([
  45951. BABYLON.serialize(),
  45952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45953. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45954. __decorate([
  45955. BABYLON.serialize(),
  45956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45957. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45958. __decorate([
  45959. BABYLON.serialize(),
  45960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45961. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45962. __decorate([
  45963. BABYLON.serialize(),
  45964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45965. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45966. __decorate([
  45967. BABYLON.serialize(),
  45968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45969. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45970. __decorate([
  45971. BABYLON.serializeAsTexture(),
  45972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45973. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45974. __decorate([
  45975. BABYLON.serialize(),
  45976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45977. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45978. __decorate([
  45979. BABYLON.serialize(),
  45980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45981. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45982. __decorate([
  45983. BABYLON.serialize(),
  45984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45985. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45986. __decorate([
  45987. BABYLON.serialize(),
  45988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45989. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45990. __decorate([
  45991. BABYLON.serialize(),
  45992. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45993. ], PBRMaterial.prototype, "unlit", void 0);
  45994. return PBRMaterial;
  45995. }(BABYLON.PBRBaseMaterial));
  45996. BABYLON.PBRMaterial = PBRMaterial;
  45997. })(BABYLON || (BABYLON = {}));
  45998. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45999. "use strict";
  46000. var BABYLON;
  46001. (function (BABYLON) {
  46002. /**
  46003. * The PBR material of BJS following the metal roughness convention.
  46004. *
  46005. * This fits to the PBR convention in the GLTF definition:
  46006. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46007. */
  46008. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46009. __extends(PBRMetallicRoughnessMaterial, _super);
  46010. /**
  46011. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46012. *
  46013. * @param name The material name
  46014. * @param scene The scene the material will be use in.
  46015. */
  46016. function PBRMetallicRoughnessMaterial(name, scene) {
  46017. var _this = _super.call(this, name, scene) || this;
  46018. _this._useRoughnessFromMetallicTextureAlpha = false;
  46019. _this._useRoughnessFromMetallicTextureGreen = true;
  46020. _this._useMetallnessFromMetallicTextureBlue = true;
  46021. _this.metallic = 1.0;
  46022. _this.roughness = 1.0;
  46023. return _this;
  46024. }
  46025. /**
  46026. * Return the currrent class name of the material.
  46027. */
  46028. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46029. return "PBRMetallicRoughnessMaterial";
  46030. };
  46031. /**
  46032. * Return the active textures of the material.
  46033. */
  46034. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46035. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46036. if (this.baseTexture) {
  46037. activeTextures.push(this.baseTexture);
  46038. }
  46039. if (this.metallicRoughnessTexture) {
  46040. activeTextures.push(this.metallicRoughnessTexture);
  46041. }
  46042. return activeTextures;
  46043. };
  46044. /**
  46045. * Checks to see if a texture is used in the material.
  46046. * @param texture - Base texture to use.
  46047. * @returns - Boolean specifying if a texture is used in the material.
  46048. */
  46049. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46050. if (_super.prototype.hasTexture.call(this, texture)) {
  46051. return true;
  46052. }
  46053. if (this.baseTexture === texture) {
  46054. return true;
  46055. }
  46056. if (this.metallicRoughnessTexture === texture) {
  46057. return true;
  46058. }
  46059. return false;
  46060. };
  46061. /**
  46062. * Makes a duplicate of the current material.
  46063. * @param name - name to use for the new material.
  46064. */
  46065. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46066. var _this = this;
  46067. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46068. clone.id = name;
  46069. clone.name = name;
  46070. return clone;
  46071. };
  46072. /**
  46073. * Serialize the material to a parsable JSON object.
  46074. */
  46075. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46076. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46077. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46078. return serializationObject;
  46079. };
  46080. /**
  46081. * Parses a JSON object correponding to the serialize function.
  46082. */
  46083. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46084. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46085. };
  46086. __decorate([
  46087. BABYLON.serializeAsColor3(),
  46088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46089. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46090. __decorate([
  46091. BABYLON.serializeAsTexture(),
  46092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46093. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46094. __decorate([
  46095. BABYLON.serialize(),
  46096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46097. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46098. __decorate([
  46099. BABYLON.serialize(),
  46100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46101. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46102. __decorate([
  46103. BABYLON.serializeAsTexture(),
  46104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46105. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46106. return PBRMetallicRoughnessMaterial;
  46107. }(BABYLON.PBRBaseSimpleMaterial));
  46108. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46109. })(BABYLON || (BABYLON = {}));
  46110. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46111. "use strict";
  46112. var BABYLON;
  46113. (function (BABYLON) {
  46114. /**
  46115. * The PBR material of BJS following the specular glossiness convention.
  46116. *
  46117. * This fits to the PBR convention in the GLTF definition:
  46118. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46119. */
  46120. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46121. __extends(PBRSpecularGlossinessMaterial, _super);
  46122. /**
  46123. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46124. *
  46125. * @param name The material name
  46126. * @param scene The scene the material will be use in.
  46127. */
  46128. function PBRSpecularGlossinessMaterial(name, scene) {
  46129. var _this = _super.call(this, name, scene) || this;
  46130. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46131. return _this;
  46132. }
  46133. /**
  46134. * Return the currrent class name of the material.
  46135. */
  46136. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46137. return "PBRSpecularGlossinessMaterial";
  46138. };
  46139. /**
  46140. * Return the active textures of the material.
  46141. */
  46142. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46143. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46144. if (this.diffuseTexture) {
  46145. activeTextures.push(this.diffuseTexture);
  46146. }
  46147. if (this.specularGlossinessTexture) {
  46148. activeTextures.push(this.specularGlossinessTexture);
  46149. }
  46150. return activeTextures;
  46151. };
  46152. /**
  46153. * Checks to see if a texture is used in the material.
  46154. * @param texture - Base texture to use.
  46155. * @returns - Boolean specifying if a texture is used in the material.
  46156. */
  46157. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46158. if (_super.prototype.hasTexture.call(this, texture)) {
  46159. return true;
  46160. }
  46161. if (this.diffuseTexture === texture) {
  46162. return true;
  46163. }
  46164. if (this.specularGlossinessTexture === texture) {
  46165. return true;
  46166. }
  46167. return false;
  46168. };
  46169. /**
  46170. * Makes a duplicate of the current material.
  46171. * @param name - name to use for the new material.
  46172. */
  46173. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46174. var _this = this;
  46175. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46176. clone.id = name;
  46177. clone.name = name;
  46178. return clone;
  46179. };
  46180. /**
  46181. * Serialize the material to a parsable JSON object.
  46182. */
  46183. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46184. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46185. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46186. return serializationObject;
  46187. };
  46188. /**
  46189. * Parses a JSON object correponding to the serialize function.
  46190. */
  46191. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46192. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46193. };
  46194. __decorate([
  46195. BABYLON.serializeAsColor3("diffuse"),
  46196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46197. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46198. __decorate([
  46199. BABYLON.serializeAsTexture(),
  46200. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46201. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46202. __decorate([
  46203. BABYLON.serializeAsColor3("specular"),
  46204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46205. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46206. __decorate([
  46207. BABYLON.serialize(),
  46208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46209. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46210. __decorate([
  46211. BABYLON.serializeAsTexture(),
  46212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46213. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46214. return PBRSpecularGlossinessMaterial;
  46215. }(BABYLON.PBRBaseSimpleMaterial));
  46216. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46217. })(BABYLON || (BABYLON = {}));
  46218. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46219. "use strict";
  46220. var BABYLON;
  46221. (function (BABYLON) {
  46222. BABYLON.CameraInputTypes = {};
  46223. var CameraInputsManager = /** @class */ (function () {
  46224. function CameraInputsManager(camera) {
  46225. this.attached = {};
  46226. this.camera = camera;
  46227. this.checkInputs = function () { };
  46228. }
  46229. /**
  46230. * Add an input method to a camera.
  46231. * builtin inputs example: camera.inputs.addGamepad();
  46232. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46233. * @param input camera input method
  46234. */
  46235. CameraInputsManager.prototype.add = function (input) {
  46236. var type = input.getSimpleName();
  46237. if (this.attached[type]) {
  46238. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46239. return;
  46240. }
  46241. this.attached[type] = input;
  46242. input.camera = this.camera;
  46243. //for checkInputs, we are dynamically creating a function
  46244. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46245. if (input.checkInputs) {
  46246. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46247. }
  46248. if (this.attachedElement) {
  46249. input.attachControl(this.attachedElement);
  46250. }
  46251. };
  46252. /**
  46253. * Remove a specific input method from a camera
  46254. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46255. * @param inputToRemove camera input method
  46256. */
  46257. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46258. for (var cam in this.attached) {
  46259. var input = this.attached[cam];
  46260. if (input === inputToRemove) {
  46261. input.detachControl(this.attachedElement);
  46262. input.camera = null;
  46263. delete this.attached[cam];
  46264. this.rebuildInputCheck();
  46265. }
  46266. }
  46267. };
  46268. CameraInputsManager.prototype.removeByType = function (inputType) {
  46269. for (var cam in this.attached) {
  46270. var input = this.attached[cam];
  46271. if (input.getClassName() === inputType) {
  46272. input.detachControl(this.attachedElement);
  46273. input.camera = null;
  46274. delete this.attached[cam];
  46275. this.rebuildInputCheck();
  46276. }
  46277. }
  46278. };
  46279. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46280. var current = this.checkInputs;
  46281. return function () {
  46282. current();
  46283. fn();
  46284. };
  46285. };
  46286. CameraInputsManager.prototype.attachInput = function (input) {
  46287. if (this.attachedElement) {
  46288. input.attachControl(this.attachedElement, this.noPreventDefault);
  46289. }
  46290. };
  46291. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46292. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46293. if (this.attachedElement) {
  46294. return;
  46295. }
  46296. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46297. this.attachedElement = element;
  46298. this.noPreventDefault = noPreventDefault;
  46299. for (var cam in this.attached) {
  46300. this.attached[cam].attachControl(element, noPreventDefault);
  46301. }
  46302. };
  46303. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46304. if (disconnect === void 0) { disconnect = false; }
  46305. if (this.attachedElement !== element) {
  46306. return;
  46307. }
  46308. for (var cam in this.attached) {
  46309. this.attached[cam].detachControl(element);
  46310. if (disconnect) {
  46311. this.attached[cam].camera = null;
  46312. }
  46313. }
  46314. this.attachedElement = null;
  46315. };
  46316. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46317. this.checkInputs = function () { };
  46318. for (var cam in this.attached) {
  46319. var input = this.attached[cam];
  46320. if (input.checkInputs) {
  46321. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46322. }
  46323. }
  46324. };
  46325. /**
  46326. * Remove all attached input methods from a camera
  46327. */
  46328. CameraInputsManager.prototype.clear = function () {
  46329. if (this.attachedElement) {
  46330. this.detachElement(this.attachedElement, true);
  46331. }
  46332. this.attached = {};
  46333. this.attachedElement = null;
  46334. this.checkInputs = function () { };
  46335. };
  46336. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46337. var inputs = {};
  46338. for (var cam in this.attached) {
  46339. var input = this.attached[cam];
  46340. var res = BABYLON.SerializationHelper.Serialize(input);
  46341. inputs[input.getClassName()] = res;
  46342. }
  46343. serializedCamera.inputsmgr = inputs;
  46344. };
  46345. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46346. var parsedInputs = parsedCamera.inputsmgr;
  46347. if (parsedInputs) {
  46348. this.clear();
  46349. for (var n in parsedInputs) {
  46350. var construct = BABYLON.CameraInputTypes[n];
  46351. if (construct) {
  46352. var parsedinput = parsedInputs[n];
  46353. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46354. this.add(input);
  46355. }
  46356. }
  46357. }
  46358. else {
  46359. //2016-03-08 this part is for managing backward compatibility
  46360. for (var n in this.attached) {
  46361. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46362. if (construct) {
  46363. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46364. this.remove(this.attached[n]);
  46365. this.add(input);
  46366. }
  46367. }
  46368. }
  46369. };
  46370. return CameraInputsManager;
  46371. }());
  46372. BABYLON.CameraInputsManager = CameraInputsManager;
  46373. })(BABYLON || (BABYLON = {}));
  46374. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46375. "use strict";
  46376. var BABYLON;
  46377. (function (BABYLON) {
  46378. var TargetCamera = /** @class */ (function (_super) {
  46379. __extends(TargetCamera, _super);
  46380. function TargetCamera(name, position, scene) {
  46381. var _this = _super.call(this, name, position, scene) || this;
  46382. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46383. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46384. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46385. _this.speed = 2.0;
  46386. _this.noRotationConstraint = false;
  46387. _this.lockedTarget = null;
  46388. _this._currentTarget = BABYLON.Vector3.Zero();
  46389. _this._viewMatrix = BABYLON.Matrix.Zero();
  46390. _this._camMatrix = BABYLON.Matrix.Zero();
  46391. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46392. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46393. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46394. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46395. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46396. _this._lookAtTemp = BABYLON.Matrix.Zero();
  46397. _this._tempMatrix = BABYLON.Matrix.Zero();
  46398. return _this;
  46399. }
  46400. TargetCamera.prototype.getFrontPosition = function (distance) {
  46401. this.getWorldMatrix();
  46402. var direction = this.getTarget().subtract(this.position);
  46403. direction.normalize();
  46404. direction.scaleInPlace(distance);
  46405. return this.globalPosition.add(direction);
  46406. };
  46407. TargetCamera.prototype._getLockedTargetPosition = function () {
  46408. if (!this.lockedTarget) {
  46409. return null;
  46410. }
  46411. if (this.lockedTarget.absolutePosition) {
  46412. this.lockedTarget.computeWorldMatrix();
  46413. }
  46414. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46415. };
  46416. TargetCamera.prototype.storeState = function () {
  46417. this._storedPosition = this.position.clone();
  46418. this._storedRotation = this.rotation.clone();
  46419. if (this.rotationQuaternion) {
  46420. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46421. }
  46422. return _super.prototype.storeState.call(this);
  46423. };
  46424. /**
  46425. * Restored camera state. You must call storeState() first
  46426. */
  46427. TargetCamera.prototype._restoreStateValues = function () {
  46428. if (!_super.prototype._restoreStateValues.call(this)) {
  46429. return false;
  46430. }
  46431. this.position = this._storedPosition.clone();
  46432. this.rotation = this._storedRotation.clone();
  46433. if (this.rotationQuaternion) {
  46434. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46435. }
  46436. this.cameraDirection.copyFromFloats(0, 0, 0);
  46437. this.cameraRotation.copyFromFloats(0, 0);
  46438. return true;
  46439. };
  46440. // Cache
  46441. TargetCamera.prototype._initCache = function () {
  46442. _super.prototype._initCache.call(this);
  46443. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46444. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46445. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46446. };
  46447. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46448. if (!ignoreParentClass) {
  46449. _super.prototype._updateCache.call(this);
  46450. }
  46451. var lockedTargetPosition = this._getLockedTargetPosition();
  46452. if (!lockedTargetPosition) {
  46453. this._cache.lockedTarget = null;
  46454. }
  46455. else {
  46456. if (!this._cache.lockedTarget) {
  46457. this._cache.lockedTarget = lockedTargetPosition.clone();
  46458. }
  46459. else {
  46460. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46461. }
  46462. }
  46463. this._cache.rotation.copyFrom(this.rotation);
  46464. if (this.rotationQuaternion)
  46465. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46466. };
  46467. // Synchronized
  46468. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46469. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46470. return false;
  46471. }
  46472. var lockedTargetPosition = this._getLockedTargetPosition();
  46473. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46474. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46475. };
  46476. // Methods
  46477. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46478. var engine = this.getEngine();
  46479. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46480. };
  46481. // Target
  46482. TargetCamera.prototype.setTarget = function (target) {
  46483. this.upVector.normalize();
  46484. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46485. this._camMatrix.invert();
  46486. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46487. var vDir = target.subtract(this.position);
  46488. if (vDir.x >= 0.0) {
  46489. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46490. }
  46491. else {
  46492. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46493. }
  46494. this.rotation.z = 0;
  46495. if (isNaN(this.rotation.x)) {
  46496. this.rotation.x = 0;
  46497. }
  46498. if (isNaN(this.rotation.y)) {
  46499. this.rotation.y = 0;
  46500. }
  46501. if (isNaN(this.rotation.z)) {
  46502. this.rotation.z = 0;
  46503. }
  46504. if (this.rotationQuaternion) {
  46505. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46506. }
  46507. };
  46508. /**
  46509. * Return the current target position of the camera. This value is expressed in local space.
  46510. */
  46511. TargetCamera.prototype.getTarget = function () {
  46512. return this._currentTarget;
  46513. };
  46514. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46515. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46516. };
  46517. TargetCamera.prototype._updatePosition = function () {
  46518. if (this.parent) {
  46519. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46520. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46521. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46522. return;
  46523. }
  46524. this.position.addInPlace(this.cameraDirection);
  46525. };
  46526. TargetCamera.prototype._checkInputs = function () {
  46527. var needToMove = this._decideIfNeedsToMove();
  46528. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46529. // Move
  46530. if (needToMove) {
  46531. this._updatePosition();
  46532. }
  46533. // Rotate
  46534. if (needToRotate) {
  46535. this.rotation.x += this.cameraRotation.x;
  46536. this.rotation.y += this.cameraRotation.y;
  46537. //rotate, if quaternion is set and rotation was used
  46538. if (this.rotationQuaternion) {
  46539. var len = this.rotation.lengthSquared();
  46540. if (len) {
  46541. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46542. }
  46543. }
  46544. if (!this.noRotationConstraint) {
  46545. var limit = (Math.PI / 2) * 0.95;
  46546. if (this.rotation.x > limit)
  46547. this.rotation.x = limit;
  46548. if (this.rotation.x < -limit)
  46549. this.rotation.x = -limit;
  46550. }
  46551. }
  46552. // Inertia
  46553. if (needToMove) {
  46554. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46555. this.cameraDirection.x = 0;
  46556. }
  46557. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46558. this.cameraDirection.y = 0;
  46559. }
  46560. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46561. this.cameraDirection.z = 0;
  46562. }
  46563. this.cameraDirection.scaleInPlace(this.inertia);
  46564. }
  46565. if (needToRotate) {
  46566. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46567. this.cameraRotation.x = 0;
  46568. }
  46569. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46570. this.cameraRotation.y = 0;
  46571. }
  46572. this.cameraRotation.scaleInPlace(this.inertia);
  46573. }
  46574. _super.prototype._checkInputs.call(this);
  46575. };
  46576. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46577. if (this.rotationQuaternion) {
  46578. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46579. }
  46580. else {
  46581. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46582. }
  46583. //update the up vector!
  46584. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46585. };
  46586. TargetCamera.prototype._getViewMatrix = function () {
  46587. if (this.lockedTarget) {
  46588. this.setTarget(this._getLockedTargetPosition());
  46589. }
  46590. // Compute
  46591. this._updateCameraRotationMatrix();
  46592. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46593. // Computing target and final matrix
  46594. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46595. if (this.getScene().useRightHandedSystem) {
  46596. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46597. }
  46598. else {
  46599. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46600. }
  46601. return this._viewMatrix;
  46602. };
  46603. /**
  46604. * @override
  46605. * Override Camera.createRigCamera
  46606. */
  46607. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46608. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46609. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46610. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46611. if (!this.rotationQuaternion) {
  46612. this.rotationQuaternion = new BABYLON.Quaternion();
  46613. }
  46614. rigCamera._cameraRigParams = {};
  46615. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46616. }
  46617. return rigCamera;
  46618. }
  46619. return null;
  46620. };
  46621. /**
  46622. * @override
  46623. * Override Camera._updateRigCameras
  46624. */
  46625. TargetCamera.prototype._updateRigCameras = function () {
  46626. var camLeft = this._rigCameras[0];
  46627. var camRight = this._rigCameras[1];
  46628. switch (this.cameraRigMode) {
  46629. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46630. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46631. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46632. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46633. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46634. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46635. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46636. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46637. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46638. camLeft.setTarget(this.getTarget());
  46639. camRight.setTarget(this.getTarget());
  46640. break;
  46641. case BABYLON.Camera.RIG_MODE_VR:
  46642. if (camLeft.rotationQuaternion) {
  46643. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46644. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46645. }
  46646. else {
  46647. camLeft.rotation.copyFrom(this.rotation);
  46648. camRight.rotation.copyFrom(this.rotation);
  46649. }
  46650. camLeft.position.copyFrom(this.position);
  46651. camRight.position.copyFrom(this.position);
  46652. break;
  46653. }
  46654. _super.prototype._updateRigCameras.call(this);
  46655. };
  46656. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46657. if (!this._rigCamTransformMatrix) {
  46658. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46659. }
  46660. var target = this.getTarget();
  46661. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46662. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46663. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46664. };
  46665. TargetCamera.prototype.getClassName = function () {
  46666. return "TargetCamera";
  46667. };
  46668. __decorate([
  46669. BABYLON.serializeAsVector3()
  46670. ], TargetCamera.prototype, "rotation", void 0);
  46671. __decorate([
  46672. BABYLON.serialize()
  46673. ], TargetCamera.prototype, "speed", void 0);
  46674. __decorate([
  46675. BABYLON.serializeAsMeshReference("lockedTargetId")
  46676. ], TargetCamera.prototype, "lockedTarget", void 0);
  46677. return TargetCamera;
  46678. }(BABYLON.Camera));
  46679. BABYLON.TargetCamera = TargetCamera;
  46680. })(BABYLON || (BABYLON = {}));
  46681. //# sourceMappingURL=babylon.targetCamera.js.map
  46682. "use strict";
  46683. var BABYLON;
  46684. (function (BABYLON) {
  46685. var FreeCameraMouseInput = /** @class */ (function () {
  46686. function FreeCameraMouseInput(touchEnabled) {
  46687. if (touchEnabled === void 0) { touchEnabled = true; }
  46688. this.touchEnabled = touchEnabled;
  46689. this.buttons = [0, 1, 2];
  46690. this.angularSensibility = 2000.0;
  46691. this.previousPosition = null;
  46692. }
  46693. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46694. var _this = this;
  46695. var engine = this.camera.getEngine();
  46696. if (!this._pointerInput) {
  46697. this._pointerInput = function (p, s) {
  46698. var evt = p.event;
  46699. if (engine.isInVRExclusivePointerMode) {
  46700. return;
  46701. }
  46702. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46703. return;
  46704. }
  46705. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46706. return;
  46707. }
  46708. var srcElement = (evt.srcElement || evt.target);
  46709. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46710. try {
  46711. srcElement.setPointerCapture(evt.pointerId);
  46712. }
  46713. catch (e) {
  46714. //Nothing to do with the error. Execution will continue.
  46715. }
  46716. _this.previousPosition = {
  46717. x: evt.clientX,
  46718. y: evt.clientY
  46719. };
  46720. if (!noPreventDefault) {
  46721. evt.preventDefault();
  46722. element.focus();
  46723. }
  46724. }
  46725. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46726. try {
  46727. srcElement.releasePointerCapture(evt.pointerId);
  46728. }
  46729. catch (e) {
  46730. //Nothing to do with the error.
  46731. }
  46732. _this.previousPosition = null;
  46733. if (!noPreventDefault) {
  46734. evt.preventDefault();
  46735. }
  46736. }
  46737. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46738. if (!_this.previousPosition || engine.isPointerLock) {
  46739. return;
  46740. }
  46741. var offsetX = evt.clientX - _this.previousPosition.x;
  46742. var offsetY = evt.clientY - _this.previousPosition.y;
  46743. if (_this.camera.getScene().useRightHandedSystem) {
  46744. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46745. }
  46746. else {
  46747. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46748. }
  46749. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46750. _this.previousPosition = {
  46751. x: evt.clientX,
  46752. y: evt.clientY
  46753. };
  46754. if (!noPreventDefault) {
  46755. evt.preventDefault();
  46756. }
  46757. }
  46758. };
  46759. }
  46760. this._onMouseMove = function (evt) {
  46761. if (!engine.isPointerLock) {
  46762. return;
  46763. }
  46764. if (engine.isInVRExclusivePointerMode) {
  46765. return;
  46766. }
  46767. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46768. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46769. if (_this.camera.getScene().useRightHandedSystem) {
  46770. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46771. }
  46772. else {
  46773. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46774. }
  46775. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46776. _this.previousPosition = null;
  46777. if (!noPreventDefault) {
  46778. evt.preventDefault();
  46779. }
  46780. };
  46781. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46782. element.addEventListener("mousemove", this._onMouseMove, false);
  46783. };
  46784. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46785. if (this._observer && element) {
  46786. this.camera.getScene().onPointerObservable.remove(this._observer);
  46787. if (this._onMouseMove) {
  46788. element.removeEventListener("mousemove", this._onMouseMove);
  46789. }
  46790. this._observer = null;
  46791. this._onMouseMove = null;
  46792. this.previousPosition = null;
  46793. }
  46794. };
  46795. FreeCameraMouseInput.prototype.getClassName = function () {
  46796. return "FreeCameraMouseInput";
  46797. };
  46798. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46799. return "mouse";
  46800. };
  46801. __decorate([
  46802. BABYLON.serialize()
  46803. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46804. __decorate([
  46805. BABYLON.serialize()
  46806. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46807. return FreeCameraMouseInput;
  46808. }());
  46809. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46810. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46811. })(BABYLON || (BABYLON = {}));
  46812. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46813. "use strict";
  46814. var BABYLON;
  46815. (function (BABYLON) {
  46816. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46817. function FreeCameraKeyboardMoveInput() {
  46818. this._keys = new Array();
  46819. this.keysUp = [38];
  46820. this.keysDown = [40];
  46821. this.keysLeft = [37];
  46822. this.keysRight = [39];
  46823. }
  46824. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46825. var _this = this;
  46826. if (this._onCanvasBlurObserver) {
  46827. return;
  46828. }
  46829. this._scene = this.camera.getScene();
  46830. this._engine = this._scene.getEngine();
  46831. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46832. _this._keys = [];
  46833. });
  46834. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46835. var evt = info.event;
  46836. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46837. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46838. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46839. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46840. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46841. var index = _this._keys.indexOf(evt.keyCode);
  46842. if (index === -1) {
  46843. _this._keys.push(evt.keyCode);
  46844. }
  46845. if (!noPreventDefault) {
  46846. evt.preventDefault();
  46847. }
  46848. }
  46849. }
  46850. else {
  46851. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46852. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46853. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46854. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46855. var index = _this._keys.indexOf(evt.keyCode);
  46856. if (index >= 0) {
  46857. _this._keys.splice(index, 1);
  46858. }
  46859. if (!noPreventDefault) {
  46860. evt.preventDefault();
  46861. }
  46862. }
  46863. }
  46864. });
  46865. };
  46866. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46867. if (this._scene) {
  46868. if (this._onKeyboardObserver) {
  46869. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46870. }
  46871. if (this._onCanvasBlurObserver) {
  46872. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46873. }
  46874. this._onKeyboardObserver = null;
  46875. this._onCanvasBlurObserver = null;
  46876. }
  46877. this._keys = [];
  46878. };
  46879. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46880. if (this._onKeyboardObserver) {
  46881. var camera = this.camera;
  46882. // Keyboard
  46883. for (var index = 0; index < this._keys.length; index++) {
  46884. var keyCode = this._keys[index];
  46885. var speed = camera._computeLocalCameraSpeed();
  46886. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46887. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46888. }
  46889. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46890. camera._localDirection.copyFromFloats(0, 0, speed);
  46891. }
  46892. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46893. camera._localDirection.copyFromFloats(speed, 0, 0);
  46894. }
  46895. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46896. camera._localDirection.copyFromFloats(0, 0, -speed);
  46897. }
  46898. if (camera.getScene().useRightHandedSystem) {
  46899. camera._localDirection.z *= -1;
  46900. }
  46901. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46902. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46903. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46904. }
  46905. }
  46906. };
  46907. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46908. return "FreeCameraKeyboardMoveInput";
  46909. };
  46910. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46911. this._keys = [];
  46912. };
  46913. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46914. return "keyboard";
  46915. };
  46916. __decorate([
  46917. BABYLON.serialize()
  46918. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46919. __decorate([
  46920. BABYLON.serialize()
  46921. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46922. __decorate([
  46923. BABYLON.serialize()
  46924. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46925. __decorate([
  46926. BABYLON.serialize()
  46927. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46928. return FreeCameraKeyboardMoveInput;
  46929. }());
  46930. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46931. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46932. })(BABYLON || (BABYLON = {}));
  46933. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46934. "use strict";
  46935. var BABYLON;
  46936. (function (BABYLON) {
  46937. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46938. __extends(FreeCameraInputsManager, _super);
  46939. function FreeCameraInputsManager(camera) {
  46940. return _super.call(this, camera) || this;
  46941. }
  46942. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46943. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46944. return this;
  46945. };
  46946. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46947. if (touchEnabled === void 0) { touchEnabled = true; }
  46948. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46949. return this;
  46950. };
  46951. FreeCameraInputsManager.prototype.addGamepad = function () {
  46952. this.add(new BABYLON.FreeCameraGamepadInput());
  46953. return this;
  46954. };
  46955. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46956. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46957. return this;
  46958. };
  46959. FreeCameraInputsManager.prototype.addTouch = function () {
  46960. this.add(new BABYLON.FreeCameraTouchInput());
  46961. return this;
  46962. };
  46963. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46964. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46965. return this;
  46966. };
  46967. return FreeCameraInputsManager;
  46968. }(BABYLON.CameraInputsManager));
  46969. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46970. })(BABYLON || (BABYLON = {}));
  46971. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46972. "use strict";
  46973. var BABYLON;
  46974. (function (BABYLON) {
  46975. var FreeCamera = /** @class */ (function (_super) {
  46976. __extends(FreeCamera, _super);
  46977. function FreeCamera(name, position, scene) {
  46978. var _this = _super.call(this, name, position, scene) || this;
  46979. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46980. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46981. _this.checkCollisions = false;
  46982. _this.applyGravity = false;
  46983. _this._needMoveForGravity = false;
  46984. _this._oldPosition = BABYLON.Vector3.Zero();
  46985. _this._diffPosition = BABYLON.Vector3.Zero();
  46986. _this._newPosition = BABYLON.Vector3.Zero();
  46987. // Collisions
  46988. _this._collisionMask = -1;
  46989. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46990. if (collidedMesh === void 0) { collidedMesh = null; }
  46991. //TODO move this to the collision coordinator!
  46992. if (_this.getScene().workerCollisions)
  46993. newPosition.multiplyInPlace(_this._collider._radius);
  46994. var updatePosition = function (newPos) {
  46995. _this._newPosition.copyFrom(newPos);
  46996. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46997. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46998. _this.position.addInPlace(_this._diffPosition);
  46999. if (_this.onCollide && collidedMesh) {
  47000. _this.onCollide(collidedMesh);
  47001. }
  47002. }
  47003. };
  47004. updatePosition(newPosition);
  47005. };
  47006. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47007. _this.inputs.addKeyboard().addMouse();
  47008. return _this;
  47009. }
  47010. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47011. //-- begin properties for backward compatibility for inputs
  47012. /**
  47013. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47014. * Higher values reduce sensitivity.
  47015. */
  47016. get: function () {
  47017. var mouse = this.inputs.attached["mouse"];
  47018. if (mouse)
  47019. return mouse.angularSensibility;
  47020. return 0;
  47021. },
  47022. /**
  47023. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47024. * Higher values reduce sensitivity.
  47025. */
  47026. set: function (value) {
  47027. var mouse = this.inputs.attached["mouse"];
  47028. if (mouse)
  47029. mouse.angularSensibility = value;
  47030. },
  47031. enumerable: true,
  47032. configurable: true
  47033. });
  47034. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47035. get: function () {
  47036. var keyboard = this.inputs.attached["keyboard"];
  47037. if (keyboard)
  47038. return keyboard.keysUp;
  47039. return [];
  47040. },
  47041. set: function (value) {
  47042. var keyboard = this.inputs.attached["keyboard"];
  47043. if (keyboard)
  47044. keyboard.keysUp = value;
  47045. },
  47046. enumerable: true,
  47047. configurable: true
  47048. });
  47049. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47050. get: function () {
  47051. var keyboard = this.inputs.attached["keyboard"];
  47052. if (keyboard)
  47053. return keyboard.keysDown;
  47054. return [];
  47055. },
  47056. set: function (value) {
  47057. var keyboard = this.inputs.attached["keyboard"];
  47058. if (keyboard)
  47059. keyboard.keysDown = value;
  47060. },
  47061. enumerable: true,
  47062. configurable: true
  47063. });
  47064. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47065. get: function () {
  47066. var keyboard = this.inputs.attached["keyboard"];
  47067. if (keyboard)
  47068. return keyboard.keysLeft;
  47069. return [];
  47070. },
  47071. set: function (value) {
  47072. var keyboard = this.inputs.attached["keyboard"];
  47073. if (keyboard)
  47074. keyboard.keysLeft = value;
  47075. },
  47076. enumerable: true,
  47077. configurable: true
  47078. });
  47079. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47080. get: function () {
  47081. var keyboard = this.inputs.attached["keyboard"];
  47082. if (keyboard)
  47083. return keyboard.keysRight;
  47084. return [];
  47085. },
  47086. set: function (value) {
  47087. var keyboard = this.inputs.attached["keyboard"];
  47088. if (keyboard)
  47089. keyboard.keysRight = value;
  47090. },
  47091. enumerable: true,
  47092. configurable: true
  47093. });
  47094. // Controls
  47095. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47096. this.inputs.attachElement(element, noPreventDefault);
  47097. };
  47098. FreeCamera.prototype.detachControl = function (element) {
  47099. this.inputs.detachElement(element);
  47100. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47101. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47102. };
  47103. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47104. get: function () {
  47105. return this._collisionMask;
  47106. },
  47107. set: function (mask) {
  47108. this._collisionMask = !isNaN(mask) ? mask : -1;
  47109. },
  47110. enumerable: true,
  47111. configurable: true
  47112. });
  47113. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47114. var globalPosition;
  47115. if (this.parent) {
  47116. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47117. }
  47118. else {
  47119. globalPosition = this.position;
  47120. }
  47121. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47122. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47123. if (!this._collider) {
  47124. this._collider = new BABYLON.Collider();
  47125. }
  47126. this._collider._radius = this.ellipsoid;
  47127. this._collider.collisionMask = this._collisionMask;
  47128. //no need for clone, as long as gravity is not on.
  47129. var actualDisplacement = displacement;
  47130. //add gravity to the direction to prevent the dual-collision checking
  47131. if (this.applyGravity) {
  47132. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47133. actualDisplacement = displacement.add(this.getScene().gravity);
  47134. }
  47135. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47136. };
  47137. FreeCamera.prototype._checkInputs = function () {
  47138. if (!this._localDirection) {
  47139. this._localDirection = BABYLON.Vector3.Zero();
  47140. this._transformedDirection = BABYLON.Vector3.Zero();
  47141. }
  47142. this.inputs.checkInputs();
  47143. _super.prototype._checkInputs.call(this);
  47144. };
  47145. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47146. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47147. };
  47148. FreeCamera.prototype._updatePosition = function () {
  47149. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47150. this._collideWithWorld(this.cameraDirection);
  47151. }
  47152. else {
  47153. _super.prototype._updatePosition.call(this);
  47154. }
  47155. };
  47156. FreeCamera.prototype.dispose = function () {
  47157. this.inputs.clear();
  47158. _super.prototype.dispose.call(this);
  47159. };
  47160. FreeCamera.prototype.getClassName = function () {
  47161. return "FreeCamera";
  47162. };
  47163. __decorate([
  47164. BABYLON.serializeAsVector3()
  47165. ], FreeCamera.prototype, "ellipsoid", void 0);
  47166. __decorate([
  47167. BABYLON.serializeAsVector3()
  47168. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47169. __decorate([
  47170. BABYLON.serialize()
  47171. ], FreeCamera.prototype, "checkCollisions", void 0);
  47172. __decorate([
  47173. BABYLON.serialize()
  47174. ], FreeCamera.prototype, "applyGravity", void 0);
  47175. return FreeCamera;
  47176. }(BABYLON.TargetCamera));
  47177. BABYLON.FreeCamera = FreeCamera;
  47178. })(BABYLON || (BABYLON = {}));
  47179. //# sourceMappingURL=babylon.freeCamera.js.map
  47180. "use strict";
  47181. var BABYLON;
  47182. (function (BABYLON) {
  47183. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47184. function ArcRotateCameraKeyboardMoveInput() {
  47185. this._keys = new Array();
  47186. this.keysUp = [38];
  47187. this.keysDown = [40];
  47188. this.keysLeft = [37];
  47189. this.keysRight = [39];
  47190. this.keysReset = [220];
  47191. this.panningSensibility = 50.0;
  47192. this.zoomingSensibility = 25.0;
  47193. this.useAltToZoom = true;
  47194. }
  47195. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47196. var _this = this;
  47197. if (this._onCanvasBlurObserver) {
  47198. return;
  47199. }
  47200. this._scene = this.camera.getScene();
  47201. this._engine = this._scene.getEngine();
  47202. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47203. _this._keys = [];
  47204. });
  47205. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47206. var evt = info.event;
  47207. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47208. _this._ctrlPressed = evt.ctrlKey;
  47209. _this._altPressed = evt.altKey;
  47210. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47211. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47212. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47213. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47214. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47215. var index = _this._keys.indexOf(evt.keyCode);
  47216. if (index === -1) {
  47217. _this._keys.push(evt.keyCode);
  47218. }
  47219. if (evt.preventDefault) {
  47220. if (!noPreventDefault) {
  47221. evt.preventDefault();
  47222. }
  47223. }
  47224. }
  47225. }
  47226. else {
  47227. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47228. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47229. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47230. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47231. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47232. var index = _this._keys.indexOf(evt.keyCode);
  47233. if (index >= 0) {
  47234. _this._keys.splice(index, 1);
  47235. }
  47236. if (evt.preventDefault) {
  47237. if (!noPreventDefault) {
  47238. evt.preventDefault();
  47239. }
  47240. }
  47241. }
  47242. }
  47243. });
  47244. };
  47245. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47246. if (this._scene) {
  47247. if (this._onKeyboardObserver) {
  47248. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47249. }
  47250. if (this._onCanvasBlurObserver) {
  47251. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47252. }
  47253. this._onKeyboardObserver = null;
  47254. this._onCanvasBlurObserver = null;
  47255. }
  47256. this._keys = [];
  47257. };
  47258. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47259. if (this._onKeyboardObserver) {
  47260. var camera = this.camera;
  47261. for (var index = 0; index < this._keys.length; index++) {
  47262. var keyCode = this._keys[index];
  47263. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47264. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47265. camera.inertialPanningX -= 1 / this.panningSensibility;
  47266. }
  47267. else {
  47268. camera.inertialAlphaOffset -= 0.01;
  47269. }
  47270. }
  47271. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47272. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47273. camera.inertialPanningY += 1 / this.panningSensibility;
  47274. }
  47275. else if (this._altPressed && this.useAltToZoom) {
  47276. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47277. }
  47278. else {
  47279. camera.inertialBetaOffset -= 0.01;
  47280. }
  47281. }
  47282. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47283. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47284. camera.inertialPanningX += 1 / this.panningSensibility;
  47285. }
  47286. else {
  47287. camera.inertialAlphaOffset += 0.01;
  47288. }
  47289. }
  47290. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47291. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47292. camera.inertialPanningY -= 1 / this.panningSensibility;
  47293. }
  47294. else if (this._altPressed && this.useAltToZoom) {
  47295. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47296. }
  47297. else {
  47298. camera.inertialBetaOffset += 0.01;
  47299. }
  47300. }
  47301. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47302. camera.restoreState();
  47303. }
  47304. }
  47305. }
  47306. };
  47307. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47308. return "ArcRotateCameraKeyboardMoveInput";
  47309. };
  47310. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47311. return "keyboard";
  47312. };
  47313. __decorate([
  47314. BABYLON.serialize()
  47315. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47316. __decorate([
  47317. BABYLON.serialize()
  47318. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47319. __decorate([
  47320. BABYLON.serialize()
  47321. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47322. __decorate([
  47323. BABYLON.serialize()
  47324. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47325. __decorate([
  47326. BABYLON.serialize()
  47327. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47328. __decorate([
  47329. BABYLON.serialize()
  47330. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47331. __decorate([
  47332. BABYLON.serialize()
  47333. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47334. __decorate([
  47335. BABYLON.serialize()
  47336. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47337. return ArcRotateCameraKeyboardMoveInput;
  47338. }());
  47339. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47340. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47341. })(BABYLON || (BABYLON = {}));
  47342. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47343. "use strict";
  47344. var BABYLON;
  47345. (function (BABYLON) {
  47346. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47347. function ArcRotateCameraMouseWheelInput() {
  47348. this.wheelPrecision = 3.0;
  47349. /**
  47350. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47351. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47352. */
  47353. this.wheelDeltaPercentage = 0;
  47354. }
  47355. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47356. var _this = this;
  47357. this._wheel = function (p, s) {
  47358. //sanity check - this should be a PointerWheel event.
  47359. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47360. return;
  47361. var event = p.event;
  47362. var delta = 0;
  47363. if (event.wheelDelta) {
  47364. if (_this.wheelDeltaPercentage) {
  47365. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47366. if (event.wheelDelta > 0) {
  47367. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47368. }
  47369. else {
  47370. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47371. }
  47372. }
  47373. else {
  47374. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47375. }
  47376. }
  47377. else if (event.detail) {
  47378. delta = -event.detail / _this.wheelPrecision;
  47379. }
  47380. if (delta)
  47381. _this.camera.inertialRadiusOffset += delta;
  47382. if (event.preventDefault) {
  47383. if (!noPreventDefault) {
  47384. event.preventDefault();
  47385. }
  47386. }
  47387. };
  47388. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47389. };
  47390. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47391. if (this._observer && element) {
  47392. this.camera.getScene().onPointerObservable.remove(this._observer);
  47393. this._observer = null;
  47394. this._wheel = null;
  47395. }
  47396. };
  47397. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47398. return "ArcRotateCameraMouseWheelInput";
  47399. };
  47400. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47401. return "mousewheel";
  47402. };
  47403. __decorate([
  47404. BABYLON.serialize()
  47405. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47406. __decorate([
  47407. BABYLON.serialize()
  47408. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47409. return ArcRotateCameraMouseWheelInput;
  47410. }());
  47411. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47412. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47413. })(BABYLON || (BABYLON = {}));
  47414. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47415. "use strict";
  47416. var BABYLON;
  47417. (function (BABYLON) {
  47418. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47419. function ArcRotateCameraPointersInput() {
  47420. this.buttons = [0, 1, 2];
  47421. this.angularSensibilityX = 1000.0;
  47422. this.angularSensibilityY = 1000.0;
  47423. this.pinchPrecision = 12.0;
  47424. /**
  47425. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47426. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47427. */
  47428. this.pinchDeltaPercentage = 0;
  47429. this.panningSensibility = 1000.0;
  47430. this.multiTouchPanning = true;
  47431. this.multiTouchPanAndZoom = true;
  47432. this._isPanClick = false;
  47433. this.pinchInwards = true;
  47434. }
  47435. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47436. var _this = this;
  47437. var engine = this.camera.getEngine();
  47438. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47439. var pointA = null;
  47440. var pointB = null;
  47441. var previousPinchSquaredDistance = 0;
  47442. var initialDistance = 0;
  47443. var twoFingerActivityCount = 0;
  47444. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47445. this._pointerInput = function (p, s) {
  47446. var evt = p.event;
  47447. var isTouch = p.event.pointerType === "touch";
  47448. if (engine.isInVRExclusivePointerMode) {
  47449. return;
  47450. }
  47451. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47452. return;
  47453. }
  47454. var srcElement = (evt.srcElement || evt.target);
  47455. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47456. try {
  47457. srcElement.setPointerCapture(evt.pointerId);
  47458. }
  47459. catch (e) {
  47460. //Nothing to do with the error. Execution will continue.
  47461. }
  47462. // Manage panning with pan button click
  47463. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47464. // manage pointers
  47465. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47466. if (pointA === null) {
  47467. pointA = cacheSoloPointer;
  47468. }
  47469. else if (pointB === null) {
  47470. pointB = cacheSoloPointer;
  47471. }
  47472. if (!noPreventDefault) {
  47473. evt.preventDefault();
  47474. element.focus();
  47475. }
  47476. }
  47477. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47478. _this.camera.restoreState();
  47479. }
  47480. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47481. try {
  47482. srcElement.releasePointerCapture(evt.pointerId);
  47483. }
  47484. catch (e) {
  47485. //Nothing to do with the error.
  47486. }
  47487. cacheSoloPointer = null;
  47488. previousPinchSquaredDistance = 0;
  47489. previousMultiTouchPanPosition.isPaning = false;
  47490. previousMultiTouchPanPosition.isPinching = false;
  47491. twoFingerActivityCount = 0;
  47492. initialDistance = 0;
  47493. if (!isTouch) {
  47494. pointB = null; // Mouse and pen are mono pointer
  47495. }
  47496. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47497. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47498. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47499. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47500. if (engine._badOS) {
  47501. pointA = pointB = null;
  47502. }
  47503. else {
  47504. //only remove the impacted pointer in case of multitouch allowing on most
  47505. //platforms switching from rotate to zoom and pan seamlessly.
  47506. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47507. pointA = pointB;
  47508. pointB = null;
  47509. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47510. }
  47511. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47512. pointB = null;
  47513. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47514. }
  47515. else {
  47516. pointA = pointB = null;
  47517. }
  47518. }
  47519. if (!noPreventDefault) {
  47520. evt.preventDefault();
  47521. }
  47522. }
  47523. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47524. if (!noPreventDefault) {
  47525. evt.preventDefault();
  47526. }
  47527. // One button down
  47528. if (pointA && pointB === null && cacheSoloPointer) {
  47529. if (_this.panningSensibility !== 0 &&
  47530. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47531. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47532. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47533. }
  47534. else {
  47535. var offsetX = evt.clientX - cacheSoloPointer.x;
  47536. var offsetY = evt.clientY - cacheSoloPointer.y;
  47537. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47538. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47539. }
  47540. cacheSoloPointer.x = evt.clientX;
  47541. cacheSoloPointer.y = evt.clientY;
  47542. }
  47543. else if (pointA && pointB) {
  47544. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47545. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47546. ed.x = evt.clientX;
  47547. ed.y = evt.clientY;
  47548. var direction = _this.pinchInwards ? 1 : -1;
  47549. var distX = pointA.x - pointB.x;
  47550. var distY = pointA.y - pointB.y;
  47551. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47552. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47553. if (previousPinchSquaredDistance === 0) {
  47554. initialDistance = pinchDistance;
  47555. previousPinchSquaredDistance = pinchSquaredDistance;
  47556. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47557. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47558. return;
  47559. }
  47560. if (_this.multiTouchPanAndZoom) {
  47561. if (_this.pinchDeltaPercentage) {
  47562. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47563. }
  47564. else {
  47565. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47566. (_this.pinchPrecision *
  47567. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47568. direction);
  47569. }
  47570. if (_this.panningSensibility !== 0) {
  47571. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47572. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47573. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47574. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47575. previousMultiTouchPanPosition.x = pointersCenterX;
  47576. previousMultiTouchPanPosition.y = pointersCenterY;
  47577. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47578. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47579. }
  47580. }
  47581. else {
  47582. twoFingerActivityCount++;
  47583. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47584. if (_this.pinchDeltaPercentage) {
  47585. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47586. }
  47587. else {
  47588. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47589. (_this.pinchPrecision *
  47590. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47591. direction);
  47592. }
  47593. previousMultiTouchPanPosition.isPaning = false;
  47594. previousMultiTouchPanPosition.isPinching = true;
  47595. }
  47596. else {
  47597. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47598. if (!previousMultiTouchPanPosition.isPaning) {
  47599. previousMultiTouchPanPosition.isPaning = true;
  47600. previousMultiTouchPanPosition.isPinching = false;
  47601. previousMultiTouchPanPosition.x = ed.x;
  47602. previousMultiTouchPanPosition.y = ed.y;
  47603. return;
  47604. }
  47605. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47606. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47607. }
  47608. }
  47609. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47610. previousMultiTouchPanPosition.x = ed.x;
  47611. previousMultiTouchPanPosition.y = ed.y;
  47612. }
  47613. }
  47614. previousPinchSquaredDistance = pinchSquaredDistance;
  47615. }
  47616. }
  47617. };
  47618. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47619. this._onContextMenu = function (evt) {
  47620. evt.preventDefault();
  47621. };
  47622. if (!this.camera._useCtrlForPanning) {
  47623. element.addEventListener("contextmenu", this._onContextMenu, false);
  47624. }
  47625. this._onLostFocus = function () {
  47626. //this._keys = [];
  47627. pointA = pointB = null;
  47628. previousPinchSquaredDistance = 0;
  47629. previousMultiTouchPanPosition.isPaning = false;
  47630. previousMultiTouchPanPosition.isPinching = false;
  47631. twoFingerActivityCount = 0;
  47632. cacheSoloPointer = null;
  47633. initialDistance = 0;
  47634. };
  47635. this._onMouseMove = function (evt) {
  47636. if (!engine.isPointerLock) {
  47637. return;
  47638. }
  47639. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47640. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47641. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47642. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47643. if (!noPreventDefault) {
  47644. evt.preventDefault();
  47645. }
  47646. };
  47647. this._onGestureStart = function (e) {
  47648. if (window.MSGesture === undefined) {
  47649. return;
  47650. }
  47651. if (!_this._MSGestureHandler) {
  47652. _this._MSGestureHandler = new MSGesture();
  47653. _this._MSGestureHandler.target = element;
  47654. }
  47655. _this._MSGestureHandler.addPointer(e.pointerId);
  47656. };
  47657. this._onGesture = function (e) {
  47658. _this.camera.radius *= e.scale;
  47659. if (e.preventDefault) {
  47660. if (!noPreventDefault) {
  47661. e.stopPropagation();
  47662. e.preventDefault();
  47663. }
  47664. }
  47665. };
  47666. element.addEventListener("mousemove", this._onMouseMove, false);
  47667. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47668. element.addEventListener("MSGestureChange", this._onGesture, false);
  47669. BABYLON.Tools.RegisterTopRootEvents([
  47670. { name: "blur", handler: this._onLostFocus }
  47671. ]);
  47672. };
  47673. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47674. if (this._onLostFocus) {
  47675. BABYLON.Tools.UnregisterTopRootEvents([
  47676. { name: "blur", handler: this._onLostFocus }
  47677. ]);
  47678. }
  47679. if (element && this._observer) {
  47680. this.camera.getScene().onPointerObservable.remove(this._observer);
  47681. this._observer = null;
  47682. if (this._onContextMenu) {
  47683. element.removeEventListener("contextmenu", this._onContextMenu);
  47684. }
  47685. if (this._onMouseMove) {
  47686. element.removeEventListener("mousemove", this._onMouseMove);
  47687. }
  47688. if (this._onGestureStart) {
  47689. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47690. }
  47691. if (this._onGesture) {
  47692. element.removeEventListener("MSGestureChange", this._onGesture);
  47693. }
  47694. this._isPanClick = false;
  47695. this.pinchInwards = true;
  47696. this._onMouseMove = null;
  47697. this._onGestureStart = null;
  47698. this._onGesture = null;
  47699. this._MSGestureHandler = null;
  47700. this._onLostFocus = null;
  47701. this._onContextMenu = null;
  47702. }
  47703. };
  47704. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47705. return "ArcRotateCameraPointersInput";
  47706. };
  47707. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47708. return "pointers";
  47709. };
  47710. __decorate([
  47711. BABYLON.serialize()
  47712. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47713. __decorate([
  47714. BABYLON.serialize()
  47715. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47716. __decorate([
  47717. BABYLON.serialize()
  47718. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47719. __decorate([
  47720. BABYLON.serialize()
  47721. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47722. __decorate([
  47723. BABYLON.serialize()
  47724. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47725. __decorate([
  47726. BABYLON.serialize()
  47727. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47728. __decorate([
  47729. BABYLON.serialize()
  47730. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47731. __decorate([
  47732. BABYLON.serialize()
  47733. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47734. return ArcRotateCameraPointersInput;
  47735. }());
  47736. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47737. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47738. })(BABYLON || (BABYLON = {}));
  47739. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47740. "use strict";
  47741. var BABYLON;
  47742. (function (BABYLON) {
  47743. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47744. __extends(ArcRotateCameraInputsManager, _super);
  47745. function ArcRotateCameraInputsManager(camera) {
  47746. return _super.call(this, camera) || this;
  47747. }
  47748. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47749. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47750. return this;
  47751. };
  47752. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47753. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47754. return this;
  47755. };
  47756. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47757. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47758. return this;
  47759. };
  47760. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47761. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47762. return this;
  47763. };
  47764. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47765. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47766. return this;
  47767. };
  47768. return ArcRotateCameraInputsManager;
  47769. }(BABYLON.CameraInputsManager));
  47770. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47771. })(BABYLON || (BABYLON = {}));
  47772. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47773. "use strict";
  47774. var BABYLON;
  47775. (function (BABYLON) {
  47776. var ArcRotateCamera = /** @class */ (function (_super) {
  47777. __extends(ArcRotateCamera, _super);
  47778. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  47779. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  47780. _this.inertialAlphaOffset = 0;
  47781. _this.inertialBetaOffset = 0;
  47782. _this.inertialRadiusOffset = 0;
  47783. _this.lowerAlphaLimit = null;
  47784. _this.upperAlphaLimit = null;
  47785. _this.lowerBetaLimit = 0.01;
  47786. _this.upperBetaLimit = Math.PI;
  47787. _this.lowerRadiusLimit = null;
  47788. _this.upperRadiusLimit = null;
  47789. _this.inertialPanningX = 0;
  47790. _this.inertialPanningY = 0;
  47791. _this.pinchToPanMaxDistance = 20;
  47792. _this.panningDistanceLimit = null;
  47793. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47794. _this.panningInertia = 0.9;
  47795. //-- end properties for backward compatibility for inputs
  47796. _this.zoomOnFactor = 1;
  47797. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47798. _this.allowUpsideDown = true;
  47799. _this._viewMatrix = new BABYLON.Matrix();
  47800. // Panning
  47801. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47802. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47803. _this.checkCollisions = false;
  47804. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47805. _this._previousPosition = BABYLON.Vector3.Zero();
  47806. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47807. _this._newPosition = BABYLON.Vector3.Zero();
  47808. _this._computationVector = BABYLON.Vector3.Zero();
  47809. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47810. if (collidedMesh === void 0) { collidedMesh = null; }
  47811. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47812. newPosition.multiplyInPlace(_this._collider._radius);
  47813. }
  47814. if (!collidedMesh) {
  47815. _this._previousPosition.copyFrom(_this.position);
  47816. }
  47817. else {
  47818. _this.setPosition(newPosition);
  47819. if (_this.onCollide) {
  47820. _this.onCollide(collidedMesh);
  47821. }
  47822. }
  47823. // Recompute because of constraints
  47824. var cosa = Math.cos(_this.alpha);
  47825. var sina = Math.sin(_this.alpha);
  47826. var cosb = Math.cos(_this.beta);
  47827. var sinb = Math.sin(_this.beta);
  47828. if (sinb === 0) {
  47829. sinb = 0.0001;
  47830. }
  47831. var target = _this._getTargetPosition();
  47832. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47833. target.addToRef(_this._computationVector, _this._newPosition);
  47834. _this.position.copyFrom(_this._newPosition);
  47835. var up = _this.upVector;
  47836. if (_this.allowUpsideDown && _this.beta < 0) {
  47837. up = up.clone();
  47838. up = up.negate();
  47839. }
  47840. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  47841. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47842. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47843. _this._collisionTriggered = false;
  47844. };
  47845. _this._target = BABYLON.Vector3.Zero();
  47846. if (target) {
  47847. _this.setTarget(target);
  47848. }
  47849. _this.alpha = alpha;
  47850. _this.beta = beta;
  47851. _this.radius = radius;
  47852. _this.getViewMatrix();
  47853. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47854. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47855. return _this;
  47856. }
  47857. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47858. get: function () {
  47859. return this._target;
  47860. },
  47861. set: function (value) {
  47862. this.setTarget(value);
  47863. },
  47864. enumerable: true,
  47865. configurable: true
  47866. });
  47867. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47868. //-- begin properties for backward compatibility for inputs
  47869. get: function () {
  47870. var pointers = this.inputs.attached["pointers"];
  47871. if (pointers)
  47872. return pointers.angularSensibilityX;
  47873. return 0;
  47874. },
  47875. set: function (value) {
  47876. var pointers = this.inputs.attached["pointers"];
  47877. if (pointers) {
  47878. pointers.angularSensibilityX = value;
  47879. }
  47880. },
  47881. enumerable: true,
  47882. configurable: true
  47883. });
  47884. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47885. get: function () {
  47886. var pointers = this.inputs.attached["pointers"];
  47887. if (pointers)
  47888. return pointers.angularSensibilityY;
  47889. return 0;
  47890. },
  47891. set: function (value) {
  47892. var pointers = this.inputs.attached["pointers"];
  47893. if (pointers) {
  47894. pointers.angularSensibilityY = value;
  47895. }
  47896. },
  47897. enumerable: true,
  47898. configurable: true
  47899. });
  47900. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47901. get: function () {
  47902. var pointers = this.inputs.attached["pointers"];
  47903. if (pointers)
  47904. return pointers.pinchPrecision;
  47905. return 0;
  47906. },
  47907. set: function (value) {
  47908. var pointers = this.inputs.attached["pointers"];
  47909. if (pointers) {
  47910. pointers.pinchPrecision = value;
  47911. }
  47912. },
  47913. enumerable: true,
  47914. configurable: true
  47915. });
  47916. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47917. get: function () {
  47918. var pointers = this.inputs.attached["pointers"];
  47919. if (pointers)
  47920. return pointers.pinchDeltaPercentage;
  47921. return 0;
  47922. },
  47923. set: function (value) {
  47924. var pointers = this.inputs.attached["pointers"];
  47925. if (pointers) {
  47926. pointers.pinchDeltaPercentage = value;
  47927. }
  47928. },
  47929. enumerable: true,
  47930. configurable: true
  47931. });
  47932. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47933. get: function () {
  47934. var pointers = this.inputs.attached["pointers"];
  47935. if (pointers)
  47936. return pointers.panningSensibility;
  47937. return 0;
  47938. },
  47939. set: function (value) {
  47940. var pointers = this.inputs.attached["pointers"];
  47941. if (pointers) {
  47942. pointers.panningSensibility = value;
  47943. }
  47944. },
  47945. enumerable: true,
  47946. configurable: true
  47947. });
  47948. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47949. get: function () {
  47950. var keyboard = this.inputs.attached["keyboard"];
  47951. if (keyboard)
  47952. return keyboard.keysUp;
  47953. return [];
  47954. },
  47955. set: function (value) {
  47956. var keyboard = this.inputs.attached["keyboard"];
  47957. if (keyboard)
  47958. keyboard.keysUp = value;
  47959. },
  47960. enumerable: true,
  47961. configurable: true
  47962. });
  47963. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47964. get: function () {
  47965. var keyboard = this.inputs.attached["keyboard"];
  47966. if (keyboard)
  47967. return keyboard.keysDown;
  47968. return [];
  47969. },
  47970. set: function (value) {
  47971. var keyboard = this.inputs.attached["keyboard"];
  47972. if (keyboard)
  47973. keyboard.keysDown = value;
  47974. },
  47975. enumerable: true,
  47976. configurable: true
  47977. });
  47978. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47979. get: function () {
  47980. var keyboard = this.inputs.attached["keyboard"];
  47981. if (keyboard)
  47982. return keyboard.keysLeft;
  47983. return [];
  47984. },
  47985. set: function (value) {
  47986. var keyboard = this.inputs.attached["keyboard"];
  47987. if (keyboard)
  47988. keyboard.keysLeft = value;
  47989. },
  47990. enumerable: true,
  47991. configurable: true
  47992. });
  47993. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47994. get: function () {
  47995. var keyboard = this.inputs.attached["keyboard"];
  47996. if (keyboard)
  47997. return keyboard.keysRight;
  47998. return [];
  47999. },
  48000. set: function (value) {
  48001. var keyboard = this.inputs.attached["keyboard"];
  48002. if (keyboard)
  48003. keyboard.keysRight = value;
  48004. },
  48005. enumerable: true,
  48006. configurable: true
  48007. });
  48008. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48009. get: function () {
  48010. var mousewheel = this.inputs.attached["mousewheel"];
  48011. if (mousewheel)
  48012. return mousewheel.wheelPrecision;
  48013. return 0;
  48014. },
  48015. set: function (value) {
  48016. var mousewheel = this.inputs.attached["mousewheel"];
  48017. if (mousewheel)
  48018. mousewheel.wheelPrecision = value;
  48019. },
  48020. enumerable: true,
  48021. configurable: true
  48022. });
  48023. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48024. get: function () {
  48025. var mousewheel = this.inputs.attached["mousewheel"];
  48026. if (mousewheel)
  48027. return mousewheel.wheelDeltaPercentage;
  48028. return 0;
  48029. },
  48030. set: function (value) {
  48031. var mousewheel = this.inputs.attached["mousewheel"];
  48032. if (mousewheel)
  48033. mousewheel.wheelDeltaPercentage = value;
  48034. },
  48035. enumerable: true,
  48036. configurable: true
  48037. });
  48038. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48039. get: function () {
  48040. return this._bouncingBehavior;
  48041. },
  48042. enumerable: true,
  48043. configurable: true
  48044. });
  48045. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48046. get: function () {
  48047. return this._bouncingBehavior != null;
  48048. },
  48049. set: function (value) {
  48050. if (value === this.useBouncingBehavior) {
  48051. return;
  48052. }
  48053. if (value) {
  48054. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48055. this.addBehavior(this._bouncingBehavior);
  48056. }
  48057. else if (this._bouncingBehavior) {
  48058. this.removeBehavior(this._bouncingBehavior);
  48059. this._bouncingBehavior = null;
  48060. }
  48061. },
  48062. enumerable: true,
  48063. configurable: true
  48064. });
  48065. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48066. get: function () {
  48067. return this._framingBehavior;
  48068. },
  48069. enumerable: true,
  48070. configurable: true
  48071. });
  48072. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48073. get: function () {
  48074. return this._framingBehavior != null;
  48075. },
  48076. set: function (value) {
  48077. if (value === this.useFramingBehavior) {
  48078. return;
  48079. }
  48080. if (value) {
  48081. this._framingBehavior = new BABYLON.FramingBehavior();
  48082. this.addBehavior(this._framingBehavior);
  48083. }
  48084. else if (this._framingBehavior) {
  48085. this.removeBehavior(this._framingBehavior);
  48086. this._framingBehavior = null;
  48087. }
  48088. },
  48089. enumerable: true,
  48090. configurable: true
  48091. });
  48092. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48093. get: function () {
  48094. return this._autoRotationBehavior;
  48095. },
  48096. enumerable: true,
  48097. configurable: true
  48098. });
  48099. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48100. get: function () {
  48101. return this._autoRotationBehavior != null;
  48102. },
  48103. set: function (value) {
  48104. if (value === this.useAutoRotationBehavior) {
  48105. return;
  48106. }
  48107. if (value) {
  48108. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48109. this.addBehavior(this._autoRotationBehavior);
  48110. }
  48111. else if (this._autoRotationBehavior) {
  48112. this.removeBehavior(this._autoRotationBehavior);
  48113. this._autoRotationBehavior = null;
  48114. }
  48115. },
  48116. enumerable: true,
  48117. configurable: true
  48118. });
  48119. // Cache
  48120. ArcRotateCamera.prototype._initCache = function () {
  48121. _super.prototype._initCache.call(this);
  48122. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48123. this._cache.alpha = undefined;
  48124. this._cache.beta = undefined;
  48125. this._cache.radius = undefined;
  48126. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48127. };
  48128. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48129. if (!ignoreParentClass) {
  48130. _super.prototype._updateCache.call(this);
  48131. }
  48132. this._cache._target.copyFrom(this._getTargetPosition());
  48133. this._cache.alpha = this.alpha;
  48134. this._cache.beta = this.beta;
  48135. this._cache.radius = this.radius;
  48136. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48137. };
  48138. ArcRotateCamera.prototype._getTargetPosition = function () {
  48139. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48140. var pos = this._targetHost.getAbsolutePosition();
  48141. if (this._targetBoundingCenter) {
  48142. pos.addToRef(this._targetBoundingCenter, this._target);
  48143. }
  48144. else {
  48145. this._target.copyFrom(pos);
  48146. }
  48147. }
  48148. var lockedTargetPosition = this._getLockedTargetPosition();
  48149. if (lockedTargetPosition) {
  48150. return lockedTargetPosition;
  48151. }
  48152. return this._target;
  48153. };
  48154. ArcRotateCamera.prototype.storeState = function () {
  48155. this._storedAlpha = this.alpha;
  48156. this._storedBeta = this.beta;
  48157. this._storedRadius = this.radius;
  48158. this._storedTarget = this._getTargetPosition().clone();
  48159. return _super.prototype.storeState.call(this);
  48160. };
  48161. /**
  48162. * Restored camera state. You must call storeState() first
  48163. */
  48164. ArcRotateCamera.prototype._restoreStateValues = function () {
  48165. if (!_super.prototype._restoreStateValues.call(this)) {
  48166. return false;
  48167. }
  48168. this.alpha = this._storedAlpha;
  48169. this.beta = this._storedBeta;
  48170. this.radius = this._storedRadius;
  48171. this.setTarget(this._storedTarget.clone());
  48172. this.inertialAlphaOffset = 0;
  48173. this.inertialBetaOffset = 0;
  48174. this.inertialRadiusOffset = 0;
  48175. this.inertialPanningX = 0;
  48176. this.inertialPanningY = 0;
  48177. return true;
  48178. };
  48179. // Synchronized
  48180. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48181. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48182. return false;
  48183. return this._cache._target.equals(this._getTargetPosition())
  48184. && this._cache.alpha === this.alpha
  48185. && this._cache.beta === this.beta
  48186. && this._cache.radius === this.radius
  48187. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48188. };
  48189. // Methods
  48190. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48191. var _this = this;
  48192. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48193. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48194. this._useCtrlForPanning = useCtrlForPanning;
  48195. this._panningMouseButton = panningMouseButton;
  48196. this.inputs.attachElement(element, noPreventDefault);
  48197. this._reset = function () {
  48198. _this.inertialAlphaOffset = 0;
  48199. _this.inertialBetaOffset = 0;
  48200. _this.inertialRadiusOffset = 0;
  48201. _this.inertialPanningX = 0;
  48202. _this.inertialPanningY = 0;
  48203. };
  48204. };
  48205. ArcRotateCamera.prototype.detachControl = function (element) {
  48206. this.inputs.detachElement(element);
  48207. if (this._reset) {
  48208. this._reset();
  48209. }
  48210. };
  48211. ArcRotateCamera.prototype._checkInputs = function () {
  48212. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48213. if (this._collisionTriggered) {
  48214. return;
  48215. }
  48216. this.inputs.checkInputs();
  48217. // Inertia
  48218. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48219. if (this.getScene().useRightHandedSystem) {
  48220. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  48221. }
  48222. else {
  48223. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  48224. }
  48225. this.beta += this.inertialBetaOffset;
  48226. this.radius -= this.inertialRadiusOffset;
  48227. this.inertialAlphaOffset *= this.inertia;
  48228. this.inertialBetaOffset *= this.inertia;
  48229. this.inertialRadiusOffset *= this.inertia;
  48230. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48231. this.inertialAlphaOffset = 0;
  48232. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48233. this.inertialBetaOffset = 0;
  48234. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48235. this.inertialRadiusOffset = 0;
  48236. }
  48237. // Panning inertia
  48238. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48239. if (!this._localDirection) {
  48240. this._localDirection = BABYLON.Vector3.Zero();
  48241. this._transformedDirection = BABYLON.Vector3.Zero();
  48242. }
  48243. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48244. this._localDirection.multiplyInPlace(this.panningAxis);
  48245. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48246. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48247. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48248. if (!this.panningAxis.y) {
  48249. this._transformedDirection.y = 0;
  48250. }
  48251. if (!this._targetHost) {
  48252. if (this.panningDistanceLimit) {
  48253. this._transformedDirection.addInPlace(this._target);
  48254. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48255. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48256. this._target.copyFrom(this._transformedDirection);
  48257. }
  48258. }
  48259. else {
  48260. this._target.addInPlace(this._transformedDirection);
  48261. }
  48262. }
  48263. this.inertialPanningX *= this.panningInertia;
  48264. this.inertialPanningY *= this.panningInertia;
  48265. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48266. this.inertialPanningX = 0;
  48267. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48268. this.inertialPanningY = 0;
  48269. }
  48270. // Limits
  48271. this._checkLimits();
  48272. _super.prototype._checkInputs.call(this);
  48273. };
  48274. ArcRotateCamera.prototype._checkLimits = function () {
  48275. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48276. if (this.allowUpsideDown && this.beta > Math.PI) {
  48277. this.beta = this.beta - (2 * Math.PI);
  48278. }
  48279. }
  48280. else {
  48281. if (this.beta < this.lowerBetaLimit) {
  48282. this.beta = this.lowerBetaLimit;
  48283. }
  48284. }
  48285. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48286. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48287. this.beta = this.beta + (2 * Math.PI);
  48288. }
  48289. }
  48290. else {
  48291. if (this.beta > this.upperBetaLimit) {
  48292. this.beta = this.upperBetaLimit;
  48293. }
  48294. }
  48295. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48296. this.alpha = this.lowerAlphaLimit;
  48297. }
  48298. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48299. this.alpha = this.upperAlphaLimit;
  48300. }
  48301. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48302. this.radius = this.lowerRadiusLimit;
  48303. }
  48304. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48305. this.radius = this.upperRadiusLimit;
  48306. }
  48307. };
  48308. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48309. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48310. this.radius = this._computationVector.length();
  48311. if (this.radius === 0) {
  48312. this.radius = 0.0001; // Just to avoid division by zero
  48313. }
  48314. // Alpha
  48315. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48316. if (this._computationVector.z < 0) {
  48317. this.alpha = 2 * Math.PI - this.alpha;
  48318. }
  48319. // Beta
  48320. this.beta = Math.acos(this._computationVector.y / this.radius);
  48321. this._checkLimits();
  48322. };
  48323. ArcRotateCamera.prototype.setPosition = function (position) {
  48324. if (this.position.equals(position)) {
  48325. return;
  48326. }
  48327. this.position.copyFrom(position);
  48328. this.rebuildAnglesAndRadius();
  48329. };
  48330. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48331. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48332. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48333. if (target.getBoundingInfo) {
  48334. if (toBoundingCenter) {
  48335. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48336. }
  48337. else {
  48338. this._targetBoundingCenter = null;
  48339. }
  48340. this._targetHost = target;
  48341. this._target = this._getTargetPosition();
  48342. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48343. }
  48344. else {
  48345. var newTarget = target;
  48346. var currentTarget = this._getTargetPosition();
  48347. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48348. return;
  48349. }
  48350. this._targetHost = null;
  48351. this._target = newTarget;
  48352. this._targetBoundingCenter = null;
  48353. this.onMeshTargetChangedObservable.notifyObservers(null);
  48354. }
  48355. this.rebuildAnglesAndRadius();
  48356. };
  48357. ArcRotateCamera.prototype._getViewMatrix = function () {
  48358. // Compute
  48359. var cosa = Math.cos(this.alpha);
  48360. var sina = Math.sin(this.alpha);
  48361. var cosb = Math.cos(this.beta);
  48362. var sinb = Math.sin(this.beta);
  48363. if (sinb === 0) {
  48364. sinb = 0.0001;
  48365. }
  48366. var target = this._getTargetPosition();
  48367. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48368. target.addToRef(this._computationVector, this._newPosition);
  48369. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48370. if (!this._collider) {
  48371. this._collider = new BABYLON.Collider();
  48372. }
  48373. this._collider._radius = this.collisionRadius;
  48374. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48375. this._collisionTriggered = true;
  48376. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48377. }
  48378. else {
  48379. this.position.copyFrom(this._newPosition);
  48380. var up = this.upVector;
  48381. if (this.allowUpsideDown && sinb < 0) {
  48382. up = up.clone();
  48383. up = up.negate();
  48384. }
  48385. if (this.getScene().useRightHandedSystem) {
  48386. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  48387. }
  48388. else {
  48389. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  48390. }
  48391. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48392. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48393. }
  48394. this._currentTarget = target;
  48395. return this._viewMatrix;
  48396. };
  48397. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48398. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48399. meshes = meshes || this.getScene().meshes;
  48400. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48401. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48402. this.radius = distance * this.zoomOnFactor;
  48403. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48404. };
  48405. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48406. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48407. var meshesOrMinMaxVector;
  48408. var distance;
  48409. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  48410. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48411. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48412. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48413. }
  48414. else {
  48415. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48416. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48417. distance = minMaxVectorAndDistance.distance;
  48418. }
  48419. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48420. if (!doNotUpdateMaxZ) {
  48421. this.maxZ = distance * 2;
  48422. }
  48423. };
  48424. /**
  48425. * @override
  48426. * Override Camera.createRigCamera
  48427. */
  48428. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48429. var alphaShift = 0;
  48430. switch (this.cameraRigMode) {
  48431. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48432. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48433. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48434. case BABYLON.Camera.RIG_MODE_VR:
  48435. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48436. break;
  48437. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48438. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48439. break;
  48440. }
  48441. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48442. rigCam._cameraRigParams = {};
  48443. return rigCam;
  48444. };
  48445. /**
  48446. * @override
  48447. * Override Camera._updateRigCameras
  48448. */
  48449. ArcRotateCamera.prototype._updateRigCameras = function () {
  48450. var camLeft = this._rigCameras[0];
  48451. var camRight = this._rigCameras[1];
  48452. camLeft.beta = camRight.beta = this.beta;
  48453. camLeft.radius = camRight.radius = this.radius;
  48454. switch (this.cameraRigMode) {
  48455. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48456. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48457. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48458. case BABYLON.Camera.RIG_MODE_VR:
  48459. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48460. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48461. break;
  48462. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48463. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48464. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48465. break;
  48466. }
  48467. _super.prototype._updateRigCameras.call(this);
  48468. };
  48469. ArcRotateCamera.prototype.dispose = function () {
  48470. this.inputs.clear();
  48471. _super.prototype.dispose.call(this);
  48472. };
  48473. ArcRotateCamera.prototype.getClassName = function () {
  48474. return "ArcRotateCamera";
  48475. };
  48476. __decorate([
  48477. BABYLON.serialize()
  48478. ], ArcRotateCamera.prototype, "alpha", void 0);
  48479. __decorate([
  48480. BABYLON.serialize()
  48481. ], ArcRotateCamera.prototype, "beta", void 0);
  48482. __decorate([
  48483. BABYLON.serialize()
  48484. ], ArcRotateCamera.prototype, "radius", void 0);
  48485. __decorate([
  48486. BABYLON.serializeAsVector3("target")
  48487. ], ArcRotateCamera.prototype, "_target", void 0);
  48488. __decorate([
  48489. BABYLON.serialize()
  48490. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48491. __decorate([
  48492. BABYLON.serialize()
  48493. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48494. __decorate([
  48495. BABYLON.serialize()
  48496. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48497. __decorate([
  48498. BABYLON.serialize()
  48499. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48500. __decorate([
  48501. BABYLON.serialize()
  48502. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48503. __decorate([
  48504. BABYLON.serialize()
  48505. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48506. __decorate([
  48507. BABYLON.serialize()
  48508. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48509. __decorate([
  48510. BABYLON.serialize()
  48511. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48512. __decorate([
  48513. BABYLON.serialize()
  48514. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48515. __decorate([
  48516. BABYLON.serialize()
  48517. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48518. __decorate([
  48519. BABYLON.serialize()
  48520. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48521. __decorate([
  48522. BABYLON.serialize()
  48523. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48524. __decorate([
  48525. BABYLON.serialize()
  48526. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48527. __decorate([
  48528. BABYLON.serializeAsVector3()
  48529. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48530. __decorate([
  48531. BABYLON.serialize()
  48532. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48533. __decorate([
  48534. BABYLON.serialize()
  48535. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48536. __decorate([
  48537. BABYLON.serialize()
  48538. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48539. return ArcRotateCamera;
  48540. }(BABYLON.TargetCamera));
  48541. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48542. })(BABYLON || (BABYLON = {}));
  48543. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48544. "use strict";
  48545. var BABYLON;
  48546. (function (BABYLON) {
  48547. /**
  48548. * The HemisphericLight simulates the ambient environment light,
  48549. * so the passed direction is the light reflection direction, not the incoming direction.
  48550. */
  48551. var HemisphericLight = /** @class */ (function (_super) {
  48552. __extends(HemisphericLight, _super);
  48553. /**
  48554. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48555. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48556. * The HemisphericLight can't cast shadows.
  48557. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48558. * @param name The friendly name of the light
  48559. * @param direction The direction of the light reflection
  48560. * @param scene The scene the light belongs to
  48561. */
  48562. function HemisphericLight(name, direction, scene) {
  48563. var _this = _super.call(this, name, scene) || this;
  48564. /**
  48565. * The groundColor is the light in the opposite direction to the one specified during creation.
  48566. * 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.
  48567. */
  48568. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48569. _this.direction = direction || BABYLON.Vector3.Up();
  48570. return _this;
  48571. }
  48572. HemisphericLight.prototype._buildUniformLayout = function () {
  48573. this._uniformBuffer.addUniform("vLightData", 4);
  48574. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48575. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48576. this._uniformBuffer.addUniform("vLightGround", 3);
  48577. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48578. this._uniformBuffer.addUniform("depthValues", 2);
  48579. this._uniformBuffer.create();
  48580. };
  48581. /**
  48582. * Returns the string "HemisphericLight".
  48583. * @return The class name
  48584. */
  48585. HemisphericLight.prototype.getClassName = function () {
  48586. return "HemisphericLight";
  48587. };
  48588. /**
  48589. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48590. * Returns the updated direction.
  48591. * @param target The target the direction should point to
  48592. * @return The computed direction
  48593. */
  48594. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48595. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48596. return this.direction;
  48597. };
  48598. /**
  48599. * Returns the shadow generator associated to the light.
  48600. * @returns Always null for hemispheric lights because it does not support shadows.
  48601. */
  48602. HemisphericLight.prototype.getShadowGenerator = function () {
  48603. return null;
  48604. };
  48605. /**
  48606. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48607. * @param effect The effect to update
  48608. * @param lightIndex The index of the light in the effect to update
  48609. * @returns The hemispheric light
  48610. */
  48611. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48612. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48613. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48614. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48615. return this;
  48616. };
  48617. /**
  48618. * @ignore internal use only.
  48619. */
  48620. HemisphericLight.prototype._getWorldMatrix = function () {
  48621. if (!this._worldMatrix) {
  48622. this._worldMatrix = BABYLON.Matrix.Identity();
  48623. }
  48624. return this._worldMatrix;
  48625. };
  48626. /**
  48627. * Returns the integer 3.
  48628. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48629. */
  48630. HemisphericLight.prototype.getTypeID = function () {
  48631. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48632. };
  48633. __decorate([
  48634. BABYLON.serializeAsColor3()
  48635. ], HemisphericLight.prototype, "groundColor", void 0);
  48636. __decorate([
  48637. BABYLON.serializeAsVector3()
  48638. ], HemisphericLight.prototype, "direction", void 0);
  48639. return HemisphericLight;
  48640. }(BABYLON.Light));
  48641. BABYLON.HemisphericLight = HemisphericLight;
  48642. })(BABYLON || (BABYLON = {}));
  48643. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48644. "use strict";
  48645. var BABYLON;
  48646. (function (BABYLON) {
  48647. /**
  48648. * Base implementation IShadowLight
  48649. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48650. */
  48651. var ShadowLight = /** @class */ (function (_super) {
  48652. __extends(ShadowLight, _super);
  48653. function ShadowLight() {
  48654. var _this = _super !== null && _super.apply(this, arguments) || this;
  48655. _this._needProjectionMatrixCompute = true;
  48656. return _this;
  48657. }
  48658. ShadowLight.prototype._setPosition = function (value) {
  48659. this._position = value;
  48660. };
  48661. Object.defineProperty(ShadowLight.prototype, "position", {
  48662. /**
  48663. * Sets the position the shadow will be casted from. Also use as the light position for both
  48664. * point and spot lights.
  48665. */
  48666. get: function () {
  48667. return this._position;
  48668. },
  48669. /**
  48670. * Sets the position the shadow will be casted from. Also use as the light position for both
  48671. * point and spot lights.
  48672. */
  48673. set: function (value) {
  48674. this._setPosition(value);
  48675. },
  48676. enumerable: true,
  48677. configurable: true
  48678. });
  48679. ShadowLight.prototype._setDirection = function (value) {
  48680. this._direction = value;
  48681. };
  48682. Object.defineProperty(ShadowLight.prototype, "direction", {
  48683. /**
  48684. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48685. * Also use as the light direction on spot and directional lights.
  48686. */
  48687. get: function () {
  48688. return this._direction;
  48689. },
  48690. /**
  48691. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48692. * Also use as the light direction on spot and directional lights.
  48693. */
  48694. set: function (value) {
  48695. this._setDirection(value);
  48696. },
  48697. enumerable: true,
  48698. configurable: true
  48699. });
  48700. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48701. /**
  48702. * Gets the shadow projection clipping minimum z value.
  48703. */
  48704. get: function () {
  48705. return this._shadowMinZ;
  48706. },
  48707. /**
  48708. * Sets the shadow projection clipping minimum z value.
  48709. */
  48710. set: function (value) {
  48711. this._shadowMinZ = value;
  48712. this.forceProjectionMatrixCompute();
  48713. },
  48714. enumerable: true,
  48715. configurable: true
  48716. });
  48717. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48718. /**
  48719. * Sets the shadow projection clipping maximum z value.
  48720. */
  48721. get: function () {
  48722. return this._shadowMaxZ;
  48723. },
  48724. /**
  48725. * Gets the shadow projection clipping maximum z value.
  48726. */
  48727. set: function (value) {
  48728. this._shadowMaxZ = value;
  48729. this.forceProjectionMatrixCompute();
  48730. },
  48731. enumerable: true,
  48732. configurable: true
  48733. });
  48734. /**
  48735. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48736. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48737. */
  48738. ShadowLight.prototype.computeTransformedInformation = function () {
  48739. if (this.parent && this.parent.getWorldMatrix) {
  48740. if (!this.transformedPosition) {
  48741. this.transformedPosition = BABYLON.Vector3.Zero();
  48742. }
  48743. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48744. // In case the direction is present.
  48745. if (this.direction) {
  48746. if (!this.transformedDirection) {
  48747. this.transformedDirection = BABYLON.Vector3.Zero();
  48748. }
  48749. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48750. }
  48751. return true;
  48752. }
  48753. return false;
  48754. };
  48755. /**
  48756. * Return the depth scale used for the shadow map.
  48757. * @returns the depth scale.
  48758. */
  48759. ShadowLight.prototype.getDepthScale = function () {
  48760. return 50.0;
  48761. };
  48762. /**
  48763. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48764. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48765. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48766. */
  48767. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48768. return this.transformedDirection ? this.transformedDirection : this.direction;
  48769. };
  48770. /**
  48771. * Returns the ShadowLight absolute position in the World.
  48772. * @returns the position vector in world space
  48773. */
  48774. ShadowLight.prototype.getAbsolutePosition = function () {
  48775. return this.transformedPosition ? this.transformedPosition : this.position;
  48776. };
  48777. /**
  48778. * Sets the ShadowLight direction toward the passed target.
  48779. * @param target The point tot target in local space
  48780. * @returns the updated ShadowLight direction
  48781. */
  48782. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48783. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48784. return this.direction;
  48785. };
  48786. /**
  48787. * Returns the light rotation in euler definition.
  48788. * @returns the x y z rotation in local space.
  48789. */
  48790. ShadowLight.prototype.getRotation = function () {
  48791. this.direction.normalize();
  48792. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48793. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48794. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48795. };
  48796. /**
  48797. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48798. * @returns true if a cube texture needs to be use
  48799. */
  48800. ShadowLight.prototype.needCube = function () {
  48801. return false;
  48802. };
  48803. /**
  48804. * Detects if the projection matrix requires to be recomputed this frame.
  48805. * @returns true if it requires to be recomputed otherwise, false.
  48806. */
  48807. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48808. return this._needProjectionMatrixCompute;
  48809. };
  48810. /**
  48811. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48812. */
  48813. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48814. this._needProjectionMatrixCompute = true;
  48815. };
  48816. /**
  48817. * Get the world matrix of the sahdow lights.
  48818. * @ignore Internal Use Only
  48819. */
  48820. ShadowLight.prototype._getWorldMatrix = function () {
  48821. if (!this._worldMatrix) {
  48822. this._worldMatrix = BABYLON.Matrix.Identity();
  48823. }
  48824. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48825. return this._worldMatrix;
  48826. };
  48827. /**
  48828. * Gets the minZ used for shadow according to both the scene and the light.
  48829. * @param activeCamera The camera we are returning the min for
  48830. * @returns the depth min z
  48831. */
  48832. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48833. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48834. };
  48835. /**
  48836. * Gets the maxZ used for shadow according to both the scene and the light.
  48837. * @param activeCamera The camera we are returning the max for
  48838. * @returns the depth max z
  48839. */
  48840. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48841. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48842. };
  48843. /**
  48844. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48845. * @param matrix The materix to updated with the projection information
  48846. * @param viewMatrix The transform matrix of the light
  48847. * @param renderList The list of mesh to render in the map
  48848. * @returns The current light
  48849. */
  48850. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48851. if (this.customProjectionMatrixBuilder) {
  48852. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48853. }
  48854. else {
  48855. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48856. }
  48857. return this;
  48858. };
  48859. __decorate([
  48860. BABYLON.serializeAsVector3()
  48861. ], ShadowLight.prototype, "position", null);
  48862. __decorate([
  48863. BABYLON.serializeAsVector3()
  48864. ], ShadowLight.prototype, "direction", null);
  48865. __decorate([
  48866. BABYLON.serialize()
  48867. ], ShadowLight.prototype, "shadowMinZ", null);
  48868. __decorate([
  48869. BABYLON.serialize()
  48870. ], ShadowLight.prototype, "shadowMaxZ", null);
  48871. return ShadowLight;
  48872. }(BABYLON.Light));
  48873. BABYLON.ShadowLight = ShadowLight;
  48874. })(BABYLON || (BABYLON = {}));
  48875. //# sourceMappingURL=babylon.shadowLight.js.map
  48876. "use strict";
  48877. var BABYLON;
  48878. (function (BABYLON) {
  48879. /**
  48880. * A point light is a light defined by an unique point in world space.
  48881. * The light is emitted in every direction from this point.
  48882. * A good example of a point light is a standard light bulb.
  48883. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48884. */
  48885. var PointLight = /** @class */ (function (_super) {
  48886. __extends(PointLight, _super);
  48887. /**
  48888. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48889. * A PointLight emits the light in every direction.
  48890. * It can cast shadows.
  48891. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48892. * ```javascript
  48893. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48894. * ```
  48895. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48896. * @param name The light friendly name
  48897. * @param position The position of the point light in the scene
  48898. * @param scene The scene the lights belongs to
  48899. */
  48900. function PointLight(name, position, scene) {
  48901. var _this = _super.call(this, name, scene) || this;
  48902. _this._shadowAngle = Math.PI / 2;
  48903. _this.position = position;
  48904. return _this;
  48905. }
  48906. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48907. /**
  48908. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48909. * This specifies what angle the shadow will use to be created.
  48910. *
  48911. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48912. */
  48913. get: function () {
  48914. return this._shadowAngle;
  48915. },
  48916. /**
  48917. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48918. * This specifies what angle the shadow will use to be created.
  48919. *
  48920. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48921. */
  48922. set: function (value) {
  48923. this._shadowAngle = value;
  48924. this.forceProjectionMatrixCompute();
  48925. },
  48926. enumerable: true,
  48927. configurable: true
  48928. });
  48929. Object.defineProperty(PointLight.prototype, "direction", {
  48930. /**
  48931. * Gets the direction if it has been set.
  48932. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48933. */
  48934. get: function () {
  48935. return this._direction;
  48936. },
  48937. /**
  48938. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48939. */
  48940. set: function (value) {
  48941. var previousNeedCube = this.needCube();
  48942. this._direction = value;
  48943. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48944. this._shadowGenerator.recreateShadowMap();
  48945. }
  48946. },
  48947. enumerable: true,
  48948. configurable: true
  48949. });
  48950. /**
  48951. * Returns the string "PointLight"
  48952. * @returns the class name
  48953. */
  48954. PointLight.prototype.getClassName = function () {
  48955. return "PointLight";
  48956. };
  48957. /**
  48958. * Returns the integer 0.
  48959. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48960. */
  48961. PointLight.prototype.getTypeID = function () {
  48962. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48963. };
  48964. /**
  48965. * Specifies wether or not the shadowmap should be a cube texture.
  48966. * @returns true if the shadowmap needs to be a cube texture.
  48967. */
  48968. PointLight.prototype.needCube = function () {
  48969. return !this.direction;
  48970. };
  48971. /**
  48972. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48973. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48974. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48975. */
  48976. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48977. if (this.direction) {
  48978. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48979. }
  48980. else {
  48981. switch (faceIndex) {
  48982. case 0:
  48983. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48984. case 1:
  48985. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48986. case 2:
  48987. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48988. case 3:
  48989. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48990. case 4:
  48991. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48992. case 5:
  48993. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48994. }
  48995. }
  48996. return BABYLON.Vector3.Zero();
  48997. };
  48998. /**
  48999. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49000. * - fov = PI / 2
  49001. * - aspect ratio : 1.0
  49002. * - z-near and far equal to the active camera minZ and maxZ.
  49003. * Returns the PointLight.
  49004. */
  49005. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49006. var activeCamera = this.getScene().activeCamera;
  49007. if (!activeCamera) {
  49008. return;
  49009. }
  49010. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49011. };
  49012. PointLight.prototype._buildUniformLayout = function () {
  49013. this._uniformBuffer.addUniform("vLightData", 4);
  49014. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49015. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49016. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49017. this._uniformBuffer.addUniform("depthValues", 2);
  49018. this._uniformBuffer.create();
  49019. };
  49020. /**
  49021. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49022. * @param effect The effect to update
  49023. * @param lightIndex The index of the light in the effect to update
  49024. * @returns The point light
  49025. */
  49026. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49027. if (this.computeTransformedInformation()) {
  49028. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49029. return this;
  49030. }
  49031. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49032. return this;
  49033. };
  49034. __decorate([
  49035. BABYLON.serialize()
  49036. ], PointLight.prototype, "shadowAngle", null);
  49037. return PointLight;
  49038. }(BABYLON.ShadowLight));
  49039. BABYLON.PointLight = PointLight;
  49040. })(BABYLON || (BABYLON = {}));
  49041. //# sourceMappingURL=babylon.pointLight.js.map
  49042. "use strict";
  49043. var BABYLON;
  49044. (function (BABYLON) {
  49045. /**
  49046. * A directional light is defined by a direction (what a surprise!).
  49047. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49048. * 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.
  49049. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49050. */
  49051. var DirectionalLight = /** @class */ (function (_super) {
  49052. __extends(DirectionalLight, _super);
  49053. /**
  49054. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49055. * The directional light is emitted from everywhere in the given direction.
  49056. * It can cast shawdows.
  49057. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49058. * @param name The friendly name of the light
  49059. * @param direction The direction of the light
  49060. * @param scene The scene the light belongs to
  49061. */
  49062. function DirectionalLight(name, direction, scene) {
  49063. var _this = _super.call(this, name, scene) || this;
  49064. _this._shadowFrustumSize = 0;
  49065. _this._shadowOrthoScale = 0.1;
  49066. /**
  49067. * Automatically compute the projection matrix to best fit (including all the casters)
  49068. * on each frame.
  49069. */
  49070. _this.autoUpdateExtends = true;
  49071. // Cache
  49072. _this._orthoLeft = Number.MAX_VALUE;
  49073. _this._orthoRight = Number.MIN_VALUE;
  49074. _this._orthoTop = Number.MIN_VALUE;
  49075. _this._orthoBottom = Number.MAX_VALUE;
  49076. _this.position = direction.scale(-1.0);
  49077. _this.direction = direction;
  49078. return _this;
  49079. }
  49080. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49081. /**
  49082. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49083. */
  49084. get: function () {
  49085. return this._shadowFrustumSize;
  49086. },
  49087. /**
  49088. * Specifies a fix frustum size for the shadow generation.
  49089. */
  49090. set: function (value) {
  49091. this._shadowFrustumSize = value;
  49092. this.forceProjectionMatrixCompute();
  49093. },
  49094. enumerable: true,
  49095. configurable: true
  49096. });
  49097. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49098. /**
  49099. * Gets the shadow projection scale against the optimal computed one.
  49100. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49101. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49102. */
  49103. get: function () {
  49104. return this._shadowOrthoScale;
  49105. },
  49106. /**
  49107. * Sets the shadow projection scale against the optimal computed one.
  49108. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49109. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49110. */
  49111. set: function (value) {
  49112. this._shadowOrthoScale = value;
  49113. this.forceProjectionMatrixCompute();
  49114. },
  49115. enumerable: true,
  49116. configurable: true
  49117. });
  49118. /**
  49119. * Returns the string "DirectionalLight".
  49120. * @return The class name
  49121. */
  49122. DirectionalLight.prototype.getClassName = function () {
  49123. return "DirectionalLight";
  49124. };
  49125. /**
  49126. * Returns the integer 1.
  49127. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49128. */
  49129. DirectionalLight.prototype.getTypeID = function () {
  49130. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49131. };
  49132. /**
  49133. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49134. * Returns the DirectionalLight Shadow projection matrix.
  49135. */
  49136. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49137. if (this.shadowFrustumSize > 0) {
  49138. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49139. }
  49140. else {
  49141. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49142. }
  49143. };
  49144. /**
  49145. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49146. * Returns the DirectionalLight Shadow projection matrix.
  49147. */
  49148. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49149. var activeCamera = this.getScene().activeCamera;
  49150. if (!activeCamera) {
  49151. return;
  49152. }
  49153. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49154. };
  49155. /**
  49156. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49157. * Returns the DirectionalLight Shadow projection matrix.
  49158. */
  49159. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49160. var activeCamera = this.getScene().activeCamera;
  49161. if (!activeCamera) {
  49162. return;
  49163. }
  49164. // Check extends
  49165. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49166. var tempVector3 = BABYLON.Vector3.Zero();
  49167. this._orthoLeft = Number.MAX_VALUE;
  49168. this._orthoRight = Number.MIN_VALUE;
  49169. this._orthoTop = Number.MIN_VALUE;
  49170. this._orthoBottom = Number.MAX_VALUE;
  49171. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49172. var mesh = renderList[meshIndex];
  49173. if (!mesh) {
  49174. continue;
  49175. }
  49176. var boundingInfo = mesh.getBoundingInfo();
  49177. var boundingBox = boundingInfo.boundingBox;
  49178. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49179. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49180. if (tempVector3.x < this._orthoLeft)
  49181. this._orthoLeft = tempVector3.x;
  49182. if (tempVector3.y < this._orthoBottom)
  49183. this._orthoBottom = tempVector3.y;
  49184. if (tempVector3.x > this._orthoRight)
  49185. this._orthoRight = tempVector3.x;
  49186. if (tempVector3.y > this._orthoTop)
  49187. this._orthoTop = tempVector3.y;
  49188. }
  49189. }
  49190. }
  49191. var xOffset = this._orthoRight - this._orthoLeft;
  49192. var yOffset = this._orthoTop - this._orthoBottom;
  49193. 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);
  49194. };
  49195. DirectionalLight.prototype._buildUniformLayout = function () {
  49196. this._uniformBuffer.addUniform("vLightData", 4);
  49197. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49198. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49199. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49200. this._uniformBuffer.addUniform("depthValues", 2);
  49201. this._uniformBuffer.create();
  49202. };
  49203. /**
  49204. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49205. * @param effect The effect to update
  49206. * @param lightIndex The index of the light in the effect to update
  49207. * @returns The directional light
  49208. */
  49209. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49210. if (this.computeTransformedInformation()) {
  49211. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49212. return this;
  49213. }
  49214. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49215. return this;
  49216. };
  49217. /**
  49218. * Gets the minZ used for shadow according to both the scene and the light.
  49219. *
  49220. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49221. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49222. * @param activeCamera The camera we are returning the min for
  49223. * @returns the depth min z
  49224. */
  49225. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49226. return 1;
  49227. };
  49228. /**
  49229. * Gets the maxZ used for shadow according to both the scene and the light.
  49230. *
  49231. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49232. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49233. * @param activeCamera The camera we are returning the max for
  49234. * @returns the depth max z
  49235. */
  49236. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49237. return 1;
  49238. };
  49239. __decorate([
  49240. BABYLON.serialize()
  49241. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49242. __decorate([
  49243. BABYLON.serialize()
  49244. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49245. __decorate([
  49246. BABYLON.serialize()
  49247. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49248. return DirectionalLight;
  49249. }(BABYLON.ShadowLight));
  49250. BABYLON.DirectionalLight = DirectionalLight;
  49251. })(BABYLON || (BABYLON = {}));
  49252. //# sourceMappingURL=babylon.directionalLight.js.map
  49253. "use strict";
  49254. var BABYLON;
  49255. (function (BABYLON) {
  49256. /**
  49257. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49258. * These values define a cone of light starting from the position, emitting toward the direction.
  49259. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49260. * and the exponent defines the speed of the decay of the light with distance (reach).
  49261. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49262. */
  49263. var SpotLight = /** @class */ (function (_super) {
  49264. __extends(SpotLight, _super);
  49265. /**
  49266. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49267. * It can cast shadows.
  49268. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49269. * @param name The light friendly name
  49270. * @param position The position of the spot light in the scene
  49271. * @param direction The direction of the light in the scene
  49272. * @param angle The cone angle of the light in Radians
  49273. * @param exponent The light decay speed with the distance from the emission spot
  49274. * @param scene The scene the lights belongs to
  49275. */
  49276. function SpotLight(name, position, direction, angle, exponent, scene) {
  49277. var _this = _super.call(this, name, scene) || this;
  49278. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49279. _this._projectionTextureLightNear = 1e-6;
  49280. _this._projectionTextureLightFar = 1000.0;
  49281. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49282. _this._projectionTextureViewLightDirty = true;
  49283. _this._projectionTextureProjectionLightDirty = true;
  49284. _this._projectionTextureDirty = true;
  49285. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49286. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49287. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49288. _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);
  49289. _this.position = position;
  49290. _this.direction = direction;
  49291. _this.angle = angle;
  49292. _this.exponent = exponent;
  49293. return _this;
  49294. }
  49295. Object.defineProperty(SpotLight.prototype, "angle", {
  49296. /**
  49297. * Gets the cone angle of the spot light in Radians.
  49298. */
  49299. get: function () {
  49300. return this._angle;
  49301. },
  49302. /**
  49303. * Sets the cone angle of the spot light in Radians.
  49304. */
  49305. set: function (value) {
  49306. this._angle = value;
  49307. this._projectionTextureProjectionLightDirty = true;
  49308. this.forceProjectionMatrixCompute();
  49309. },
  49310. enumerable: true,
  49311. configurable: true
  49312. });
  49313. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49314. /**
  49315. * Allows scaling the angle of the light for shadow generation only.
  49316. */
  49317. get: function () {
  49318. return this._shadowAngleScale;
  49319. },
  49320. /**
  49321. * Allows scaling the angle of the light for shadow generation only.
  49322. */
  49323. set: function (value) {
  49324. this._shadowAngleScale = value;
  49325. this.forceProjectionMatrixCompute();
  49326. },
  49327. enumerable: true,
  49328. configurable: true
  49329. });
  49330. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49331. /**
  49332. * Allows reading the projecton texture
  49333. */
  49334. get: function () {
  49335. return this._projectionTextureMatrix;
  49336. },
  49337. enumerable: true,
  49338. configurable: true
  49339. });
  49340. ;
  49341. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49342. /**
  49343. * Gets the near clip of the Spotlight for texture projection.
  49344. */
  49345. get: function () {
  49346. return this._projectionTextureLightNear;
  49347. },
  49348. /**
  49349. * Sets the near clip of the Spotlight for texture projection.
  49350. */
  49351. set: function (value) {
  49352. this._projectionTextureLightNear = value;
  49353. this._projectionTextureProjectionLightDirty = true;
  49354. },
  49355. enumerable: true,
  49356. configurable: true
  49357. });
  49358. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49359. /**
  49360. * Gets the far clip of the Spotlight for texture projection.
  49361. */
  49362. get: function () {
  49363. return this._projectionTextureLightFar;
  49364. },
  49365. /**
  49366. * Sets the far clip of the Spotlight for texture projection.
  49367. */
  49368. set: function (value) {
  49369. this._projectionTextureLightFar = value;
  49370. this._projectionTextureProjectionLightDirty = true;
  49371. },
  49372. enumerable: true,
  49373. configurable: true
  49374. });
  49375. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49376. /**
  49377. * Gets the Up vector of the Spotlight for texture projection.
  49378. */
  49379. get: function () {
  49380. return this._projectionTextureUpDirection;
  49381. },
  49382. /**
  49383. * Sets the Up vector of the Spotlight for texture projection.
  49384. */
  49385. set: function (value) {
  49386. this._projectionTextureUpDirection = value;
  49387. this._projectionTextureProjectionLightDirty = true;
  49388. },
  49389. enumerable: true,
  49390. configurable: true
  49391. });
  49392. ;
  49393. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49394. /**
  49395. * Gets the projection texture of the light.
  49396. */
  49397. get: function () {
  49398. return this._projectionTexture;
  49399. },
  49400. /**
  49401. * Sets the projection texture of the light.
  49402. */
  49403. set: function (value) {
  49404. this._projectionTexture = value;
  49405. this._projectionTextureDirty = true;
  49406. },
  49407. enumerable: true,
  49408. configurable: true
  49409. });
  49410. /**
  49411. * Returns the string "SpotLight".
  49412. * @returns the class name
  49413. */
  49414. SpotLight.prototype.getClassName = function () {
  49415. return "SpotLight";
  49416. };
  49417. /**
  49418. * Returns the integer 2.
  49419. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49420. */
  49421. SpotLight.prototype.getTypeID = function () {
  49422. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49423. };
  49424. /**
  49425. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49426. */
  49427. SpotLight.prototype._setDirection = function (value) {
  49428. _super.prototype._setDirection.call(this, value);
  49429. this._projectionTextureViewLightDirty = true;
  49430. };
  49431. /**
  49432. * Overrides the position setter to recompute the projection texture view light Matrix.
  49433. */
  49434. SpotLight.prototype._setPosition = function (value) {
  49435. _super.prototype._setPosition.call(this, value);
  49436. this._projectionTextureViewLightDirty = true;
  49437. };
  49438. /**
  49439. * 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.
  49440. * Returns the SpotLight.
  49441. */
  49442. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49443. var activeCamera = this.getScene().activeCamera;
  49444. if (!activeCamera) {
  49445. return;
  49446. }
  49447. this._shadowAngleScale = this._shadowAngleScale || 1;
  49448. var angle = this._shadowAngleScale * this._angle;
  49449. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49450. };
  49451. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49452. this._projectionTextureViewLightDirty = false;
  49453. this._projectionTextureDirty = true;
  49454. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49455. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49456. };
  49457. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49458. this._projectionTextureProjectionLightDirty = false;
  49459. this._projectionTextureDirty = true;
  49460. var light_far = this.projectionTextureLightFar;
  49461. var light_near = this.projectionTextureLightNear;
  49462. var P = light_far / (light_far - light_near);
  49463. var Q = -P * light_near;
  49464. var S = 1.0 / Math.tan(this._angle / 2.0);
  49465. var A = 1.0;
  49466. 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);
  49467. };
  49468. /**
  49469. * Main function for light texture projection matrix computing.
  49470. */
  49471. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49472. this._projectionTextureDirty = false;
  49473. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49474. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49475. };
  49476. SpotLight.prototype._buildUniformLayout = function () {
  49477. this._uniformBuffer.addUniform("vLightData", 4);
  49478. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49479. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49480. this._uniformBuffer.addUniform("vLightDirection", 3);
  49481. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49482. this._uniformBuffer.addUniform("depthValues", 2);
  49483. this._uniformBuffer.create();
  49484. };
  49485. /**
  49486. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49487. * @param effect The effect to update
  49488. * @param lightIndex The index of the light in the effect to update
  49489. * @returns The spot light
  49490. */
  49491. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49492. var normalizeDirection;
  49493. if (this.computeTransformedInformation()) {
  49494. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49495. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49496. }
  49497. else {
  49498. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49499. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49500. }
  49501. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49502. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49503. if (this._projectionTextureViewLightDirty) {
  49504. this._computeProjectionTextureViewLightMatrix();
  49505. }
  49506. if (this._projectionTextureProjectionLightDirty) {
  49507. this._computeProjectionTextureProjectionLightMatrix();
  49508. }
  49509. if (this._projectionTextureDirty) {
  49510. this._computeProjectionTextureMatrix();
  49511. }
  49512. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49513. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49514. }
  49515. return this;
  49516. };
  49517. /**
  49518. * Disposes the light and the associated resources.
  49519. */
  49520. SpotLight.prototype.dispose = function () {
  49521. _super.prototype.dispose.call(this);
  49522. if (this._projectionTexture) {
  49523. this._projectionTexture.dispose();
  49524. }
  49525. };
  49526. __decorate([
  49527. BABYLON.serialize()
  49528. ], SpotLight.prototype, "angle", null);
  49529. __decorate([
  49530. BABYLON.serialize()
  49531. ], SpotLight.prototype, "shadowAngleScale", null);
  49532. __decorate([
  49533. BABYLON.serialize()
  49534. ], SpotLight.prototype, "exponent", void 0);
  49535. __decorate([
  49536. BABYLON.serialize()
  49537. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49538. __decorate([
  49539. BABYLON.serialize()
  49540. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49541. __decorate([
  49542. BABYLON.serialize()
  49543. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49544. __decorate([
  49545. BABYLON.serializeAsTexture("projectedLightTexture")
  49546. ], SpotLight.prototype, "_projectionTexture", void 0);
  49547. return SpotLight;
  49548. }(BABYLON.ShadowLight));
  49549. BABYLON.SpotLight = SpotLight;
  49550. })(BABYLON || (BABYLON = {}));
  49551. //# sourceMappingURL=babylon.spotLight.js.map
  49552. "use strict";
  49553. var BABYLON;
  49554. (function (BABYLON) {
  49555. /**
  49556. * Class used to override all child animations of a given target
  49557. */
  49558. var AnimationPropertiesOverride = /** @class */ (function () {
  49559. function AnimationPropertiesOverride() {
  49560. /**
  49561. * Gets or sets a value indicating if animation blending must be used
  49562. */
  49563. this.enableBlending = false;
  49564. /**
  49565. * Gets or sets the blending speed to use when enableBlending is true
  49566. */
  49567. this.blendingSpeed = 0.01;
  49568. /**
  49569. * Gets or sets the default loop mode to use
  49570. */
  49571. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49572. }
  49573. return AnimationPropertiesOverride;
  49574. }());
  49575. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49576. })(BABYLON || (BABYLON = {}));
  49577. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49578. "use strict";
  49579. var BABYLON;
  49580. (function (BABYLON) {
  49581. var AnimationRange = /** @class */ (function () {
  49582. function AnimationRange(name, from, to) {
  49583. this.name = name;
  49584. this.from = from;
  49585. this.to = to;
  49586. }
  49587. AnimationRange.prototype.clone = function () {
  49588. return new AnimationRange(this.name, this.from, this.to);
  49589. };
  49590. return AnimationRange;
  49591. }());
  49592. BABYLON.AnimationRange = AnimationRange;
  49593. /**
  49594. * Composed of a frame, and an action function
  49595. */
  49596. var AnimationEvent = /** @class */ (function () {
  49597. function AnimationEvent(frame, action, onlyOnce) {
  49598. this.frame = frame;
  49599. this.action = action;
  49600. this.onlyOnce = onlyOnce;
  49601. this.isDone = false;
  49602. }
  49603. return AnimationEvent;
  49604. }());
  49605. BABYLON.AnimationEvent = AnimationEvent;
  49606. var PathCursor = /** @class */ (function () {
  49607. function PathCursor(path) {
  49608. this.path = path;
  49609. this._onchange = new Array();
  49610. this.value = 0;
  49611. this.animations = new Array();
  49612. }
  49613. PathCursor.prototype.getPoint = function () {
  49614. var point = this.path.getPointAtLengthPosition(this.value);
  49615. return new BABYLON.Vector3(point.x, 0, point.y);
  49616. };
  49617. PathCursor.prototype.moveAhead = function (step) {
  49618. if (step === void 0) { step = 0.002; }
  49619. this.move(step);
  49620. return this;
  49621. };
  49622. PathCursor.prototype.moveBack = function (step) {
  49623. if (step === void 0) { step = 0.002; }
  49624. this.move(-step);
  49625. return this;
  49626. };
  49627. PathCursor.prototype.move = function (step) {
  49628. if (Math.abs(step) > 1) {
  49629. throw "step size should be less than 1.";
  49630. }
  49631. this.value += step;
  49632. this.ensureLimits();
  49633. this.raiseOnChange();
  49634. return this;
  49635. };
  49636. PathCursor.prototype.ensureLimits = function () {
  49637. while (this.value > 1) {
  49638. this.value -= 1;
  49639. }
  49640. while (this.value < 0) {
  49641. this.value += 1;
  49642. }
  49643. return this;
  49644. };
  49645. // used by animation engine
  49646. PathCursor.prototype.raiseOnChange = function () {
  49647. var _this = this;
  49648. this._onchange.forEach(function (f) { return f(_this); });
  49649. return this;
  49650. };
  49651. PathCursor.prototype.onchange = function (f) {
  49652. this._onchange.push(f);
  49653. return this;
  49654. };
  49655. return PathCursor;
  49656. }());
  49657. BABYLON.PathCursor = PathCursor;
  49658. var AnimationKeyInterpolation;
  49659. (function (AnimationKeyInterpolation) {
  49660. /**
  49661. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  49662. */
  49663. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49664. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49665. /**
  49666. * Class used to store any kind of animation
  49667. */
  49668. var Animation = /** @class */ (function () {
  49669. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  49670. this.name = name;
  49671. this.targetProperty = targetProperty;
  49672. this.framePerSecond = framePerSecond;
  49673. this.dataType = dataType;
  49674. this.loopMode = loopMode;
  49675. this.enableBlending = enableBlending;
  49676. this._runtimeAnimations = new Array();
  49677. // The set of event that will be linked to this animation
  49678. this._events = new Array();
  49679. this.blendingSpeed = 0.01;
  49680. this._ranges = {};
  49681. this.targetPropertyPath = targetProperty.split(".");
  49682. this.dataType = dataType;
  49683. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49684. }
  49685. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49686. var dataType = undefined;
  49687. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49688. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49689. }
  49690. else if (from instanceof BABYLON.Quaternion) {
  49691. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49692. }
  49693. else if (from instanceof BABYLON.Vector3) {
  49694. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49695. }
  49696. else if (from instanceof BABYLON.Vector2) {
  49697. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49698. }
  49699. else if (from instanceof BABYLON.Color3) {
  49700. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49701. }
  49702. else if (from instanceof BABYLON.Size) {
  49703. dataType = Animation.ANIMATIONTYPE_SIZE;
  49704. }
  49705. if (dataType == undefined) {
  49706. return null;
  49707. }
  49708. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49709. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49710. animation.setKeys(keys);
  49711. if (easingFunction !== undefined) {
  49712. animation.setEasingFunction(easingFunction);
  49713. }
  49714. return animation;
  49715. };
  49716. /**
  49717. * Sets up an animation.
  49718. * @param property the property to animate
  49719. * @param animationType the animation type to apply
  49720. * @param easingFunction the easing function used in the animation
  49721. * @returns The created animation
  49722. */
  49723. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49724. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49725. animation.setEasingFunction(easingFunction);
  49726. return animation;
  49727. };
  49728. /**
  49729. * Create and start an animation on a node
  49730. * @param {string} name defines the name of the global animation that will be run on all nodes
  49731. * @param {BABYLON.Node} node defines the root node where the animation will take place
  49732. * @param {string} targetProperty defines property to animate
  49733. * @param {number} framePerSecond defines the number of frame per second yo use
  49734. * @param {number} totalFrame defines the number of frames in total
  49735. * @param {any} from defines the initial value
  49736. * @param {any} to defines the final value
  49737. * @param {number} loopMode defines which loop mode you want to use (off by default)
  49738. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  49739. * @param onAnimationEnd defines the callback to call when animation end
  49740. * @returns the animatable created for this animation
  49741. */
  49742. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49743. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49744. if (!animation) {
  49745. return null;
  49746. }
  49747. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49748. };
  49749. /**
  49750. * Create and start an animation on a node and its descendants
  49751. * @param {string} name defines the name of the global animation that will be run on all nodes
  49752. * @param {BABYLON.Node} node defines the root node where the animation will take place
  49753. * @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.
  49754. * @param {string} targetProperty defines property to animate
  49755. * @param {number} framePerSecond defines the number of frame per second yo use
  49756. * @param {number} totalFrame defines the number of frames in total
  49757. * @param {any} from defines the initial value
  49758. * @param {any} to defines the final value
  49759. * @param {number} loopMode defines which loop mode you want to use (off by default)
  49760. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  49761. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49762. * @returns the list of animatables created for all nodes
  49763. * @example https://www.babylonjs-playground.com/#MH0VLI
  49764. */
  49765. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49766. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49767. if (!animation) {
  49768. return null;
  49769. }
  49770. var scene = node.getScene();
  49771. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49772. };
  49773. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49774. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49775. if (!animation) {
  49776. return null;
  49777. }
  49778. node.animations.push(animation);
  49779. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49780. };
  49781. /**
  49782. * Transition property of the Camera to the target Value.
  49783. * @param property The property to transition
  49784. * @param targetValue The target Value of the property
  49785. * @param host The object where the property to animate belongs
  49786. * @param scene Scene used to run the animation
  49787. * @param frameRate Framerate (in frame/s) to use
  49788. * @param transition The transition type we want to use
  49789. * @param duration The duration of the animation, in milliseconds
  49790. * @param onAnimationEnd Call back trigger at the end of the animation.
  49791. */
  49792. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49793. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49794. if (duration <= 0) {
  49795. host[property] = targetValue;
  49796. if (onAnimationEnd) {
  49797. onAnimationEnd();
  49798. }
  49799. return null;
  49800. }
  49801. var endFrame = frameRate * (duration / 1000);
  49802. transition.setKeys([{
  49803. frame: 0,
  49804. value: host[property].clone ? host[property].clone() : host[property]
  49805. },
  49806. {
  49807. frame: endFrame,
  49808. value: targetValue
  49809. }]);
  49810. if (!host.animations) {
  49811. host.animations = [];
  49812. }
  49813. host.animations.push(transition);
  49814. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49815. animation.onAnimationEnd = onAnimationEnd;
  49816. return animation;
  49817. };
  49818. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49819. /**
  49820. * Return the array of runtime animations currently using this animation
  49821. */
  49822. get: function () {
  49823. return this._runtimeAnimations;
  49824. },
  49825. enumerable: true,
  49826. configurable: true
  49827. });
  49828. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49829. get: function () {
  49830. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49831. var runtimeAnimation = _a[_i];
  49832. if (!runtimeAnimation.isStopped) {
  49833. return true;
  49834. }
  49835. }
  49836. return false;
  49837. },
  49838. enumerable: true,
  49839. configurable: true
  49840. });
  49841. // Methods
  49842. /**
  49843. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  49844. */
  49845. Animation.prototype.toString = function (fullDetails) {
  49846. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49847. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49848. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49849. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49850. if (fullDetails) {
  49851. ret += ", Ranges: {";
  49852. var first = true;
  49853. for (var name in this._ranges) {
  49854. if (first) {
  49855. ret += ", ";
  49856. first = false;
  49857. }
  49858. ret += name;
  49859. }
  49860. ret += "}";
  49861. }
  49862. return ret;
  49863. };
  49864. /**
  49865. * Add an event to this animation.
  49866. */
  49867. Animation.prototype.addEvent = function (event) {
  49868. this._events.push(event);
  49869. };
  49870. /**
  49871. * Remove all events found at the given frame
  49872. * @param frame
  49873. */
  49874. Animation.prototype.removeEvents = function (frame) {
  49875. for (var index = 0; index < this._events.length; index++) {
  49876. if (this._events[index].frame === frame) {
  49877. this._events.splice(index, 1);
  49878. index--;
  49879. }
  49880. }
  49881. };
  49882. Animation.prototype.getEvents = function () {
  49883. return this._events;
  49884. };
  49885. Animation.prototype.createRange = function (name, from, to) {
  49886. // check name not already in use; could happen for bones after serialized
  49887. if (!this._ranges[name]) {
  49888. this._ranges[name] = new AnimationRange(name, from, to);
  49889. }
  49890. };
  49891. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49892. if (deleteFrames === void 0) { deleteFrames = true; }
  49893. var range = this._ranges[name];
  49894. if (!range) {
  49895. return;
  49896. }
  49897. if (deleteFrames) {
  49898. var from = range.from;
  49899. var to = range.to;
  49900. // this loop MUST go high to low for multiple splices to work
  49901. for (var key = this._keys.length - 1; key >= 0; key--) {
  49902. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49903. this._keys.splice(key, 1);
  49904. }
  49905. }
  49906. }
  49907. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49908. };
  49909. Animation.prototype.getRange = function (name) {
  49910. return this._ranges[name];
  49911. };
  49912. Animation.prototype.getKeys = function () {
  49913. return this._keys;
  49914. };
  49915. Animation.prototype.getHighestFrame = function () {
  49916. var ret = 0;
  49917. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49918. if (ret < this._keys[key].frame) {
  49919. ret = this._keys[key].frame;
  49920. }
  49921. }
  49922. return ret;
  49923. };
  49924. Animation.prototype.getEasingFunction = function () {
  49925. return this._easingFunction;
  49926. };
  49927. Animation.prototype.setEasingFunction = function (easingFunction) {
  49928. this._easingFunction = easingFunction;
  49929. };
  49930. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49931. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49932. };
  49933. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49934. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49935. };
  49936. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49937. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49938. };
  49939. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49940. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49941. };
  49942. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49943. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49944. };
  49945. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49946. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49947. };
  49948. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49949. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49950. };
  49951. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49952. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49953. };
  49954. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49955. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49956. };
  49957. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49958. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49959. };
  49960. /**
  49961. * Defines the function to use to interpolate matrices
  49962. * @param startValue defines the start matrix
  49963. * @param endValue defines the end matrix
  49964. * @param gradient defines the gradient between both matrices
  49965. * @param result defines an optional target matrix where to store the interpolation
  49966. * @returns the interpolated matrix
  49967. */
  49968. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  49969. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49970. if (result) {
  49971. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  49972. return result;
  49973. }
  49974. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49975. }
  49976. if (result) {
  49977. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  49978. return result;
  49979. }
  49980. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49981. };
  49982. Animation.prototype.clone = function () {
  49983. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49984. clone.enableBlending = this.enableBlending;
  49985. clone.blendingSpeed = this.blendingSpeed;
  49986. if (this._keys) {
  49987. clone.setKeys(this._keys);
  49988. }
  49989. if (this._ranges) {
  49990. clone._ranges = {};
  49991. for (var name in this._ranges) {
  49992. var range = this._ranges[name];
  49993. if (!range) {
  49994. continue;
  49995. }
  49996. clone._ranges[name] = range.clone();
  49997. }
  49998. }
  49999. return clone;
  50000. };
  50001. Animation.prototype.setKeys = function (values) {
  50002. this._keys = values.slice(0);
  50003. };
  50004. Animation.prototype.serialize = function () {
  50005. var serializationObject = {};
  50006. serializationObject.name = this.name;
  50007. serializationObject.property = this.targetProperty;
  50008. serializationObject.framePerSecond = this.framePerSecond;
  50009. serializationObject.dataType = this.dataType;
  50010. serializationObject.loopBehavior = this.loopMode;
  50011. serializationObject.enableBlending = this.enableBlending;
  50012. serializationObject.blendingSpeed = this.blendingSpeed;
  50013. var dataType = this.dataType;
  50014. serializationObject.keys = [];
  50015. var keys = this.getKeys();
  50016. for (var index = 0; index < keys.length; index++) {
  50017. var animationKey = keys[index];
  50018. var key = {};
  50019. key.frame = animationKey.frame;
  50020. switch (dataType) {
  50021. case Animation.ANIMATIONTYPE_FLOAT:
  50022. key.values = [animationKey.value];
  50023. break;
  50024. case Animation.ANIMATIONTYPE_QUATERNION:
  50025. case Animation.ANIMATIONTYPE_MATRIX:
  50026. case Animation.ANIMATIONTYPE_VECTOR3:
  50027. case Animation.ANIMATIONTYPE_COLOR3:
  50028. key.values = animationKey.value.asArray();
  50029. break;
  50030. }
  50031. serializationObject.keys.push(key);
  50032. }
  50033. serializationObject.ranges = [];
  50034. for (var name in this._ranges) {
  50035. var source = this._ranges[name];
  50036. if (!source) {
  50037. continue;
  50038. }
  50039. var range = {};
  50040. range.name = name;
  50041. range.from = source.from;
  50042. range.to = source.to;
  50043. serializationObject.ranges.push(range);
  50044. }
  50045. return serializationObject;
  50046. };
  50047. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50048. get: function () {
  50049. return Animation._ANIMATIONTYPE_FLOAT;
  50050. },
  50051. enumerable: true,
  50052. configurable: true
  50053. });
  50054. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50055. get: function () {
  50056. return Animation._ANIMATIONTYPE_VECTOR3;
  50057. },
  50058. enumerable: true,
  50059. configurable: true
  50060. });
  50061. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50062. get: function () {
  50063. return Animation._ANIMATIONTYPE_VECTOR2;
  50064. },
  50065. enumerable: true,
  50066. configurable: true
  50067. });
  50068. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50069. get: function () {
  50070. return Animation._ANIMATIONTYPE_SIZE;
  50071. },
  50072. enumerable: true,
  50073. configurable: true
  50074. });
  50075. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50076. get: function () {
  50077. return Animation._ANIMATIONTYPE_QUATERNION;
  50078. },
  50079. enumerable: true,
  50080. configurable: true
  50081. });
  50082. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50083. get: function () {
  50084. return Animation._ANIMATIONTYPE_MATRIX;
  50085. },
  50086. enumerable: true,
  50087. configurable: true
  50088. });
  50089. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50090. get: function () {
  50091. return Animation._ANIMATIONTYPE_COLOR3;
  50092. },
  50093. enumerable: true,
  50094. configurable: true
  50095. });
  50096. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50097. get: function () {
  50098. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50099. },
  50100. enumerable: true,
  50101. configurable: true
  50102. });
  50103. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50104. get: function () {
  50105. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50106. },
  50107. enumerable: true,
  50108. configurable: true
  50109. });
  50110. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50111. get: function () {
  50112. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50113. },
  50114. enumerable: true,
  50115. configurable: true
  50116. });
  50117. Animation.Parse = function (parsedAnimation) {
  50118. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50119. var dataType = parsedAnimation.dataType;
  50120. var keys = [];
  50121. var data;
  50122. var index;
  50123. if (parsedAnimation.enableBlending) {
  50124. animation.enableBlending = parsedAnimation.enableBlending;
  50125. }
  50126. if (parsedAnimation.blendingSpeed) {
  50127. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50128. }
  50129. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50130. var key = parsedAnimation.keys[index];
  50131. var inTangent;
  50132. var outTangent;
  50133. switch (dataType) {
  50134. case Animation.ANIMATIONTYPE_FLOAT:
  50135. data = key.values[0];
  50136. if (key.values.length >= 1) {
  50137. inTangent = key.values[1];
  50138. }
  50139. if (key.values.length >= 2) {
  50140. outTangent = key.values[2];
  50141. }
  50142. break;
  50143. case Animation.ANIMATIONTYPE_QUATERNION:
  50144. data = BABYLON.Quaternion.FromArray(key.values);
  50145. if (key.values.length >= 8) {
  50146. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50147. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50148. inTangent = _inTangent;
  50149. }
  50150. }
  50151. if (key.values.length >= 12) {
  50152. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50153. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50154. outTangent = _outTangent;
  50155. }
  50156. }
  50157. break;
  50158. case Animation.ANIMATIONTYPE_MATRIX:
  50159. data = BABYLON.Matrix.FromArray(key.values);
  50160. break;
  50161. case Animation.ANIMATIONTYPE_COLOR3:
  50162. data = BABYLON.Color3.FromArray(key.values);
  50163. break;
  50164. case Animation.ANIMATIONTYPE_VECTOR3:
  50165. default:
  50166. data = BABYLON.Vector3.FromArray(key.values);
  50167. break;
  50168. }
  50169. var keyData = {};
  50170. keyData.frame = key.frame;
  50171. keyData.value = data;
  50172. if (inTangent != undefined) {
  50173. keyData.inTangent = inTangent;
  50174. }
  50175. if (outTangent != undefined) {
  50176. keyData.outTangent = outTangent;
  50177. }
  50178. keys.push(keyData);
  50179. }
  50180. animation.setKeys(keys);
  50181. if (parsedAnimation.ranges) {
  50182. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50183. data = parsedAnimation.ranges[index];
  50184. animation.createRange(data.name, data.from, data.to);
  50185. }
  50186. }
  50187. return animation;
  50188. };
  50189. Animation.AppendSerializedAnimations = function (source, destination) {
  50190. if (source.animations) {
  50191. destination.animations = [];
  50192. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50193. var animation = source.animations[animationIndex];
  50194. destination.animations.push(animation.serialize());
  50195. }
  50196. }
  50197. };
  50198. /**
  50199. * Use matrix interpolation instead of using direct key value when animating matrices
  50200. */
  50201. Animation.AllowMatricesInterpolation = false;
  50202. /**
  50203. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50204. */
  50205. Animation.AllowMatrixDecomposeForInterpolation = true;
  50206. // Statics
  50207. Animation._ANIMATIONTYPE_FLOAT = 0;
  50208. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50209. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50210. Animation._ANIMATIONTYPE_MATRIX = 3;
  50211. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50212. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50213. Animation._ANIMATIONTYPE_SIZE = 6;
  50214. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50215. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50216. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50217. return Animation;
  50218. }());
  50219. BABYLON.Animation = Animation;
  50220. })(BABYLON || (BABYLON = {}));
  50221. //# sourceMappingURL=babylon.animation.js.map
  50222. "use strict";
  50223. var BABYLON;
  50224. (function (BABYLON) {
  50225. /**
  50226. * This class defines the direct association between an animation and a target
  50227. */
  50228. var TargetedAnimation = /** @class */ (function () {
  50229. function TargetedAnimation() {
  50230. }
  50231. return TargetedAnimation;
  50232. }());
  50233. BABYLON.TargetedAnimation = TargetedAnimation;
  50234. /**
  50235. * Use this class to create coordinated animations on multiple targets
  50236. */
  50237. var AnimationGroup = /** @class */ (function () {
  50238. function AnimationGroup(name, scene) {
  50239. if (scene === void 0) { scene = null; }
  50240. this.name = name;
  50241. this._targetedAnimations = new Array();
  50242. this._animatables = new Array();
  50243. this._from = Number.MAX_VALUE;
  50244. this._to = -Number.MAX_VALUE;
  50245. this._speedRatio = 1;
  50246. this.onAnimationEndObservable = new BABYLON.Observable();
  50247. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50248. this._scene.animationGroups.push(this);
  50249. }
  50250. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50251. /**
  50252. * Define if the animations are started
  50253. */
  50254. get: function () {
  50255. return this._isStarted;
  50256. },
  50257. enumerable: true,
  50258. configurable: true
  50259. });
  50260. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50261. /**
  50262. * Gets or sets the speed ratio to use for all animations
  50263. */
  50264. get: function () {
  50265. return this._speedRatio;
  50266. },
  50267. /**
  50268. * Gets or sets the speed ratio to use for all animations
  50269. */
  50270. set: function (value) {
  50271. if (this._speedRatio === value) {
  50272. return;
  50273. }
  50274. this._speedRatio = value;
  50275. for (var index = 0; index < this._animatables.length; index++) {
  50276. var animatable = this._animatables[index];
  50277. animatable.speedRatio = this._speedRatio;
  50278. }
  50279. },
  50280. enumerable: true,
  50281. configurable: true
  50282. });
  50283. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50284. /**
  50285. * Gets the targeted animations for this animation group
  50286. */
  50287. get: function () {
  50288. return this._targetedAnimations;
  50289. },
  50290. enumerable: true,
  50291. configurable: true
  50292. });
  50293. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50294. /**
  50295. * returning the list of animatables controlled by this animation group.
  50296. */
  50297. get: function () {
  50298. return this._animatables;
  50299. },
  50300. enumerable: true,
  50301. configurable: true
  50302. });
  50303. /**
  50304. * Add an animation (with its target) in the group
  50305. * @param animation defines the animation we want to add
  50306. * @param target defines the target of the animation
  50307. * @returns the {BABYLON.TargetedAnimation} object
  50308. */
  50309. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50310. var targetedAnimation = {
  50311. animation: animation,
  50312. target: target
  50313. };
  50314. var keys = animation.getKeys();
  50315. if (this._from > keys[0].frame) {
  50316. this._from = keys[0].frame;
  50317. }
  50318. if (this._to < keys[keys.length - 1].frame) {
  50319. this._to = keys[keys.length - 1].frame;
  50320. }
  50321. this._targetedAnimations.push(targetedAnimation);
  50322. return targetedAnimation;
  50323. };
  50324. /**
  50325. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50326. * It can add constant keys at begin or end
  50327. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  50328. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  50329. */
  50330. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50331. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  50332. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  50333. beginFrame = Math.max(beginFrame, this._from);
  50334. endFrame = Math.min(endFrame, this._to);
  50335. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50336. var targetedAnimation = this._targetedAnimations[index];
  50337. var keys = targetedAnimation.animation.getKeys();
  50338. var startKey = keys[0];
  50339. var endKey = keys[keys.length - 1];
  50340. if (startKey.frame > beginFrame) {
  50341. var newKey = {
  50342. frame: beginFrame,
  50343. value: startKey.value,
  50344. inTangent: startKey.inTangent,
  50345. outTangent: startKey.outTangent,
  50346. interpolation: startKey.interpolation
  50347. };
  50348. keys.splice(0, 0, newKey);
  50349. }
  50350. if (endKey.frame < endFrame) {
  50351. var newKey = {
  50352. frame: endFrame,
  50353. value: endKey.value,
  50354. inTangent: endKey.outTangent,
  50355. outTangent: endKey.outTangent,
  50356. interpolation: endKey.interpolation
  50357. };
  50358. keys.push(newKey);
  50359. }
  50360. }
  50361. return this;
  50362. };
  50363. /**
  50364. * Start all animations on given targets
  50365. * @param loop defines if animations must loop
  50366. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50367. * @param from defines the from key (optional)
  50368. * @param to defines the to key (optional)
  50369. * @returns the current animation group
  50370. */
  50371. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50372. var _this = this;
  50373. if (loop === void 0) { loop = false; }
  50374. if (speedRatio === void 0) { speedRatio = 1; }
  50375. if (this._isStarted || this._targetedAnimations.length === 0) {
  50376. return this;
  50377. }
  50378. var _loop_1 = function () {
  50379. var targetedAnimation = this_1._targetedAnimations[index];
  50380. if (!targetedAnimation.target.animations) {
  50381. targetedAnimation.target.animations = [];
  50382. }
  50383. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  50384. targetedAnimation.target.animations.push(targetedAnimation.animation);
  50385. }
  50386. 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 () {
  50387. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50388. }));
  50389. };
  50390. var this_1 = this;
  50391. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50392. _loop_1();
  50393. }
  50394. this._speedRatio = speedRatio;
  50395. this._isStarted = true;
  50396. return this;
  50397. };
  50398. /**
  50399. * Pause all animations
  50400. */
  50401. AnimationGroup.prototype.pause = function () {
  50402. if (!this._isStarted) {
  50403. return this;
  50404. }
  50405. for (var index = 0; index < this._animatables.length; index++) {
  50406. var animatable = this._animatables[index];
  50407. animatable.pause();
  50408. }
  50409. return this;
  50410. };
  50411. /**
  50412. * Play all animations to initial state
  50413. * This function will start() the animations if they were not started or will restart() them if they were paused
  50414. * @param loop defines if animations must loop
  50415. */
  50416. AnimationGroup.prototype.play = function (loop) {
  50417. if (this.isStarted) {
  50418. if (loop !== undefined) {
  50419. for (var index = 0; index < this._animatables.length; index++) {
  50420. var animatable = this._animatables[index];
  50421. animatable.loopAnimation = loop;
  50422. }
  50423. }
  50424. this.restart();
  50425. }
  50426. else {
  50427. this.start(loop, this._speedRatio);
  50428. }
  50429. return this;
  50430. };
  50431. /**
  50432. * Reset all animations to initial state
  50433. */
  50434. AnimationGroup.prototype.reset = function () {
  50435. if (!this._isStarted) {
  50436. return this;
  50437. }
  50438. for (var index = 0; index < this._animatables.length; index++) {
  50439. var animatable = this._animatables[index];
  50440. animatable.reset();
  50441. }
  50442. return this;
  50443. };
  50444. /**
  50445. * Restart animations from key 0
  50446. */
  50447. AnimationGroup.prototype.restart = function () {
  50448. if (!this._isStarted) {
  50449. return this;
  50450. }
  50451. for (var index = 0; index < this._animatables.length; index++) {
  50452. var animatable = this._animatables[index];
  50453. animatable.restart();
  50454. }
  50455. return this;
  50456. };
  50457. /**
  50458. * Stop all animations
  50459. */
  50460. AnimationGroup.prototype.stop = function () {
  50461. if (!this._isStarted) {
  50462. return this;
  50463. }
  50464. for (var index = 0; index < this._animatables.length; index++) {
  50465. var animatable = this._animatables[index];
  50466. animatable.stop();
  50467. }
  50468. this._isStarted = false;
  50469. return this;
  50470. };
  50471. /**
  50472. * Goes to a specific frame in this animation group
  50473. *
  50474. * @param frame the frame number to go to
  50475. * @return the animationGroup
  50476. */
  50477. AnimationGroup.prototype.goToFrame = function (frame) {
  50478. if (!this._isStarted) {
  50479. return this;
  50480. }
  50481. for (var index = 0; index < this._animatables.length; index++) {
  50482. var animatable = this._animatables[index];
  50483. animatable.goToFrame(frame);
  50484. }
  50485. return this;
  50486. };
  50487. /**
  50488. * Dispose all associated resources
  50489. */
  50490. AnimationGroup.prototype.dispose = function () {
  50491. this._targetedAnimations = [];
  50492. this._animatables = [];
  50493. var index = this._scene.animationGroups.indexOf(this);
  50494. if (index > -1) {
  50495. this._scene.animationGroups.splice(index, 1);
  50496. }
  50497. };
  50498. return AnimationGroup;
  50499. }());
  50500. BABYLON.AnimationGroup = AnimationGroup;
  50501. })(BABYLON || (BABYLON = {}));
  50502. //# sourceMappingURL=babylon.animationGroup.js.map
  50503. "use strict";
  50504. var BABYLON;
  50505. (function (BABYLON) {
  50506. var RuntimeAnimation = /** @class */ (function () {
  50507. /**
  50508. * Create a new RuntimeAnimation object
  50509. * @param target defines the target of the animation
  50510. * @param animation defines the source {BABYLON.Animation} object
  50511. * @param scene defines the hosting scene
  50512. * @param host defines the initiating Animatable
  50513. */
  50514. function RuntimeAnimation(target, animation, scene, host) {
  50515. this._currentFrame = 0;
  50516. this._offsetsCache = {};
  50517. this._highLimitsCache = {};
  50518. this._stopped = false;
  50519. this._blendingFactor = 0;
  50520. this._targetPath = "";
  50521. this._weight = 1.0;
  50522. this._ratioOffset = 0;
  50523. this._previousDelay = 0;
  50524. this._previousRatio = 0;
  50525. this._animation = animation;
  50526. this._target = target;
  50527. this._scene = scene;
  50528. this._host = host;
  50529. animation._runtimeAnimations.push(this);
  50530. }
  50531. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50532. /**
  50533. * Gets the current frame
  50534. */
  50535. get: function () {
  50536. return this._currentFrame;
  50537. },
  50538. enumerable: true,
  50539. configurable: true
  50540. });
  50541. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50542. /**
  50543. * Gets the weight of the runtime animation
  50544. */
  50545. get: function () {
  50546. return this._weight;
  50547. },
  50548. enumerable: true,
  50549. configurable: true
  50550. });
  50551. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  50552. /**
  50553. * Gets the original value of the runtime animation
  50554. */
  50555. get: function () {
  50556. return this._originalValue;
  50557. },
  50558. enumerable: true,
  50559. configurable: true
  50560. });
  50561. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50562. /**
  50563. * Gets the current value of the runtime animation
  50564. */
  50565. get: function () {
  50566. return this._currentValue;
  50567. },
  50568. enumerable: true,
  50569. configurable: true
  50570. });
  50571. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50572. /**
  50573. * Gets the path where to store the animated value in the target
  50574. */
  50575. get: function () {
  50576. return this._targetPath;
  50577. },
  50578. enumerable: true,
  50579. configurable: true
  50580. });
  50581. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50582. /**
  50583. * Gets the actual target of the runtime animation
  50584. */
  50585. get: function () {
  50586. return this._activeTarget;
  50587. },
  50588. enumerable: true,
  50589. configurable: true
  50590. });
  50591. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50592. get: function () {
  50593. return this._animation;
  50594. },
  50595. enumerable: true,
  50596. configurable: true
  50597. });
  50598. RuntimeAnimation.prototype.reset = function () {
  50599. this._offsetsCache = {};
  50600. this._highLimitsCache = {};
  50601. this._currentFrame = 0;
  50602. this._blendingFactor = 0;
  50603. this._originalValue = null;
  50604. };
  50605. RuntimeAnimation.prototype.isStopped = function () {
  50606. return this._stopped;
  50607. };
  50608. RuntimeAnimation.prototype.dispose = function () {
  50609. var index = this._animation.runtimeAnimations.indexOf(this);
  50610. if (index > -1) {
  50611. this._animation.runtimeAnimations.splice(index, 1);
  50612. }
  50613. };
  50614. RuntimeAnimation.prototype._getKeyValue = function (value) {
  50615. if (typeof value === "function") {
  50616. return value();
  50617. }
  50618. return value;
  50619. };
  50620. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50621. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50622. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50623. }
  50624. this._currentFrame = currentFrame;
  50625. var keys = this._animation.getKeys();
  50626. // Try to get a hash to find the right key
  50627. 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));
  50628. if (keys[startKeyIndex].frame >= currentFrame) {
  50629. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50630. startKeyIndex--;
  50631. }
  50632. }
  50633. for (var key = startKeyIndex; key < keys.length; key++) {
  50634. var endKey = keys[key + 1];
  50635. if (endKey.frame >= currentFrame) {
  50636. var startKey = keys[key];
  50637. var startValue = this._getKeyValue(startKey.value);
  50638. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  50639. return startValue;
  50640. }
  50641. var endValue = this._getKeyValue(endKey.value);
  50642. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50643. var frameDelta = endKey.frame - startKey.frame;
  50644. // gradient : percent of currentFrame between the frame inf and the frame sup
  50645. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50646. // check for easingFunction and correction of gradient
  50647. var easingFunction = this._animation.getEasingFunction();
  50648. if (easingFunction != null) {
  50649. gradient = easingFunction.ease(gradient);
  50650. }
  50651. switch (this._animation.dataType) {
  50652. // Float
  50653. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50654. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  50655. switch (loopMode) {
  50656. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50657. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50658. return floatValue;
  50659. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50660. return offsetValue * repeatCount + floatValue;
  50661. }
  50662. break;
  50663. // Quaternion
  50664. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50665. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  50666. switch (loopMode) {
  50667. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50668. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50669. return quatValue;
  50670. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50671. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50672. }
  50673. return quatValue;
  50674. // Vector3
  50675. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50676. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  50677. switch (loopMode) {
  50678. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50679. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50680. return vec3Value;
  50681. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50682. return vec3Value.add(offsetValue.scale(repeatCount));
  50683. }
  50684. // Vector2
  50685. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50686. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  50687. switch (loopMode) {
  50688. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50689. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50690. return vec2Value;
  50691. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50692. return vec2Value.add(offsetValue.scale(repeatCount));
  50693. }
  50694. // Size
  50695. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50696. switch (loopMode) {
  50697. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50698. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50699. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  50700. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50701. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50702. }
  50703. // Color3
  50704. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50705. switch (loopMode) {
  50706. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50707. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50708. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  50709. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50710. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50711. }
  50712. // Matrix
  50713. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  50714. switch (loopMode) {
  50715. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50716. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50717. if (BABYLON.Animation.AllowMatricesInterpolation) {
  50718. this._workValue = this._animation.matrixInterpolateFunction(startValue, endValue, gradient, this._workValue);
  50719. return this._workValue;
  50720. }
  50721. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50722. return startValue;
  50723. }
  50724. default:
  50725. break;
  50726. }
  50727. break;
  50728. }
  50729. }
  50730. return this._getKeyValue(keys[keys.length - 1].value);
  50731. };
  50732. /**
  50733. * Affect the interpolated value to the target
  50734. * @param currentValue defines the value computed by the animation
  50735. * @param weight defines the weight to apply to this value
  50736. */
  50737. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50738. if (weight === void 0) { weight = 1.0; }
  50739. // Set value
  50740. var path;
  50741. var destination;
  50742. var targetPropertyPath = this._animation.targetPropertyPath;
  50743. if (targetPropertyPath.length > 1) {
  50744. var property = this._target[targetPropertyPath[0]];
  50745. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50746. property = property[targetPropertyPath[index]];
  50747. }
  50748. path = targetPropertyPath[targetPropertyPath.length - 1];
  50749. destination = property;
  50750. }
  50751. else {
  50752. path = targetPropertyPath[0];
  50753. destination = this._target;
  50754. }
  50755. this._targetPath = path;
  50756. this._activeTarget = destination;
  50757. this._weight = weight;
  50758. // Blending
  50759. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50760. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50761. if (enableBlending && this._blendingFactor <= 1.0) {
  50762. if (!this._originalBlendValue) {
  50763. var originalValue = destination[path];
  50764. if (originalValue.clone) {
  50765. this._originalBlendValue = originalValue.clone();
  50766. }
  50767. else {
  50768. this._originalBlendValue = originalValue;
  50769. }
  50770. }
  50771. }
  50772. if (weight !== -1.0) {
  50773. if (!this._originalValue) {
  50774. var originalValue = void 0;
  50775. if (destination.getRestPose) {
  50776. originalValue = destination.getRestPose();
  50777. }
  50778. else {
  50779. originalValue = destination[path];
  50780. }
  50781. if (originalValue.clone) {
  50782. this._originalValue = originalValue.clone();
  50783. }
  50784. else {
  50785. this._originalValue = originalValue;
  50786. }
  50787. }
  50788. }
  50789. if (enableBlending && this._blendingFactor <= 1.0) {
  50790. if (this._originalBlendValue.prototype) {
  50791. if (this._originalBlendValue.prototype.Lerp) {
  50792. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  50793. }
  50794. else {
  50795. this._currentValue = currentValue;
  50796. }
  50797. }
  50798. else if (this._originalBlendValue.m) {
  50799. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50800. if (this._currentValue) {
  50801. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50802. }
  50803. else {
  50804. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50805. }
  50806. }
  50807. else {
  50808. if (this._currentValue) {
  50809. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50810. }
  50811. else {
  50812. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50813. }
  50814. }
  50815. }
  50816. else {
  50817. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  50818. }
  50819. this._blendingFactor += blendingSpeed;
  50820. }
  50821. else {
  50822. this._currentValue = currentValue;
  50823. }
  50824. if (weight !== -1.0) {
  50825. this._scene._registerTargetForLateAnimationBinding(this);
  50826. }
  50827. else {
  50828. destination[path] = this._currentValue;
  50829. }
  50830. if (this._target.markAsDirty) {
  50831. this._target.markAsDirty(this._animation.targetProperty);
  50832. }
  50833. };
  50834. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50835. if (this._target && this._target.animationPropertiesOverride) {
  50836. return this._target.animationPropertiesOverride.loopMode;
  50837. }
  50838. return this._animation.loopMode;
  50839. };
  50840. /**
  50841. * Move the current animation to a given frame
  50842. * @param frame defines the frame to move to
  50843. */
  50844. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50845. var keys = this._animation.getKeys();
  50846. if (frame < keys[0].frame) {
  50847. frame = keys[0].frame;
  50848. }
  50849. else if (frame > keys[keys.length - 1].frame) {
  50850. frame = keys[keys.length - 1].frame;
  50851. }
  50852. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50853. this.setValue(currentValue, -1);
  50854. };
  50855. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  50856. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  50857. this._ratioOffset = this._previousRatio - newRatio;
  50858. };
  50859. /**
  50860. * Execute the current animation
  50861. * @param delay defines the delay to add to the current frame
  50862. * @param from defines the lower bound of the animation range
  50863. * @param to defines the upper bound of the animation range
  50864. * @param loop defines if the current animation must loop
  50865. * @param speedRatio defines the current speed ratio
  50866. * @param weight defines the weight of the animation (default is -1 so no weight)
  50867. * @returns a boolean indicating if the animation has ended
  50868. */
  50869. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  50870. if (weight === void 0) { weight = -1.0; }
  50871. var targetPropertyPath = this._animation.targetPropertyPath;
  50872. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  50873. this._stopped = true;
  50874. return false;
  50875. }
  50876. var returnValue = true;
  50877. var keys = this._animation.getKeys();
  50878. // Adding a start key at frame 0 if missing
  50879. if (keys[0].frame !== 0) {
  50880. var newKey = { frame: 0, value: keys[0].value };
  50881. keys.splice(0, 0, newKey);
  50882. }
  50883. // Check limits
  50884. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  50885. from = keys[0].frame;
  50886. }
  50887. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  50888. to = keys[keys.length - 1].frame;
  50889. }
  50890. //to and from cannot be the same key
  50891. if (from === to) {
  50892. if (from > keys[0].frame) {
  50893. from--;
  50894. }
  50895. else if (to < keys[keys.length - 1].frame) {
  50896. to++;
  50897. }
  50898. }
  50899. // Compute ratio
  50900. var range = to - from;
  50901. var offsetValue;
  50902. // ratio represents the frame delta between from and to
  50903. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  50904. var highLimitValue = 0;
  50905. this._previousDelay = delay;
  50906. this._previousRatio = ratio;
  50907. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  50908. returnValue = false;
  50909. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  50910. }
  50911. else {
  50912. // Get max value if required
  50913. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  50914. var keyOffset = to.toString() + from.toString();
  50915. if (!this._offsetsCache[keyOffset]) {
  50916. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50917. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50918. switch (this._animation.dataType) {
  50919. // Float
  50920. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50921. this._offsetsCache[keyOffset] = toValue - fromValue;
  50922. break;
  50923. // Quaternion
  50924. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50925. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50926. break;
  50927. // Vector3
  50928. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50929. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50930. // Vector2
  50931. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50932. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50933. // Size
  50934. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50935. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50936. // Color3
  50937. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50938. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50939. default:
  50940. break;
  50941. }
  50942. this._highLimitsCache[keyOffset] = toValue;
  50943. }
  50944. highLimitValue = this._highLimitsCache[keyOffset];
  50945. offsetValue = this._offsetsCache[keyOffset];
  50946. }
  50947. }
  50948. if (offsetValue === undefined) {
  50949. switch (this._animation.dataType) {
  50950. // Float
  50951. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50952. offsetValue = 0;
  50953. break;
  50954. // Quaternion
  50955. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50956. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  50957. break;
  50958. // Vector3
  50959. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50960. offsetValue = BABYLON.Vector3.Zero();
  50961. break;
  50962. // Vector2
  50963. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50964. offsetValue = BABYLON.Vector2.Zero();
  50965. break;
  50966. // Size
  50967. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50968. offsetValue = BABYLON.Size.Zero();
  50969. break;
  50970. // Color3
  50971. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50972. offsetValue = BABYLON.Color3.Black();
  50973. }
  50974. }
  50975. // Compute value
  50976. var repeatCount = (ratio / range) >> 0;
  50977. var currentFrame = returnValue ? from + ratio % range : to;
  50978. // Need to normalize?
  50979. if (this._host && this._host.syncRoot) {
  50980. var syncRoot = this._host.syncRoot;
  50981. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  50982. currentFrame = from + (to - from) * hostNormalizedFrame;
  50983. }
  50984. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  50985. // Set value
  50986. this.setValue(currentValue, weight);
  50987. // Check events
  50988. var events = this._animation.getEvents();
  50989. for (var index = 0; index < events.length; index++) {
  50990. // Make sure current frame has passed event frame and that event frame is within the current range
  50991. // Also, handle both forward and reverse animations
  50992. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  50993. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  50994. var event = events[index];
  50995. if (!event.isDone) {
  50996. // If event should be done only once, remove it.
  50997. if (event.onlyOnce) {
  50998. events.splice(index, 1);
  50999. index--;
  51000. }
  51001. event.isDone = true;
  51002. event.action();
  51003. } // Don't do anything if the event has already be done.
  51004. }
  51005. else if (events[index].isDone && !events[index].onlyOnce) {
  51006. // reset event, the animation is looping
  51007. events[index].isDone = false;
  51008. }
  51009. }
  51010. if (!returnValue) {
  51011. this._stopped = true;
  51012. }
  51013. return returnValue;
  51014. };
  51015. return RuntimeAnimation;
  51016. }());
  51017. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51018. })(BABYLON || (BABYLON = {}));
  51019. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51020. "use strict";
  51021. var BABYLON;
  51022. (function (BABYLON) {
  51023. var Animatable = /** @class */ (function () {
  51024. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51025. if (fromFrame === void 0) { fromFrame = 0; }
  51026. if (toFrame === void 0) { toFrame = 100; }
  51027. if (loopAnimation === void 0) { loopAnimation = false; }
  51028. if (speedRatio === void 0) { speedRatio = 1.0; }
  51029. this.target = target;
  51030. this.fromFrame = fromFrame;
  51031. this.toFrame = toFrame;
  51032. this.loopAnimation = loopAnimation;
  51033. this.onAnimationEnd = onAnimationEnd;
  51034. this._localDelayOffset = null;
  51035. this._pausedDelay = null;
  51036. this._runtimeAnimations = new Array();
  51037. this._paused = false;
  51038. this._speedRatio = 1;
  51039. this._weight = -1.0;
  51040. this.animationStarted = false;
  51041. if (animations) {
  51042. this.appendAnimations(target, animations);
  51043. }
  51044. this._speedRatio = speedRatio;
  51045. this._scene = scene;
  51046. scene._activeAnimatables.push(this);
  51047. }
  51048. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51049. /**
  51050. * Gets the root Animatable used to synchronize and normalize animations
  51051. */
  51052. get: function () {
  51053. return this._syncRoot;
  51054. },
  51055. enumerable: true,
  51056. configurable: true
  51057. });
  51058. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51059. /**
  51060. * Gets the current frame of the first RuntimeAnimation
  51061. * Used to synchronize Animatables
  51062. */
  51063. get: function () {
  51064. if (this._runtimeAnimations.length === 0) {
  51065. return 0;
  51066. }
  51067. return this._runtimeAnimations[0].currentFrame;
  51068. },
  51069. enumerable: true,
  51070. configurable: true
  51071. });
  51072. Object.defineProperty(Animatable.prototype, "weight", {
  51073. /**
  51074. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51075. */
  51076. get: function () {
  51077. return this._weight;
  51078. },
  51079. set: function (value) {
  51080. if (value === -1) {
  51081. this._weight = -1;
  51082. return;
  51083. }
  51084. // Else weight must be in [0, 1] range
  51085. this._weight = Math.min(Math.max(value, 0), 1.0);
  51086. },
  51087. enumerable: true,
  51088. configurable: true
  51089. });
  51090. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51091. /**
  51092. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51093. */
  51094. get: function () {
  51095. return this._speedRatio;
  51096. },
  51097. set: function (value) {
  51098. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51099. var animation = this._runtimeAnimations[index];
  51100. animation._prepareForSpeedRatioChange(value);
  51101. }
  51102. this._speedRatio = value;
  51103. },
  51104. enumerable: true,
  51105. configurable: true
  51106. });
  51107. // Methods
  51108. /**
  51109. * Synchronize and normalize current Animatable with a source Animatable.
  51110. * This is useful when using animation weights and when animations are not of the same length
  51111. * @param root defines the root Animatable to synchronize with
  51112. * @returns the current Animatable
  51113. */
  51114. Animatable.prototype.syncWith = function (root) {
  51115. this._syncRoot = root;
  51116. if (root) {
  51117. // Make sure this animatable will animate after the root
  51118. var index = this._scene._activeAnimatables.indexOf(this);
  51119. if (index > -1) {
  51120. this._scene._activeAnimatables.splice(index, 1);
  51121. this._scene._activeAnimatables.push(this);
  51122. }
  51123. }
  51124. return this;
  51125. };
  51126. Animatable.prototype.getAnimations = function () {
  51127. return this._runtimeAnimations;
  51128. };
  51129. Animatable.prototype.appendAnimations = function (target, animations) {
  51130. for (var index = 0; index < animations.length; index++) {
  51131. var animation = animations[index];
  51132. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51133. }
  51134. };
  51135. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51136. var runtimeAnimations = this._runtimeAnimations;
  51137. for (var index = 0; index < runtimeAnimations.length; index++) {
  51138. if (runtimeAnimations[index].animation.targetProperty === property) {
  51139. return runtimeAnimations[index].animation;
  51140. }
  51141. }
  51142. return null;
  51143. };
  51144. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51145. var runtimeAnimations = this._runtimeAnimations;
  51146. for (var index = 0; index < runtimeAnimations.length; index++) {
  51147. if (runtimeAnimations[index].animation.targetProperty === property) {
  51148. return runtimeAnimations[index];
  51149. }
  51150. }
  51151. return null;
  51152. };
  51153. Animatable.prototype.reset = function () {
  51154. var runtimeAnimations = this._runtimeAnimations;
  51155. for (var index = 0; index < runtimeAnimations.length; index++) {
  51156. runtimeAnimations[index].reset();
  51157. }
  51158. // Reset to original value
  51159. for (index = 0; index < runtimeAnimations.length; index++) {
  51160. var animation = runtimeAnimations[index];
  51161. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  51162. }
  51163. this._localDelayOffset = null;
  51164. this._pausedDelay = null;
  51165. };
  51166. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51167. var runtimeAnimations = this._runtimeAnimations;
  51168. for (var index = 0; index < runtimeAnimations.length; index++) {
  51169. runtimeAnimations[index].animation.enableBlending = true;
  51170. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51171. }
  51172. };
  51173. Animatable.prototype.disableBlending = function () {
  51174. var runtimeAnimations = this._runtimeAnimations;
  51175. for (var index = 0; index < runtimeAnimations.length; index++) {
  51176. runtimeAnimations[index].animation.enableBlending = false;
  51177. }
  51178. };
  51179. Animatable.prototype.goToFrame = function (frame) {
  51180. var runtimeAnimations = this._runtimeAnimations;
  51181. if (runtimeAnimations[0]) {
  51182. var fps = runtimeAnimations[0].animation.framePerSecond;
  51183. var currentFrame = runtimeAnimations[0].currentFrame;
  51184. var adjustTime = frame - currentFrame;
  51185. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51186. if (this._localDelayOffset === null) {
  51187. this._localDelayOffset = 0;
  51188. }
  51189. this._localDelayOffset -= delay;
  51190. }
  51191. for (var index = 0; index < runtimeAnimations.length; index++) {
  51192. runtimeAnimations[index].goToFrame(frame);
  51193. }
  51194. };
  51195. Animatable.prototype.pause = function () {
  51196. if (this._paused) {
  51197. return;
  51198. }
  51199. this._paused = true;
  51200. };
  51201. Animatable.prototype.restart = function () {
  51202. this._paused = false;
  51203. };
  51204. Animatable.prototype.stop = function (animationName) {
  51205. if (animationName) {
  51206. var idx = this._scene._activeAnimatables.indexOf(this);
  51207. if (idx > -1) {
  51208. var runtimeAnimations = this._runtimeAnimations;
  51209. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51210. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51211. continue;
  51212. }
  51213. runtimeAnimations[index].dispose();
  51214. runtimeAnimations.splice(index, 1);
  51215. }
  51216. if (runtimeAnimations.length == 0) {
  51217. this._scene._activeAnimatables.splice(idx, 1);
  51218. if (this.onAnimationEnd) {
  51219. this.onAnimationEnd();
  51220. }
  51221. }
  51222. }
  51223. }
  51224. else {
  51225. var index = this._scene._activeAnimatables.indexOf(this);
  51226. if (index > -1) {
  51227. this._scene._activeAnimatables.splice(index, 1);
  51228. var runtimeAnimations = this._runtimeAnimations;
  51229. for (var index = 0; index < runtimeAnimations.length; index++) {
  51230. runtimeAnimations[index].dispose();
  51231. }
  51232. if (this.onAnimationEnd) {
  51233. this.onAnimationEnd();
  51234. }
  51235. }
  51236. }
  51237. };
  51238. Animatable.prototype._animate = function (delay) {
  51239. if (this._paused) {
  51240. this.animationStarted = false;
  51241. if (this._pausedDelay === null) {
  51242. this._pausedDelay = delay;
  51243. }
  51244. return true;
  51245. }
  51246. if (this._localDelayOffset === null) {
  51247. this._localDelayOffset = delay;
  51248. this._pausedDelay = null;
  51249. }
  51250. else if (this._pausedDelay !== null) {
  51251. this._localDelayOffset += delay - this._pausedDelay;
  51252. this._pausedDelay = null;
  51253. }
  51254. if (this._weight === 0) {
  51255. return true;
  51256. }
  51257. // Animating
  51258. var running = false;
  51259. var runtimeAnimations = this._runtimeAnimations;
  51260. var index;
  51261. for (index = 0; index < runtimeAnimations.length; index++) {
  51262. var animation = runtimeAnimations[index];
  51263. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51264. running = running || isRunning;
  51265. }
  51266. this.animationStarted = running;
  51267. if (!running) {
  51268. // Remove from active animatables
  51269. index = this._scene._activeAnimatables.indexOf(this);
  51270. this._scene._activeAnimatables.splice(index, 1);
  51271. // Dispose all runtime animations
  51272. for (index = 0; index < runtimeAnimations.length; index++) {
  51273. runtimeAnimations[index].dispose();
  51274. }
  51275. }
  51276. if (!running && this.onAnimationEnd) {
  51277. this.onAnimationEnd();
  51278. this.onAnimationEnd = null;
  51279. }
  51280. return running;
  51281. };
  51282. return Animatable;
  51283. }());
  51284. BABYLON.Animatable = Animatable;
  51285. })(BABYLON || (BABYLON = {}));
  51286. //# sourceMappingURL=babylon.animatable.js.map
  51287. "use strict";
  51288. var BABYLON;
  51289. (function (BABYLON) {
  51290. var EasingFunction = /** @class */ (function () {
  51291. function EasingFunction() {
  51292. // Properties
  51293. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51294. }
  51295. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51296. get: function () {
  51297. return EasingFunction._EASINGMODE_EASEIN;
  51298. },
  51299. enumerable: true,
  51300. configurable: true
  51301. });
  51302. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51303. get: function () {
  51304. return EasingFunction._EASINGMODE_EASEOUT;
  51305. },
  51306. enumerable: true,
  51307. configurable: true
  51308. });
  51309. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51310. get: function () {
  51311. return EasingFunction._EASINGMODE_EASEINOUT;
  51312. },
  51313. enumerable: true,
  51314. configurable: true
  51315. });
  51316. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51317. var n = Math.min(Math.max(easingMode, 0), 2);
  51318. this._easingMode = n;
  51319. };
  51320. EasingFunction.prototype.getEasingMode = function () {
  51321. return this._easingMode;
  51322. };
  51323. EasingFunction.prototype.easeInCore = function (gradient) {
  51324. throw new Error('You must implement this method');
  51325. };
  51326. EasingFunction.prototype.ease = function (gradient) {
  51327. switch (this._easingMode) {
  51328. case EasingFunction.EASINGMODE_EASEIN:
  51329. return this.easeInCore(gradient);
  51330. case EasingFunction.EASINGMODE_EASEOUT:
  51331. return (1 - this.easeInCore(1 - gradient));
  51332. }
  51333. if (gradient >= 0.5) {
  51334. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51335. }
  51336. return (this.easeInCore(gradient * 2) * 0.5);
  51337. };
  51338. //Statics
  51339. EasingFunction._EASINGMODE_EASEIN = 0;
  51340. EasingFunction._EASINGMODE_EASEOUT = 1;
  51341. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51342. return EasingFunction;
  51343. }());
  51344. BABYLON.EasingFunction = EasingFunction;
  51345. var CircleEase = /** @class */ (function (_super) {
  51346. __extends(CircleEase, _super);
  51347. function CircleEase() {
  51348. return _super !== null && _super.apply(this, arguments) || this;
  51349. }
  51350. CircleEase.prototype.easeInCore = function (gradient) {
  51351. gradient = Math.max(0, Math.min(1, gradient));
  51352. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51353. };
  51354. return CircleEase;
  51355. }(EasingFunction));
  51356. BABYLON.CircleEase = CircleEase;
  51357. var BackEase = /** @class */ (function (_super) {
  51358. __extends(BackEase, _super);
  51359. function BackEase(amplitude) {
  51360. if (amplitude === void 0) { amplitude = 1; }
  51361. var _this = _super.call(this) || this;
  51362. _this.amplitude = amplitude;
  51363. return _this;
  51364. }
  51365. BackEase.prototype.easeInCore = function (gradient) {
  51366. var num = Math.max(0, this.amplitude);
  51367. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51368. };
  51369. return BackEase;
  51370. }(EasingFunction));
  51371. BABYLON.BackEase = BackEase;
  51372. var BounceEase = /** @class */ (function (_super) {
  51373. __extends(BounceEase, _super);
  51374. function BounceEase(bounces, bounciness) {
  51375. if (bounces === void 0) { bounces = 3; }
  51376. if (bounciness === void 0) { bounciness = 2; }
  51377. var _this = _super.call(this) || this;
  51378. _this.bounces = bounces;
  51379. _this.bounciness = bounciness;
  51380. return _this;
  51381. }
  51382. BounceEase.prototype.easeInCore = function (gradient) {
  51383. var y = Math.max(0.0, this.bounces);
  51384. var bounciness = this.bounciness;
  51385. if (bounciness <= 1.0) {
  51386. bounciness = 1.001;
  51387. }
  51388. var num9 = Math.pow(bounciness, y);
  51389. var num5 = 1.0 - bounciness;
  51390. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51391. var num15 = gradient * num4;
  51392. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51393. var num3 = Math.floor(num65);
  51394. var num13 = num3 + 1.0;
  51395. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51396. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51397. var num7 = (num8 + num12) * 0.5;
  51398. var num6 = gradient - num7;
  51399. var num2 = num7 - num8;
  51400. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51401. };
  51402. return BounceEase;
  51403. }(EasingFunction));
  51404. BABYLON.BounceEase = BounceEase;
  51405. var CubicEase = /** @class */ (function (_super) {
  51406. __extends(CubicEase, _super);
  51407. function CubicEase() {
  51408. return _super !== null && _super.apply(this, arguments) || this;
  51409. }
  51410. CubicEase.prototype.easeInCore = function (gradient) {
  51411. return (gradient * gradient * gradient);
  51412. };
  51413. return CubicEase;
  51414. }(EasingFunction));
  51415. BABYLON.CubicEase = CubicEase;
  51416. var ElasticEase = /** @class */ (function (_super) {
  51417. __extends(ElasticEase, _super);
  51418. function ElasticEase(oscillations, springiness) {
  51419. if (oscillations === void 0) { oscillations = 3; }
  51420. if (springiness === void 0) { springiness = 3; }
  51421. var _this = _super.call(this) || this;
  51422. _this.oscillations = oscillations;
  51423. _this.springiness = springiness;
  51424. return _this;
  51425. }
  51426. ElasticEase.prototype.easeInCore = function (gradient) {
  51427. var num2;
  51428. var num3 = Math.max(0.0, this.oscillations);
  51429. var num = Math.max(0.0, this.springiness);
  51430. if (num == 0) {
  51431. num2 = gradient;
  51432. }
  51433. else {
  51434. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51435. }
  51436. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51437. };
  51438. return ElasticEase;
  51439. }(EasingFunction));
  51440. BABYLON.ElasticEase = ElasticEase;
  51441. var ExponentialEase = /** @class */ (function (_super) {
  51442. __extends(ExponentialEase, _super);
  51443. function ExponentialEase(exponent) {
  51444. if (exponent === void 0) { exponent = 2; }
  51445. var _this = _super.call(this) || this;
  51446. _this.exponent = exponent;
  51447. return _this;
  51448. }
  51449. ExponentialEase.prototype.easeInCore = function (gradient) {
  51450. if (this.exponent <= 0) {
  51451. return gradient;
  51452. }
  51453. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51454. };
  51455. return ExponentialEase;
  51456. }(EasingFunction));
  51457. BABYLON.ExponentialEase = ExponentialEase;
  51458. var PowerEase = /** @class */ (function (_super) {
  51459. __extends(PowerEase, _super);
  51460. function PowerEase(power) {
  51461. if (power === void 0) { power = 2; }
  51462. var _this = _super.call(this) || this;
  51463. _this.power = power;
  51464. return _this;
  51465. }
  51466. PowerEase.prototype.easeInCore = function (gradient) {
  51467. var y = Math.max(0.0, this.power);
  51468. return Math.pow(gradient, y);
  51469. };
  51470. return PowerEase;
  51471. }(EasingFunction));
  51472. BABYLON.PowerEase = PowerEase;
  51473. var QuadraticEase = /** @class */ (function (_super) {
  51474. __extends(QuadraticEase, _super);
  51475. function QuadraticEase() {
  51476. return _super !== null && _super.apply(this, arguments) || this;
  51477. }
  51478. QuadraticEase.prototype.easeInCore = function (gradient) {
  51479. return (gradient * gradient);
  51480. };
  51481. return QuadraticEase;
  51482. }(EasingFunction));
  51483. BABYLON.QuadraticEase = QuadraticEase;
  51484. var QuarticEase = /** @class */ (function (_super) {
  51485. __extends(QuarticEase, _super);
  51486. function QuarticEase() {
  51487. return _super !== null && _super.apply(this, arguments) || this;
  51488. }
  51489. QuarticEase.prototype.easeInCore = function (gradient) {
  51490. return (gradient * gradient * gradient * gradient);
  51491. };
  51492. return QuarticEase;
  51493. }(EasingFunction));
  51494. BABYLON.QuarticEase = QuarticEase;
  51495. var QuinticEase = /** @class */ (function (_super) {
  51496. __extends(QuinticEase, _super);
  51497. function QuinticEase() {
  51498. return _super !== null && _super.apply(this, arguments) || this;
  51499. }
  51500. QuinticEase.prototype.easeInCore = function (gradient) {
  51501. return (gradient * gradient * gradient * gradient * gradient);
  51502. };
  51503. return QuinticEase;
  51504. }(EasingFunction));
  51505. BABYLON.QuinticEase = QuinticEase;
  51506. var SineEase = /** @class */ (function (_super) {
  51507. __extends(SineEase, _super);
  51508. function SineEase() {
  51509. return _super !== null && _super.apply(this, arguments) || this;
  51510. }
  51511. SineEase.prototype.easeInCore = function (gradient) {
  51512. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51513. };
  51514. return SineEase;
  51515. }(EasingFunction));
  51516. BABYLON.SineEase = SineEase;
  51517. var BezierCurveEase = /** @class */ (function (_super) {
  51518. __extends(BezierCurveEase, _super);
  51519. function BezierCurveEase(x1, y1, x2, y2) {
  51520. if (x1 === void 0) { x1 = 0; }
  51521. if (y1 === void 0) { y1 = 0; }
  51522. if (x2 === void 0) { x2 = 1; }
  51523. if (y2 === void 0) { y2 = 1; }
  51524. var _this = _super.call(this) || this;
  51525. _this.x1 = x1;
  51526. _this.y1 = y1;
  51527. _this.x2 = x2;
  51528. _this.y2 = y2;
  51529. return _this;
  51530. }
  51531. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51532. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51533. };
  51534. return BezierCurveEase;
  51535. }(EasingFunction));
  51536. BABYLON.BezierCurveEase = BezierCurveEase;
  51537. })(BABYLON || (BABYLON = {}));
  51538. //# sourceMappingURL=babylon.easing.js.map
  51539. "use strict";
  51540. var BABYLON;
  51541. (function (BABYLON) {
  51542. /**
  51543. * A Condition applied to an Action
  51544. */
  51545. var Condition = /** @class */ (function () {
  51546. /**
  51547. * Creates a new Condition
  51548. * @param actionManager the manager of the action the condition is applied to
  51549. */
  51550. function Condition(actionManager) {
  51551. this._actionManager = actionManager;
  51552. }
  51553. /**
  51554. * Check if the current condition is valid
  51555. * @returns a boolean
  51556. */
  51557. Condition.prototype.isValid = function () {
  51558. return true;
  51559. };
  51560. /**
  51561. * Internal only
  51562. * @ignore
  51563. */
  51564. Condition.prototype._getProperty = function (propertyPath) {
  51565. return this._actionManager._getProperty(propertyPath);
  51566. };
  51567. /**
  51568. * Internal only
  51569. * @ignore
  51570. */
  51571. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51572. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51573. };
  51574. /**
  51575. * Serialize placeholder for child classes
  51576. * @returns the serialized object
  51577. */
  51578. Condition.prototype.serialize = function () {
  51579. };
  51580. /**
  51581. * Internal only
  51582. * @ignore
  51583. */
  51584. Condition.prototype._serialize = function (serializedCondition) {
  51585. return {
  51586. type: 2,
  51587. children: [],
  51588. name: serializedCondition.name,
  51589. properties: serializedCondition.properties
  51590. };
  51591. };
  51592. return Condition;
  51593. }());
  51594. BABYLON.Condition = Condition;
  51595. /**
  51596. * Defines specific conditional operators as extensions of Condition
  51597. */
  51598. var ValueCondition = /** @class */ (function (_super) {
  51599. __extends(ValueCondition, _super);
  51600. /**
  51601. * Creates a new ValueCondition
  51602. * @param actionManager manager for the action the condition applies to
  51603. * @param target for the action
  51604. * @param propertyPath path to specify the property of the target the conditional operator uses
  51605. * @param value the vale compared by the conditional operator against the current value of the property
  51606. * @param operator the conditional operator, default {BABYLON.ValueCondition.IsEqual}
  51607. */
  51608. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  51609. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51610. var _this = _super.call(this, actionManager) || this;
  51611. _this.propertyPath = propertyPath;
  51612. _this.value = value;
  51613. _this.operator = operator;
  51614. _this._target = target;
  51615. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51616. _this._property = _this._getProperty(_this.propertyPath);
  51617. return _this;
  51618. }
  51619. Object.defineProperty(ValueCondition, "IsEqual", {
  51620. /**
  51621. * returns the number for IsEqual
  51622. */
  51623. get: function () {
  51624. return ValueCondition._IsEqual;
  51625. },
  51626. enumerable: true,
  51627. configurable: true
  51628. });
  51629. Object.defineProperty(ValueCondition, "IsDifferent", {
  51630. /**
  51631. * Returns the number for IsDifferent
  51632. */
  51633. get: function () {
  51634. return ValueCondition._IsDifferent;
  51635. },
  51636. enumerable: true,
  51637. configurable: true
  51638. });
  51639. Object.defineProperty(ValueCondition, "IsGreater", {
  51640. /**
  51641. * Returns the number for IsGreater
  51642. */
  51643. get: function () {
  51644. return ValueCondition._IsGreater;
  51645. },
  51646. enumerable: true,
  51647. configurable: true
  51648. });
  51649. Object.defineProperty(ValueCondition, "IsLesser", {
  51650. /**
  51651. * Returns the number for IsLesser
  51652. */
  51653. get: function () {
  51654. return ValueCondition._IsLesser;
  51655. },
  51656. enumerable: true,
  51657. configurable: true
  51658. });
  51659. /**
  51660. * Compares the given value with the property value for the specified conditional operator
  51661. * @returns the result of the comparison
  51662. */
  51663. ValueCondition.prototype.isValid = function () {
  51664. switch (this.operator) {
  51665. case ValueCondition.IsGreater:
  51666. return this._effectiveTarget[this._property] > this.value;
  51667. case ValueCondition.IsLesser:
  51668. return this._effectiveTarget[this._property] < this.value;
  51669. case ValueCondition.IsEqual:
  51670. case ValueCondition.IsDifferent:
  51671. var check;
  51672. if (this.value.equals) {
  51673. check = this.value.equals(this._effectiveTarget[this._property]);
  51674. }
  51675. else {
  51676. check = this.value === this._effectiveTarget[this._property];
  51677. }
  51678. return this.operator === ValueCondition.IsEqual ? check : !check;
  51679. }
  51680. return false;
  51681. };
  51682. /**
  51683. * Serialize the ValueCondition into a JSON compatible object
  51684. * @returns serialization object
  51685. */
  51686. ValueCondition.prototype.serialize = function () {
  51687. return this._serialize({
  51688. name: "ValueCondition",
  51689. properties: [
  51690. BABYLON.Action._GetTargetProperty(this._target),
  51691. { name: "propertyPath", value: this.propertyPath },
  51692. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51693. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51694. ]
  51695. });
  51696. };
  51697. /**
  51698. * Gets the name of the conditional operator for the ValueCondition
  51699. * @param operator the conditional operator
  51700. * @returns the name
  51701. */
  51702. ValueCondition.GetOperatorName = function (operator) {
  51703. switch (operator) {
  51704. case ValueCondition._IsEqual: return "IsEqual";
  51705. case ValueCondition._IsDifferent: return "IsDifferent";
  51706. case ValueCondition._IsGreater: return "IsGreater";
  51707. case ValueCondition._IsLesser: return "IsLesser";
  51708. default: return "";
  51709. }
  51710. };
  51711. /**
  51712. * Internal only
  51713. * @ignore
  51714. */
  51715. ValueCondition._IsEqual = 0;
  51716. /**
  51717. * Internal only
  51718. * @ignore
  51719. */
  51720. ValueCondition._IsDifferent = 1;
  51721. /**
  51722. * Internal only
  51723. * @ignore
  51724. */
  51725. ValueCondition._IsGreater = 2;
  51726. /**
  51727. * Internal only
  51728. * @ignore
  51729. */
  51730. ValueCondition._IsLesser = 3;
  51731. return ValueCondition;
  51732. }(Condition));
  51733. BABYLON.ValueCondition = ValueCondition;
  51734. /**
  51735. * Defines a predicate condition as an extension of Condition
  51736. */
  51737. var PredicateCondition = /** @class */ (function (_super) {
  51738. __extends(PredicateCondition, _super);
  51739. /**
  51740. * Creates a new {BABYLON.PredicateCondition}
  51741. * @param actionManager manager for the action the condition applies to
  51742. * @param predicate
  51743. */
  51744. function PredicateCondition(actionManager, predicate) {
  51745. var _this = _super.call(this, actionManager) || this;
  51746. _this.predicate = predicate;
  51747. return _this;
  51748. }
  51749. /**
  51750. * @returns the validity of the predicate condition
  51751. */
  51752. PredicateCondition.prototype.isValid = function () {
  51753. return this.predicate();
  51754. };
  51755. return PredicateCondition;
  51756. }(Condition));
  51757. BABYLON.PredicateCondition = PredicateCondition;
  51758. /**
  51759. * Defines a state condition as an extension of {BABYLON.Condition}
  51760. */
  51761. var StateCondition = /** @class */ (function (_super) {
  51762. __extends(StateCondition, _super);
  51763. /**
  51764. * Creates a new {BABYLON.StateCondition}
  51765. * @param actionManager manager for the action the condition applies to
  51766. * @param target of the condition
  51767. * @param value to compare with target state
  51768. */
  51769. function StateCondition(actionManager, target, value) {
  51770. var _this = _super.call(this, actionManager) || this;
  51771. _this.value = value;
  51772. _this._target = target;
  51773. return _this;
  51774. }
  51775. /**
  51776. * @returns the validity of the state
  51777. */
  51778. StateCondition.prototype.isValid = function () {
  51779. return this._target.state === this.value;
  51780. };
  51781. /**
  51782. * Serialize the {BABYLON.StateCondition} into a JSON compatible object
  51783. * @returns serialization object
  51784. */
  51785. StateCondition.prototype.serialize = function () {
  51786. return this._serialize({
  51787. name: "StateCondition",
  51788. properties: [
  51789. BABYLON.Action._GetTargetProperty(this._target),
  51790. { name: "value", value: this.value }
  51791. ]
  51792. });
  51793. };
  51794. return StateCondition;
  51795. }(Condition));
  51796. BABYLON.StateCondition = StateCondition;
  51797. })(BABYLON || (BABYLON = {}));
  51798. //# sourceMappingURL=babylon.condition.js.map
  51799. "use strict";
  51800. var BABYLON;
  51801. (function (BABYLON) {
  51802. /**
  51803. * The action to be carried out following a trigger
  51804. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51805. */
  51806. var Action = /** @class */ (function () {
  51807. /**
  51808. * Creates a new Action
  51809. * @param triggerOptions the trigger, with or without parameters, for the action
  51810. * @param condition an optional determinant of action
  51811. */
  51812. function Action(triggerOptions, condition) {
  51813. this.triggerOptions = triggerOptions;
  51814. /**
  51815. * An event triggered prior to action being executed.
  51816. */
  51817. this.onBeforeExecuteObservable = new BABYLON.Observable();
  51818. if (triggerOptions.parameter) {
  51819. this.trigger = triggerOptions.trigger;
  51820. this._triggerParameter = triggerOptions.parameter;
  51821. }
  51822. else {
  51823. this.trigger = triggerOptions;
  51824. }
  51825. this._nextActiveAction = this;
  51826. this._condition = condition;
  51827. }
  51828. /**
  51829. * Internal only
  51830. * @ignore
  51831. */
  51832. Action.prototype._prepare = function () {
  51833. };
  51834. /**
  51835. * Gets the trigger parameters
  51836. * @returns the trigger parameters
  51837. */
  51838. Action.prototype.getTriggerParameter = function () {
  51839. return this._triggerParameter;
  51840. };
  51841. /**
  51842. * Internal only - executes current action event
  51843. * @ignore
  51844. */
  51845. Action.prototype._executeCurrent = function (evt) {
  51846. if (this._nextActiveAction._condition) {
  51847. var condition = this._nextActiveAction._condition;
  51848. var currentRenderId = this._actionManager.getScene().getRenderId();
  51849. // We cache the current evaluation for the current frame
  51850. if (condition._evaluationId === currentRenderId) {
  51851. if (!condition._currentResult) {
  51852. return;
  51853. }
  51854. }
  51855. else {
  51856. condition._evaluationId = currentRenderId;
  51857. if (!condition.isValid()) {
  51858. condition._currentResult = false;
  51859. return;
  51860. }
  51861. condition._currentResult = true;
  51862. }
  51863. }
  51864. this.onBeforeExecuteObservable.notifyObservers(this);
  51865. this._nextActiveAction.execute(evt);
  51866. this.skipToNextActiveAction();
  51867. };
  51868. /**
  51869. * Execute placeholder for child classes
  51870. * @param evt optional action event
  51871. */
  51872. Action.prototype.execute = function (evt) {
  51873. };
  51874. /**
  51875. * Skips to next active action
  51876. */
  51877. Action.prototype.skipToNextActiveAction = function () {
  51878. if (this._nextActiveAction._child) {
  51879. if (!this._nextActiveAction._child._actionManager) {
  51880. this._nextActiveAction._child._actionManager = this._actionManager;
  51881. }
  51882. this._nextActiveAction = this._nextActiveAction._child;
  51883. }
  51884. else {
  51885. this._nextActiveAction = this;
  51886. }
  51887. };
  51888. /**
  51889. * Adds action to chain of actions, may be a DoNothingAction
  51890. * @param index The index of the attribute.
  51891. * @returns The action passed in
  51892. * @see https://www.babylonjs-playground.com/#1T30HR#0
  51893. */
  51894. Action.prototype.then = function (action) {
  51895. this._child = action;
  51896. action._actionManager = this._actionManager;
  51897. action._prepare();
  51898. return action;
  51899. };
  51900. /**
  51901. * Internal only
  51902. * @ignore
  51903. */
  51904. Action.prototype._getProperty = function (propertyPath) {
  51905. return this._actionManager._getProperty(propertyPath);
  51906. };
  51907. /**
  51908. * Internal only
  51909. * @ignore
  51910. */
  51911. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  51912. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51913. };
  51914. /**
  51915. * Serialize placeholder for child classes
  51916. * @param parent of child
  51917. * @returns the serialized object
  51918. */
  51919. Action.prototype.serialize = function (parent) {
  51920. };
  51921. /**
  51922. * Internal only called by serialize
  51923. * @ignore
  51924. */
  51925. Action.prototype._serialize = function (serializedAction, parent) {
  51926. var serializationObject = {
  51927. type: 1,
  51928. children: [],
  51929. name: serializedAction.name,
  51930. properties: serializedAction.properties || []
  51931. };
  51932. // Serialize child
  51933. if (this._child) {
  51934. this._child.serialize(serializationObject);
  51935. }
  51936. // Check if "this" has a condition
  51937. if (this._condition) {
  51938. var serializedCondition = this._condition.serialize();
  51939. serializedCondition.children.push(serializationObject);
  51940. if (parent) {
  51941. parent.children.push(serializedCondition);
  51942. }
  51943. return serializedCondition;
  51944. }
  51945. if (parent) {
  51946. parent.children.push(serializationObject);
  51947. }
  51948. return serializationObject;
  51949. };
  51950. /**
  51951. * Internal only
  51952. * @ignore
  51953. */
  51954. Action._SerializeValueAsString = function (value) {
  51955. if (typeof value === "number") {
  51956. return value.toString();
  51957. }
  51958. if (typeof value === "boolean") {
  51959. return value ? "true" : "false";
  51960. }
  51961. if (value instanceof BABYLON.Vector2) {
  51962. return value.x + ", " + value.y;
  51963. }
  51964. if (value instanceof BABYLON.Vector3) {
  51965. return value.x + ", " + value.y + ", " + value.z;
  51966. }
  51967. if (value instanceof BABYLON.Color3) {
  51968. return value.r + ", " + value.g + ", " + value.b;
  51969. }
  51970. if (value instanceof BABYLON.Color4) {
  51971. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  51972. }
  51973. return value; // string
  51974. };
  51975. /**
  51976. * Internal only
  51977. * @ignore
  51978. */
  51979. Action._GetTargetProperty = function (target) {
  51980. return {
  51981. name: "target",
  51982. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  51983. : target instanceof BABYLON.Light ? "LightProperties"
  51984. : target instanceof BABYLON.Camera ? "CameraProperties"
  51985. : "SceneProperties",
  51986. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  51987. };
  51988. };
  51989. return Action;
  51990. }());
  51991. BABYLON.Action = Action;
  51992. })(BABYLON || (BABYLON = {}));
  51993. //# sourceMappingURL=babylon.action.js.map
  51994. "use strict";
  51995. var BABYLON;
  51996. (function (BABYLON) {
  51997. /**
  51998. * ActionEvent is the event being sent when an action is triggered.
  51999. */
  52000. var ActionEvent = /** @class */ (function () {
  52001. /**
  52002. * @param source The mesh or sprite that triggered the action.
  52003. * @param pointerX The X mouse cursor position at the time of the event
  52004. * @param pointerY The Y mouse cursor position at the time of the event
  52005. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52006. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52007. */
  52008. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  52009. this.source = source;
  52010. this.pointerX = pointerX;
  52011. this.pointerY = pointerY;
  52012. this.meshUnderPointer = meshUnderPointer;
  52013. this.sourceEvent = sourceEvent;
  52014. this.additionalData = additionalData;
  52015. }
  52016. /**
  52017. * Helper function to auto-create an ActionEvent from a source mesh.
  52018. * @param source The source mesh that triggered the event
  52019. * @param evt {Event} The original (browser) event
  52020. */
  52021. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52022. var scene = source.getScene();
  52023. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52024. };
  52025. /**
  52026. * Helper function to auto-create an ActionEvent from a source mesh.
  52027. * @param source The source sprite that triggered the event
  52028. * @param scene Scene associated with the sprite
  52029. * @param evt {Event} The original (browser) event
  52030. */
  52031. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52032. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52033. };
  52034. /**
  52035. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52036. * @param scene the scene where the event occurred
  52037. * @param evt {Event} The original (browser) event
  52038. */
  52039. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52040. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52041. };
  52042. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52043. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52044. };
  52045. return ActionEvent;
  52046. }());
  52047. BABYLON.ActionEvent = ActionEvent;
  52048. /**
  52049. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52050. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52051. */
  52052. var ActionManager = /** @class */ (function () {
  52053. function ActionManager(scene) {
  52054. // Members
  52055. this.actions = new Array();
  52056. this.hoverCursor = '';
  52057. this._scene = scene;
  52058. scene._actionManagers.push(this);
  52059. }
  52060. Object.defineProperty(ActionManager, "NothingTrigger", {
  52061. get: function () {
  52062. return ActionManager._NothingTrigger;
  52063. },
  52064. enumerable: true,
  52065. configurable: true
  52066. });
  52067. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52068. get: function () {
  52069. return ActionManager._OnPickTrigger;
  52070. },
  52071. enumerable: true,
  52072. configurable: true
  52073. });
  52074. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52075. get: function () {
  52076. return ActionManager._OnLeftPickTrigger;
  52077. },
  52078. enumerable: true,
  52079. configurable: true
  52080. });
  52081. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52082. get: function () {
  52083. return ActionManager._OnRightPickTrigger;
  52084. },
  52085. enumerable: true,
  52086. configurable: true
  52087. });
  52088. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52089. get: function () {
  52090. return ActionManager._OnCenterPickTrigger;
  52091. },
  52092. enumerable: true,
  52093. configurable: true
  52094. });
  52095. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52096. get: function () {
  52097. return ActionManager._OnPickDownTrigger;
  52098. },
  52099. enumerable: true,
  52100. configurable: true
  52101. });
  52102. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52103. get: function () {
  52104. return ActionManager._OnDoublePickTrigger;
  52105. },
  52106. enumerable: true,
  52107. configurable: true
  52108. });
  52109. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52110. get: function () {
  52111. return ActionManager._OnPickUpTrigger;
  52112. },
  52113. enumerable: true,
  52114. configurable: true
  52115. });
  52116. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52117. /// This trigger will only be raised if you also declared a OnPickDown
  52118. get: function () {
  52119. return ActionManager._OnPickOutTrigger;
  52120. },
  52121. enumerable: true,
  52122. configurable: true
  52123. });
  52124. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52125. get: function () {
  52126. return ActionManager._OnLongPressTrigger;
  52127. },
  52128. enumerable: true,
  52129. configurable: true
  52130. });
  52131. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52132. get: function () {
  52133. return ActionManager._OnPointerOverTrigger;
  52134. },
  52135. enumerable: true,
  52136. configurable: true
  52137. });
  52138. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52139. get: function () {
  52140. return ActionManager._OnPointerOutTrigger;
  52141. },
  52142. enumerable: true,
  52143. configurable: true
  52144. });
  52145. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52146. get: function () {
  52147. return ActionManager._OnEveryFrameTrigger;
  52148. },
  52149. enumerable: true,
  52150. configurable: true
  52151. });
  52152. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52153. get: function () {
  52154. return ActionManager._OnIntersectionEnterTrigger;
  52155. },
  52156. enumerable: true,
  52157. configurable: true
  52158. });
  52159. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52160. get: function () {
  52161. return ActionManager._OnIntersectionExitTrigger;
  52162. },
  52163. enumerable: true,
  52164. configurable: true
  52165. });
  52166. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52167. get: function () {
  52168. return ActionManager._OnKeyDownTrigger;
  52169. },
  52170. enumerable: true,
  52171. configurable: true
  52172. });
  52173. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52174. get: function () {
  52175. return ActionManager._OnKeyUpTrigger;
  52176. },
  52177. enumerable: true,
  52178. configurable: true
  52179. });
  52180. // Methods
  52181. ActionManager.prototype.dispose = function () {
  52182. var index = this._scene._actionManagers.indexOf(this);
  52183. for (var i = 0; i < this.actions.length; i++) {
  52184. var action = this.actions[i];
  52185. ActionManager.Triggers[action.trigger]--;
  52186. if (ActionManager.Triggers[action.trigger] === 0) {
  52187. delete ActionManager.Triggers[action.trigger];
  52188. }
  52189. }
  52190. if (index > -1) {
  52191. this._scene._actionManagers.splice(index, 1);
  52192. }
  52193. };
  52194. ActionManager.prototype.getScene = function () {
  52195. return this._scene;
  52196. };
  52197. /**
  52198. * Does this action manager handles actions of any of the given triggers
  52199. * @param {number[]} triggers - the triggers to be tested
  52200. * @return {boolean} whether one (or more) of the triggers is handeled
  52201. */
  52202. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52203. for (var index = 0; index < this.actions.length; index++) {
  52204. var action = this.actions[index];
  52205. if (triggers.indexOf(action.trigger) > -1) {
  52206. return true;
  52207. }
  52208. }
  52209. return false;
  52210. };
  52211. /**
  52212. * Does this action manager handles actions of a given trigger
  52213. * @param trigger defines the trigger to be tested
  52214. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52215. * @return whether the trigger is handled
  52216. */
  52217. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52218. for (var index = 0; index < this.actions.length; index++) {
  52219. var action = this.actions[index];
  52220. if (action.trigger === trigger) {
  52221. if (parameterPredicate) {
  52222. if (parameterPredicate(action.getTriggerParameter())) {
  52223. return true;
  52224. }
  52225. }
  52226. else {
  52227. return true;
  52228. }
  52229. }
  52230. }
  52231. return false;
  52232. };
  52233. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52234. /**
  52235. * Does this action manager has pointer triggers
  52236. * @return {boolean} whether or not it has pointer triggers
  52237. */
  52238. get: function () {
  52239. for (var index = 0; index < this.actions.length; index++) {
  52240. var action = this.actions[index];
  52241. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52242. return true;
  52243. }
  52244. }
  52245. return false;
  52246. },
  52247. enumerable: true,
  52248. configurable: true
  52249. });
  52250. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52251. /**
  52252. * Does this action manager has pick triggers
  52253. * @return {boolean} whether or not it has pick triggers
  52254. */
  52255. get: function () {
  52256. for (var index = 0; index < this.actions.length; index++) {
  52257. var action = this.actions[index];
  52258. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52259. return true;
  52260. }
  52261. }
  52262. return false;
  52263. },
  52264. enumerable: true,
  52265. configurable: true
  52266. });
  52267. Object.defineProperty(ActionManager, "HasTriggers", {
  52268. /**
  52269. * Does exist one action manager with at least one trigger
  52270. * @return {boolean} whether or not it exists one action manager with one trigger
  52271. **/
  52272. get: function () {
  52273. for (var t in ActionManager.Triggers) {
  52274. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52275. return true;
  52276. }
  52277. }
  52278. return false;
  52279. },
  52280. enumerable: true,
  52281. configurable: true
  52282. });
  52283. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52284. /**
  52285. * Does exist one action manager with at least one pick trigger
  52286. * @return {boolean} whether or not it exists one action manager with one pick trigger
  52287. **/
  52288. get: function () {
  52289. for (var t in ActionManager.Triggers) {
  52290. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52291. var t_int = parseInt(t);
  52292. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52293. return true;
  52294. }
  52295. }
  52296. }
  52297. return false;
  52298. },
  52299. enumerable: true,
  52300. configurable: true
  52301. });
  52302. /**
  52303. * Does exist one action manager that handles actions of a given trigger
  52304. * @param {number} trigger - the trigger to be tested
  52305. * @return {boolean} whether the trigger is handeled by at least one action manager
  52306. **/
  52307. ActionManager.HasSpecificTrigger = function (trigger) {
  52308. for (var t in ActionManager.Triggers) {
  52309. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52310. var t_int = parseInt(t);
  52311. if (t_int === trigger) {
  52312. return true;
  52313. }
  52314. }
  52315. }
  52316. return false;
  52317. };
  52318. /**
  52319. * Registers an action to this action manager
  52320. * @param {BABYLON.Action} action - the action to be registered
  52321. * @return {BABYLON.Action} the action amended (prepared) after registration
  52322. */
  52323. ActionManager.prototype.registerAction = function (action) {
  52324. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52325. if (this.getScene().actionManager !== this) {
  52326. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52327. return null;
  52328. }
  52329. }
  52330. this.actions.push(action);
  52331. if (ActionManager.Triggers[action.trigger]) {
  52332. ActionManager.Triggers[action.trigger]++;
  52333. }
  52334. else {
  52335. ActionManager.Triggers[action.trigger] = 1;
  52336. }
  52337. action._actionManager = this;
  52338. action._prepare();
  52339. return action;
  52340. };
  52341. /**
  52342. * Unregisters an action to this action manager
  52343. * @param action The action to be unregistered
  52344. * @return whether the action has been unregistered
  52345. */
  52346. ActionManager.prototype.unregisterAction = function (action) {
  52347. var index = this.actions.indexOf(action);
  52348. if (index !== -1) {
  52349. this.actions.splice(index, 1);
  52350. ActionManager.Triggers[action.trigger] -= 1;
  52351. if (ActionManager.Triggers[action.trigger] === 0) {
  52352. delete ActionManager.Triggers[action.trigger];
  52353. }
  52354. delete action._actionManager;
  52355. return true;
  52356. }
  52357. return false;
  52358. };
  52359. /**
  52360. * Process a specific trigger
  52361. * @param {number} trigger - the trigger to process
  52362. * @param evt {BABYLON.ActionEvent} the event details to be processed
  52363. */
  52364. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52365. for (var index = 0; index < this.actions.length; index++) {
  52366. var action = this.actions[index];
  52367. if (action.trigger === trigger) {
  52368. if (evt) {
  52369. if (trigger === ActionManager.OnKeyUpTrigger
  52370. || trigger === ActionManager.OnKeyDownTrigger) {
  52371. var parameter = action.getTriggerParameter();
  52372. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52373. if (!parameter.toLowerCase) {
  52374. continue;
  52375. }
  52376. var lowerCase = parameter.toLowerCase();
  52377. if (lowerCase !== evt.sourceEvent.key) {
  52378. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52379. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52380. if (actualkey !== lowerCase) {
  52381. continue;
  52382. }
  52383. }
  52384. }
  52385. }
  52386. }
  52387. action._executeCurrent(evt);
  52388. }
  52389. }
  52390. };
  52391. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52392. var properties = propertyPath.split(".");
  52393. for (var index = 0; index < properties.length - 1; index++) {
  52394. target = target[properties[index]];
  52395. }
  52396. return target;
  52397. };
  52398. ActionManager.prototype._getProperty = function (propertyPath) {
  52399. var properties = propertyPath.split(".");
  52400. return properties[properties.length - 1];
  52401. };
  52402. ActionManager.prototype.serialize = function (name) {
  52403. var root = {
  52404. children: new Array(),
  52405. name: name,
  52406. type: 3,
  52407. properties: new Array() // Empty for root but required
  52408. };
  52409. for (var i = 0; i < this.actions.length; i++) {
  52410. var triggerObject = {
  52411. type: 0,
  52412. children: new Array(),
  52413. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52414. properties: new Array()
  52415. };
  52416. var triggerOptions = this.actions[i].triggerOptions;
  52417. if (triggerOptions && typeof triggerOptions !== "number") {
  52418. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52419. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52420. }
  52421. else {
  52422. var parameter = {};
  52423. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52424. if (triggerOptions.parameter.mesh) {
  52425. parameter._meshId = triggerOptions.parameter.mesh.id;
  52426. }
  52427. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52428. }
  52429. }
  52430. // Serialize child action, recursively
  52431. this.actions[i].serialize(triggerObject);
  52432. // Add serialized trigger
  52433. root.children.push(triggerObject);
  52434. }
  52435. return root;
  52436. };
  52437. ActionManager.Parse = function (parsedActions, object, scene) {
  52438. var actionManager = new ActionManager(scene);
  52439. if (object === null)
  52440. scene.actionManager = actionManager;
  52441. else
  52442. object.actionManager = actionManager;
  52443. // instanciate a new object
  52444. var instanciate = function (name, params) {
  52445. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52446. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52447. newInstance.constructor.apply(newInstance, params);
  52448. return newInstance;
  52449. };
  52450. var parseParameter = function (name, value, target, propertyPath) {
  52451. if (propertyPath === null) {
  52452. // String, boolean or float
  52453. var floatValue = parseFloat(value);
  52454. if (value === "true" || value === "false")
  52455. return value === "true";
  52456. else
  52457. return isNaN(floatValue) ? value : floatValue;
  52458. }
  52459. var effectiveTarget = propertyPath.split(".");
  52460. var values = value.split(",");
  52461. // Get effective Target
  52462. for (var i = 0; i < effectiveTarget.length; i++) {
  52463. target = target[effectiveTarget[i]];
  52464. }
  52465. // Return appropriate value with its type
  52466. if (typeof (target) === "boolean")
  52467. return values[0] === "true";
  52468. if (typeof (target) === "string")
  52469. return values[0];
  52470. // Parameters with multiple values such as Vector3 etc.
  52471. var split = new Array();
  52472. for (var i = 0; i < values.length; i++)
  52473. split.push(parseFloat(values[i]));
  52474. if (target instanceof BABYLON.Vector3)
  52475. return BABYLON.Vector3.FromArray(split);
  52476. if (target instanceof BABYLON.Vector4)
  52477. return BABYLON.Vector4.FromArray(split);
  52478. if (target instanceof BABYLON.Color3)
  52479. return BABYLON.Color3.FromArray(split);
  52480. if (target instanceof BABYLON.Color4)
  52481. return BABYLON.Color4.FromArray(split);
  52482. return parseFloat(values[0]);
  52483. };
  52484. // traverse graph per trigger
  52485. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52486. if (combineArray === void 0) { combineArray = null; }
  52487. if (parsedAction.detached)
  52488. return;
  52489. var parameters = new Array();
  52490. var target = null;
  52491. var propertyPath = null;
  52492. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52493. // Parameters
  52494. if (parsedAction.type === 2)
  52495. parameters.push(actionManager);
  52496. else
  52497. parameters.push(trigger);
  52498. if (combine) {
  52499. var actions = new Array();
  52500. for (var j = 0; j < parsedAction.combine.length; j++) {
  52501. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52502. }
  52503. parameters.push(actions);
  52504. }
  52505. else {
  52506. for (var i = 0; i < parsedAction.properties.length; i++) {
  52507. var value = parsedAction.properties[i].value;
  52508. var name = parsedAction.properties[i].name;
  52509. var targetType = parsedAction.properties[i].targetType;
  52510. if (name === "target")
  52511. if (targetType !== null && targetType === "SceneProperties")
  52512. value = target = scene;
  52513. else
  52514. value = target = scene.getNodeByName(value);
  52515. else if (name === "parent")
  52516. value = scene.getNodeByName(value);
  52517. else if (name === "sound")
  52518. value = scene.getSoundByName(value);
  52519. else if (name !== "propertyPath") {
  52520. if (parsedAction.type === 2 && name === "operator")
  52521. value = BABYLON.ValueCondition[value];
  52522. else
  52523. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52524. }
  52525. else {
  52526. propertyPath = value;
  52527. }
  52528. parameters.push(value);
  52529. }
  52530. }
  52531. if (combineArray === null) {
  52532. parameters.push(condition);
  52533. }
  52534. else {
  52535. parameters.push(null);
  52536. }
  52537. // If interpolate value action
  52538. if (parsedAction.name === "InterpolateValueAction") {
  52539. var param = parameters[parameters.length - 2];
  52540. parameters[parameters.length - 1] = param;
  52541. parameters[parameters.length - 2] = condition;
  52542. }
  52543. // Action or condition(s) and not CombineAction
  52544. var newAction = instanciate(parsedAction.name, parameters);
  52545. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52546. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52547. if (action)
  52548. action.then(nothing);
  52549. else
  52550. actionManager.registerAction(nothing);
  52551. action = nothing;
  52552. }
  52553. if (combineArray === null) {
  52554. if (newAction instanceof BABYLON.Condition) {
  52555. condition = newAction;
  52556. newAction = action;
  52557. }
  52558. else {
  52559. condition = null;
  52560. if (action)
  52561. action.then(newAction);
  52562. else
  52563. actionManager.registerAction(newAction);
  52564. }
  52565. }
  52566. else {
  52567. combineArray.push(newAction);
  52568. }
  52569. for (var i = 0; i < parsedAction.children.length; i++)
  52570. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52571. };
  52572. // triggers
  52573. for (var i = 0; i < parsedActions.children.length; i++) {
  52574. var triggerParams;
  52575. var trigger = parsedActions.children[i];
  52576. if (trigger.properties.length > 0) {
  52577. var param = trigger.properties[0].value;
  52578. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52579. if (value._meshId) {
  52580. value.mesh = scene.getMeshByID(value._meshId);
  52581. }
  52582. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52583. }
  52584. else
  52585. triggerParams = ActionManager[trigger.name];
  52586. for (var j = 0; j < trigger.children.length; j++) {
  52587. if (!trigger.detached)
  52588. traverse(trigger.children[j], triggerParams, null, null);
  52589. }
  52590. }
  52591. };
  52592. ActionManager.GetTriggerName = function (trigger) {
  52593. switch (trigger) {
  52594. case 0: return "NothingTrigger";
  52595. case 1: return "OnPickTrigger";
  52596. case 2: return "OnLeftPickTrigger";
  52597. case 3: return "OnRightPickTrigger";
  52598. case 4: return "OnCenterPickTrigger";
  52599. case 5: return "OnPickDownTrigger";
  52600. case 6: return "OnPickUpTrigger";
  52601. case 7: return "OnLongPressTrigger";
  52602. case 8: return "OnPointerOverTrigger";
  52603. case 9: return "OnPointerOutTrigger";
  52604. case 10: return "OnEveryFrameTrigger";
  52605. case 11: return "OnIntersectionEnterTrigger";
  52606. case 12: return "OnIntersectionExitTrigger";
  52607. case 13: return "OnKeyDownTrigger";
  52608. case 14: return "OnKeyUpTrigger";
  52609. case 15: return "OnPickOutTrigger";
  52610. default: return "";
  52611. }
  52612. };
  52613. // Statics
  52614. ActionManager._NothingTrigger = 0;
  52615. ActionManager._OnPickTrigger = 1;
  52616. ActionManager._OnLeftPickTrigger = 2;
  52617. ActionManager._OnRightPickTrigger = 3;
  52618. ActionManager._OnCenterPickTrigger = 4;
  52619. ActionManager._OnPickDownTrigger = 5;
  52620. ActionManager._OnDoublePickTrigger = 6;
  52621. ActionManager._OnPickUpTrigger = 7;
  52622. ActionManager._OnLongPressTrigger = 8;
  52623. ActionManager._OnPointerOverTrigger = 9;
  52624. ActionManager._OnPointerOutTrigger = 10;
  52625. ActionManager._OnEveryFrameTrigger = 11;
  52626. ActionManager._OnIntersectionEnterTrigger = 12;
  52627. ActionManager._OnIntersectionExitTrigger = 13;
  52628. ActionManager._OnKeyDownTrigger = 14;
  52629. ActionManager._OnKeyUpTrigger = 15;
  52630. ActionManager._OnPickOutTrigger = 16;
  52631. ActionManager.Triggers = {};
  52632. return ActionManager;
  52633. }());
  52634. BABYLON.ActionManager = ActionManager;
  52635. })(BABYLON || (BABYLON = {}));
  52636. //# sourceMappingURL=babylon.actionManager.js.map
  52637. "use strict";
  52638. var BABYLON;
  52639. (function (BABYLON) {
  52640. var InterpolateValueAction = /** @class */ (function (_super) {
  52641. __extends(InterpolateValueAction, _super);
  52642. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52643. if (duration === void 0) { duration = 1000; }
  52644. var _this = _super.call(this, triggerOptions, condition) || this;
  52645. _this.propertyPath = propertyPath;
  52646. _this.value = value;
  52647. _this.duration = duration;
  52648. _this.stopOtherAnimations = stopOtherAnimations;
  52649. _this.onInterpolationDone = onInterpolationDone;
  52650. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52651. _this._target = _this._effectiveTarget = target;
  52652. return _this;
  52653. }
  52654. InterpolateValueAction.prototype._prepare = function () {
  52655. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52656. this._property = this._getProperty(this.propertyPath);
  52657. };
  52658. InterpolateValueAction.prototype.execute = function () {
  52659. var _this = this;
  52660. var scene = this._actionManager.getScene();
  52661. var keys = [
  52662. {
  52663. frame: 0,
  52664. value: this._effectiveTarget[this._property]
  52665. }, {
  52666. frame: 100,
  52667. value: this.value
  52668. }
  52669. ];
  52670. var dataType;
  52671. if (typeof this.value === "number") {
  52672. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  52673. }
  52674. else if (this.value instanceof BABYLON.Color3) {
  52675. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  52676. }
  52677. else if (this.value instanceof BABYLON.Vector3) {
  52678. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  52679. }
  52680. else if (this.value instanceof BABYLON.Matrix) {
  52681. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  52682. }
  52683. else if (this.value instanceof BABYLON.Quaternion) {
  52684. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  52685. }
  52686. else {
  52687. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  52688. return;
  52689. }
  52690. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  52691. animation.setKeys(keys);
  52692. if (this.stopOtherAnimations) {
  52693. scene.stopAnimation(this._effectiveTarget);
  52694. }
  52695. var wrapper = function () {
  52696. _this.onInterpolationDoneObservable.notifyObservers(_this);
  52697. if (_this.onInterpolationDone) {
  52698. _this.onInterpolationDone();
  52699. }
  52700. };
  52701. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  52702. };
  52703. InterpolateValueAction.prototype.serialize = function (parent) {
  52704. return _super.prototype._serialize.call(this, {
  52705. name: "InterpolateValueAction",
  52706. properties: [
  52707. BABYLON.Action._GetTargetProperty(this._target),
  52708. { name: "propertyPath", value: this.propertyPath },
  52709. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52710. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  52711. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  52712. ]
  52713. }, parent);
  52714. };
  52715. return InterpolateValueAction;
  52716. }(BABYLON.Action));
  52717. BABYLON.InterpolateValueAction = InterpolateValueAction;
  52718. })(BABYLON || (BABYLON = {}));
  52719. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  52720. "use strict";
  52721. var BABYLON;
  52722. (function (BABYLON) {
  52723. var SwitchBooleanAction = /** @class */ (function (_super) {
  52724. __extends(SwitchBooleanAction, _super);
  52725. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  52726. var _this = _super.call(this, triggerOptions, condition) || this;
  52727. _this.propertyPath = propertyPath;
  52728. _this._target = _this._effectiveTarget = target;
  52729. return _this;
  52730. }
  52731. SwitchBooleanAction.prototype._prepare = function () {
  52732. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52733. this._property = this._getProperty(this.propertyPath);
  52734. };
  52735. SwitchBooleanAction.prototype.execute = function () {
  52736. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  52737. };
  52738. SwitchBooleanAction.prototype.serialize = function (parent) {
  52739. return _super.prototype._serialize.call(this, {
  52740. name: "SwitchBooleanAction",
  52741. properties: [
  52742. BABYLON.Action._GetTargetProperty(this._target),
  52743. { name: "propertyPath", value: this.propertyPath }
  52744. ]
  52745. }, parent);
  52746. };
  52747. return SwitchBooleanAction;
  52748. }(BABYLON.Action));
  52749. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  52750. var SetStateAction = /** @class */ (function (_super) {
  52751. __extends(SetStateAction, _super);
  52752. function SetStateAction(triggerOptions, target, value, condition) {
  52753. var _this = _super.call(this, triggerOptions, condition) || this;
  52754. _this.value = value;
  52755. _this._target = target;
  52756. return _this;
  52757. }
  52758. SetStateAction.prototype.execute = function () {
  52759. this._target.state = this.value;
  52760. };
  52761. SetStateAction.prototype.serialize = function (parent) {
  52762. return _super.prototype._serialize.call(this, {
  52763. name: "SetStateAction",
  52764. properties: [
  52765. BABYLON.Action._GetTargetProperty(this._target),
  52766. { name: "value", value: this.value }
  52767. ]
  52768. }, parent);
  52769. };
  52770. return SetStateAction;
  52771. }(BABYLON.Action));
  52772. BABYLON.SetStateAction = SetStateAction;
  52773. var SetValueAction = /** @class */ (function (_super) {
  52774. __extends(SetValueAction, _super);
  52775. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  52776. var _this = _super.call(this, triggerOptions, condition) || this;
  52777. _this.propertyPath = propertyPath;
  52778. _this.value = value;
  52779. _this._target = _this._effectiveTarget = target;
  52780. return _this;
  52781. }
  52782. SetValueAction.prototype._prepare = function () {
  52783. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52784. this._property = this._getProperty(this.propertyPath);
  52785. };
  52786. SetValueAction.prototype.execute = function () {
  52787. this._effectiveTarget[this._property] = this.value;
  52788. if (this._target.markAsDirty) {
  52789. this._target.markAsDirty(this._property);
  52790. }
  52791. };
  52792. SetValueAction.prototype.serialize = function (parent) {
  52793. return _super.prototype._serialize.call(this, {
  52794. name: "SetValueAction",
  52795. properties: [
  52796. BABYLON.Action._GetTargetProperty(this._target),
  52797. { name: "propertyPath", value: this.propertyPath },
  52798. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52799. ]
  52800. }, parent);
  52801. };
  52802. return SetValueAction;
  52803. }(BABYLON.Action));
  52804. BABYLON.SetValueAction = SetValueAction;
  52805. var IncrementValueAction = /** @class */ (function (_super) {
  52806. __extends(IncrementValueAction, _super);
  52807. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  52808. var _this = _super.call(this, triggerOptions, condition) || this;
  52809. _this.propertyPath = propertyPath;
  52810. _this.value = value;
  52811. _this._target = _this._effectiveTarget = target;
  52812. return _this;
  52813. }
  52814. IncrementValueAction.prototype._prepare = function () {
  52815. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52816. this._property = this._getProperty(this.propertyPath);
  52817. if (typeof this._effectiveTarget[this._property] !== "number") {
  52818. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  52819. }
  52820. };
  52821. IncrementValueAction.prototype.execute = function () {
  52822. this._effectiveTarget[this._property] += this.value;
  52823. if (this._target.markAsDirty) {
  52824. this._target.markAsDirty(this._property);
  52825. }
  52826. };
  52827. IncrementValueAction.prototype.serialize = function (parent) {
  52828. return _super.prototype._serialize.call(this, {
  52829. name: "IncrementValueAction",
  52830. properties: [
  52831. BABYLON.Action._GetTargetProperty(this._target),
  52832. { name: "propertyPath", value: this.propertyPath },
  52833. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52834. ]
  52835. }, parent);
  52836. };
  52837. return IncrementValueAction;
  52838. }(BABYLON.Action));
  52839. BABYLON.IncrementValueAction = IncrementValueAction;
  52840. var PlayAnimationAction = /** @class */ (function (_super) {
  52841. __extends(PlayAnimationAction, _super);
  52842. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  52843. var _this = _super.call(this, triggerOptions, condition) || this;
  52844. _this.from = from;
  52845. _this.to = to;
  52846. _this.loop = loop;
  52847. _this._target = target;
  52848. return _this;
  52849. }
  52850. PlayAnimationAction.prototype._prepare = function () {
  52851. };
  52852. PlayAnimationAction.prototype.execute = function () {
  52853. var scene = this._actionManager.getScene();
  52854. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  52855. };
  52856. PlayAnimationAction.prototype.serialize = function (parent) {
  52857. return _super.prototype._serialize.call(this, {
  52858. name: "PlayAnimationAction",
  52859. properties: [
  52860. BABYLON.Action._GetTargetProperty(this._target),
  52861. { name: "from", value: String(this.from) },
  52862. { name: "to", value: String(this.to) },
  52863. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  52864. ]
  52865. }, parent);
  52866. };
  52867. return PlayAnimationAction;
  52868. }(BABYLON.Action));
  52869. BABYLON.PlayAnimationAction = PlayAnimationAction;
  52870. var StopAnimationAction = /** @class */ (function (_super) {
  52871. __extends(StopAnimationAction, _super);
  52872. function StopAnimationAction(triggerOptions, target, condition) {
  52873. var _this = _super.call(this, triggerOptions, condition) || this;
  52874. _this._target = target;
  52875. return _this;
  52876. }
  52877. StopAnimationAction.prototype._prepare = function () {
  52878. };
  52879. StopAnimationAction.prototype.execute = function () {
  52880. var scene = this._actionManager.getScene();
  52881. scene.stopAnimation(this._target);
  52882. };
  52883. StopAnimationAction.prototype.serialize = function (parent) {
  52884. return _super.prototype._serialize.call(this, {
  52885. name: "StopAnimationAction",
  52886. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  52887. }, parent);
  52888. };
  52889. return StopAnimationAction;
  52890. }(BABYLON.Action));
  52891. BABYLON.StopAnimationAction = StopAnimationAction;
  52892. var DoNothingAction = /** @class */ (function (_super) {
  52893. __extends(DoNothingAction, _super);
  52894. function DoNothingAction(triggerOptions, condition) {
  52895. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  52896. return _super.call(this, triggerOptions, condition) || this;
  52897. }
  52898. DoNothingAction.prototype.execute = function () {
  52899. };
  52900. DoNothingAction.prototype.serialize = function (parent) {
  52901. return _super.prototype._serialize.call(this, {
  52902. name: "DoNothingAction",
  52903. properties: []
  52904. }, parent);
  52905. };
  52906. return DoNothingAction;
  52907. }(BABYLON.Action));
  52908. BABYLON.DoNothingAction = DoNothingAction;
  52909. var CombineAction = /** @class */ (function (_super) {
  52910. __extends(CombineAction, _super);
  52911. function CombineAction(triggerOptions, children, condition) {
  52912. var _this = _super.call(this, triggerOptions, condition) || this;
  52913. _this.children = children;
  52914. return _this;
  52915. }
  52916. CombineAction.prototype._prepare = function () {
  52917. for (var index = 0; index < this.children.length; index++) {
  52918. this.children[index]._actionManager = this._actionManager;
  52919. this.children[index]._prepare();
  52920. }
  52921. };
  52922. CombineAction.prototype.execute = function (evt) {
  52923. for (var index = 0; index < this.children.length; index++) {
  52924. this.children[index].execute(evt);
  52925. }
  52926. };
  52927. CombineAction.prototype.serialize = function (parent) {
  52928. var serializationObject = _super.prototype._serialize.call(this, {
  52929. name: "CombineAction",
  52930. properties: [],
  52931. combine: []
  52932. }, parent);
  52933. for (var i = 0; i < this.children.length; i++) {
  52934. serializationObject.combine.push(this.children[i].serialize(null));
  52935. }
  52936. return serializationObject;
  52937. };
  52938. return CombineAction;
  52939. }(BABYLON.Action));
  52940. BABYLON.CombineAction = CombineAction;
  52941. var ExecuteCodeAction = /** @class */ (function (_super) {
  52942. __extends(ExecuteCodeAction, _super);
  52943. function ExecuteCodeAction(triggerOptions, func, condition) {
  52944. var _this = _super.call(this, triggerOptions, condition) || this;
  52945. _this.func = func;
  52946. return _this;
  52947. }
  52948. ExecuteCodeAction.prototype.execute = function (evt) {
  52949. this.func(evt);
  52950. };
  52951. return ExecuteCodeAction;
  52952. }(BABYLON.Action));
  52953. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  52954. var SetParentAction = /** @class */ (function (_super) {
  52955. __extends(SetParentAction, _super);
  52956. function SetParentAction(triggerOptions, target, parent, condition) {
  52957. var _this = _super.call(this, triggerOptions, condition) || this;
  52958. _this._target = target;
  52959. _this._parent = parent;
  52960. return _this;
  52961. }
  52962. SetParentAction.prototype._prepare = function () {
  52963. };
  52964. SetParentAction.prototype.execute = function () {
  52965. if (this._target.parent === this._parent) {
  52966. return;
  52967. }
  52968. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  52969. invertParentWorldMatrix.invert();
  52970. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  52971. this._target.parent = this._parent;
  52972. };
  52973. SetParentAction.prototype.serialize = function (parent) {
  52974. return _super.prototype._serialize.call(this, {
  52975. name: "SetParentAction",
  52976. properties: [
  52977. BABYLON.Action._GetTargetProperty(this._target),
  52978. BABYLON.Action._GetTargetProperty(this._parent),
  52979. ]
  52980. }, parent);
  52981. };
  52982. return SetParentAction;
  52983. }(BABYLON.Action));
  52984. BABYLON.SetParentAction = SetParentAction;
  52985. var PlaySoundAction = /** @class */ (function (_super) {
  52986. __extends(PlaySoundAction, _super);
  52987. function PlaySoundAction(triggerOptions, sound, condition) {
  52988. var _this = _super.call(this, triggerOptions, condition) || this;
  52989. _this._sound = sound;
  52990. return _this;
  52991. }
  52992. PlaySoundAction.prototype._prepare = function () {
  52993. };
  52994. PlaySoundAction.prototype.execute = function () {
  52995. if (this._sound !== undefined)
  52996. this._sound.play();
  52997. };
  52998. PlaySoundAction.prototype.serialize = function (parent) {
  52999. return _super.prototype._serialize.call(this, {
  53000. name: "PlaySoundAction",
  53001. properties: [{ name: "sound", value: this._sound.name }]
  53002. }, parent);
  53003. };
  53004. return PlaySoundAction;
  53005. }(BABYLON.Action));
  53006. BABYLON.PlaySoundAction = PlaySoundAction;
  53007. var StopSoundAction = /** @class */ (function (_super) {
  53008. __extends(StopSoundAction, _super);
  53009. function StopSoundAction(triggerOptions, sound, condition) {
  53010. var _this = _super.call(this, triggerOptions, condition) || this;
  53011. _this._sound = sound;
  53012. return _this;
  53013. }
  53014. StopSoundAction.prototype._prepare = function () {
  53015. };
  53016. StopSoundAction.prototype.execute = function () {
  53017. if (this._sound !== undefined)
  53018. this._sound.stop();
  53019. };
  53020. StopSoundAction.prototype.serialize = function (parent) {
  53021. return _super.prototype._serialize.call(this, {
  53022. name: "StopSoundAction",
  53023. properties: [{ name: "sound", value: this._sound.name }]
  53024. }, parent);
  53025. };
  53026. return StopSoundAction;
  53027. }(BABYLON.Action));
  53028. BABYLON.StopSoundAction = StopSoundAction;
  53029. })(BABYLON || (BABYLON = {}));
  53030. //# sourceMappingURL=babylon.directActions.js.map
  53031. "use strict";
  53032. var BABYLON;
  53033. (function (BABYLON) {
  53034. var SpriteManager = /** @class */ (function () {
  53035. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53036. if (epsilon === void 0) { epsilon = 0.01; }
  53037. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53038. this.name = name;
  53039. this.sprites = new Array();
  53040. this.renderingGroupId = 0;
  53041. this.layerMask = 0x0FFFFFFF;
  53042. this.fogEnabled = true;
  53043. this.isPickable = false;
  53044. /**
  53045. * An event triggered when the manager is disposed.
  53046. */
  53047. this.onDisposeObservable = new BABYLON.Observable();
  53048. this._vertexBuffers = {};
  53049. this._capacity = capacity;
  53050. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53051. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53052. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53053. if (cellSize.width && cellSize.height) {
  53054. this.cellWidth = cellSize.width;
  53055. this.cellHeight = cellSize.height;
  53056. }
  53057. else if (cellSize !== undefined) {
  53058. this.cellWidth = cellSize;
  53059. this.cellHeight = cellSize;
  53060. }
  53061. else {
  53062. return;
  53063. }
  53064. this._epsilon = epsilon;
  53065. this._scene = scene;
  53066. this._scene.spriteManagers.push(this);
  53067. var indices = [];
  53068. var index = 0;
  53069. for (var count = 0; count < capacity; count++) {
  53070. indices.push(index);
  53071. indices.push(index + 1);
  53072. indices.push(index + 2);
  53073. indices.push(index);
  53074. indices.push(index + 2);
  53075. indices.push(index + 3);
  53076. index += 4;
  53077. }
  53078. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53079. // VBO
  53080. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53081. this._vertexData = new Float32Array(capacity * 16 * 4);
  53082. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53083. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53084. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53085. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53086. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53087. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53088. this._vertexBuffers["options"] = options;
  53089. this._vertexBuffers["cellInfo"] = cellInfo;
  53090. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53091. // Effects
  53092. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53093. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53094. }
  53095. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53096. set: function (callback) {
  53097. if (this._onDisposeObserver) {
  53098. this.onDisposeObservable.remove(this._onDisposeObserver);
  53099. }
  53100. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53101. },
  53102. enumerable: true,
  53103. configurable: true
  53104. });
  53105. Object.defineProperty(SpriteManager.prototype, "texture", {
  53106. get: function () {
  53107. return this._spriteTexture;
  53108. },
  53109. set: function (value) {
  53110. this._spriteTexture = value;
  53111. },
  53112. enumerable: true,
  53113. configurable: true
  53114. });
  53115. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53116. var arrayOffset = index * 16;
  53117. if (offsetX === 0)
  53118. offsetX = this._epsilon;
  53119. else if (offsetX === 1)
  53120. offsetX = 1 - this._epsilon;
  53121. if (offsetY === 0)
  53122. offsetY = this._epsilon;
  53123. else if (offsetY === 1)
  53124. offsetY = 1 - this._epsilon;
  53125. this._vertexData[arrayOffset] = sprite.position.x;
  53126. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53127. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53128. this._vertexData[arrayOffset + 3] = sprite.angle;
  53129. this._vertexData[arrayOffset + 4] = sprite.width;
  53130. this._vertexData[arrayOffset + 5] = sprite.height;
  53131. this._vertexData[arrayOffset + 6] = offsetX;
  53132. this._vertexData[arrayOffset + 7] = offsetY;
  53133. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53134. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53135. var offset = (sprite.cellIndex / rowSize) >> 0;
  53136. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53137. this._vertexData[arrayOffset + 11] = offset;
  53138. // Color
  53139. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53140. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53141. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53142. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53143. };
  53144. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53145. var count = Math.min(this._capacity, this.sprites.length);
  53146. var min = BABYLON.Vector3.Zero();
  53147. var max = BABYLON.Vector3.Zero();
  53148. var distance = Number.MAX_VALUE;
  53149. var currentSprite = null;
  53150. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53151. var cameraView = camera.getViewMatrix();
  53152. for (var index = 0; index < count; index++) {
  53153. var sprite = this.sprites[index];
  53154. if (!sprite) {
  53155. continue;
  53156. }
  53157. if (predicate) {
  53158. if (!predicate(sprite)) {
  53159. continue;
  53160. }
  53161. }
  53162. else if (!sprite.isPickable) {
  53163. continue;
  53164. }
  53165. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53166. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53167. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53168. if (ray.intersectsBoxMinMax(min, max)) {
  53169. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53170. if (distance > currentDistance) {
  53171. distance = currentDistance;
  53172. currentSprite = sprite;
  53173. if (fastCheck) {
  53174. break;
  53175. }
  53176. }
  53177. }
  53178. }
  53179. if (currentSprite) {
  53180. var result = new BABYLON.PickingInfo();
  53181. result.hit = true;
  53182. result.pickedSprite = currentSprite;
  53183. result.distance = distance;
  53184. return result;
  53185. }
  53186. return null;
  53187. };
  53188. SpriteManager.prototype.render = function () {
  53189. // Check
  53190. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53191. return;
  53192. var engine = this._scene.getEngine();
  53193. var baseSize = this._spriteTexture.getBaseSize();
  53194. // Sprites
  53195. var deltaTime = engine.getDeltaTime();
  53196. var max = Math.min(this._capacity, this.sprites.length);
  53197. var rowSize = baseSize.width / this.cellWidth;
  53198. var offset = 0;
  53199. for (var index = 0; index < max; index++) {
  53200. var sprite = this.sprites[index];
  53201. if (!sprite) {
  53202. continue;
  53203. }
  53204. sprite._animate(deltaTime);
  53205. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53206. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53207. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53208. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53209. }
  53210. this._buffer.update(this._vertexData);
  53211. // Render
  53212. var effect = this._effectBase;
  53213. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53214. effect = this._effectFog;
  53215. }
  53216. engine.enableEffect(effect);
  53217. var viewMatrix = this._scene.getViewMatrix();
  53218. effect.setTexture("diffuseSampler", this._spriteTexture);
  53219. effect.setMatrix("view", viewMatrix);
  53220. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53221. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53222. // Fog
  53223. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53224. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53225. effect.setColor3("vFogColor", this._scene.fogColor);
  53226. }
  53227. // VBOs
  53228. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53229. // Draw order
  53230. engine.setDepthFunctionToLessOrEqual();
  53231. effect.setBool("alphaTest", true);
  53232. engine.setColorWrite(false);
  53233. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53234. engine.setColorWrite(true);
  53235. effect.setBool("alphaTest", false);
  53236. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53237. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53238. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53239. };
  53240. SpriteManager.prototype.dispose = function () {
  53241. if (this._buffer) {
  53242. this._buffer.dispose();
  53243. this._buffer = null;
  53244. }
  53245. if (this._indexBuffer) {
  53246. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53247. this._indexBuffer = null;
  53248. }
  53249. if (this._spriteTexture) {
  53250. this._spriteTexture.dispose();
  53251. this._spriteTexture = null;
  53252. }
  53253. // Remove from scene
  53254. var index = this._scene.spriteManagers.indexOf(this);
  53255. this._scene.spriteManagers.splice(index, 1);
  53256. // Callback
  53257. this.onDisposeObservable.notifyObservers(this);
  53258. this.onDisposeObservable.clear();
  53259. };
  53260. return SpriteManager;
  53261. }());
  53262. BABYLON.SpriteManager = SpriteManager;
  53263. })(BABYLON || (BABYLON = {}));
  53264. //# sourceMappingURL=babylon.spriteManager.js.map
  53265. "use strict";
  53266. var BABYLON;
  53267. (function (BABYLON) {
  53268. var Sprite = /** @class */ (function () {
  53269. function Sprite(name, manager) {
  53270. this.name = name;
  53271. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53272. this.width = 1.0;
  53273. this.height = 1.0;
  53274. this.angle = 0;
  53275. this.cellIndex = 0;
  53276. this.invertU = 0;
  53277. this.invertV = 0;
  53278. this.animations = new Array();
  53279. this.isPickable = false;
  53280. this._animationStarted = false;
  53281. this._loopAnimation = false;
  53282. this._fromIndex = 0;
  53283. this._toIndex = 0;
  53284. this._delay = 0;
  53285. this._direction = 1;
  53286. this._time = 0;
  53287. this._manager = manager;
  53288. this._manager.sprites.push(this);
  53289. this.position = BABYLON.Vector3.Zero();
  53290. }
  53291. Object.defineProperty(Sprite.prototype, "size", {
  53292. get: function () {
  53293. return this.width;
  53294. },
  53295. set: function (value) {
  53296. this.width = value;
  53297. this.height = value;
  53298. },
  53299. enumerable: true,
  53300. configurable: true
  53301. });
  53302. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53303. this._fromIndex = from;
  53304. this._toIndex = to;
  53305. this._loopAnimation = loop;
  53306. this._delay = delay;
  53307. this._animationStarted = true;
  53308. this._direction = from < to ? 1 : -1;
  53309. this.cellIndex = from;
  53310. this._time = 0;
  53311. this._onAnimationEnd = onAnimationEnd;
  53312. };
  53313. Sprite.prototype.stopAnimation = function () {
  53314. this._animationStarted = false;
  53315. };
  53316. Sprite.prototype._animate = function (deltaTime) {
  53317. if (!this._animationStarted)
  53318. return;
  53319. this._time += deltaTime;
  53320. if (this._time > this._delay) {
  53321. this._time = this._time % this._delay;
  53322. this.cellIndex += this._direction;
  53323. if (this.cellIndex > this._toIndex) {
  53324. if (this._loopAnimation) {
  53325. this.cellIndex = this._fromIndex;
  53326. }
  53327. else {
  53328. this.cellIndex = this._toIndex;
  53329. this._animationStarted = false;
  53330. if (this._onAnimationEnd) {
  53331. this._onAnimationEnd();
  53332. }
  53333. if (this.disposeWhenFinishedAnimating) {
  53334. this.dispose();
  53335. }
  53336. }
  53337. }
  53338. }
  53339. };
  53340. Sprite.prototype.dispose = function () {
  53341. for (var i = 0; i < this._manager.sprites.length; i++) {
  53342. if (this._manager.sprites[i] == this) {
  53343. this._manager.sprites.splice(i, 1);
  53344. }
  53345. }
  53346. };
  53347. return Sprite;
  53348. }());
  53349. BABYLON.Sprite = Sprite;
  53350. })(BABYLON || (BABYLON = {}));
  53351. //# sourceMappingURL=babylon.sprite.js.map
  53352. "use strict";
  53353. var BABYLON;
  53354. (function (BABYLON) {
  53355. var IntersectionInfo = /** @class */ (function () {
  53356. function IntersectionInfo(bu, bv, distance) {
  53357. this.bu = bu;
  53358. this.bv = bv;
  53359. this.distance = distance;
  53360. this.faceId = 0;
  53361. this.subMeshId = 0;
  53362. }
  53363. return IntersectionInfo;
  53364. }());
  53365. BABYLON.IntersectionInfo = IntersectionInfo;
  53366. var PickingInfo = /** @class */ (function () {
  53367. function PickingInfo() {
  53368. this.hit = false;
  53369. this.distance = 0;
  53370. this.pickedPoint = null;
  53371. this.pickedMesh = null;
  53372. this.bu = 0;
  53373. this.bv = 0;
  53374. this.faceId = -1;
  53375. this.subMeshId = 0;
  53376. this.pickedSprite = null;
  53377. }
  53378. // Methods
  53379. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53380. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53381. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53382. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53383. return null;
  53384. }
  53385. var indices = this.pickedMesh.getIndices();
  53386. if (!indices) {
  53387. return null;
  53388. }
  53389. var result;
  53390. if (useVerticesNormals) {
  53391. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53392. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53393. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53394. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53395. normal0 = normal0.scale(this.bu);
  53396. normal1 = normal1.scale(this.bv);
  53397. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53398. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53399. }
  53400. else {
  53401. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53402. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53403. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53404. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53405. var p1p2 = vertex1.subtract(vertex2);
  53406. var p3p2 = vertex3.subtract(vertex2);
  53407. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53408. }
  53409. if (useWorldCoordinates) {
  53410. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  53411. }
  53412. return BABYLON.Vector3.Normalize(result);
  53413. };
  53414. PickingInfo.prototype.getTextureCoordinates = function () {
  53415. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53416. return null;
  53417. }
  53418. var indices = this.pickedMesh.getIndices();
  53419. if (!indices) {
  53420. return null;
  53421. }
  53422. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53423. if (!uvs) {
  53424. return null;
  53425. }
  53426. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53427. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53428. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53429. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53430. uv1 = uv1.scale(this.bu);
  53431. uv2 = uv2.scale(this.bv);
  53432. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53433. };
  53434. return PickingInfo;
  53435. }());
  53436. BABYLON.PickingInfo = PickingInfo;
  53437. })(BABYLON || (BABYLON = {}));
  53438. //# sourceMappingURL=babylon.pickingInfo.js.map
  53439. "use strict";
  53440. var BABYLON;
  53441. (function (BABYLON) {
  53442. var Ray = /** @class */ (function () {
  53443. function Ray(origin, direction, length) {
  53444. if (length === void 0) { length = Number.MAX_VALUE; }
  53445. this.origin = origin;
  53446. this.direction = direction;
  53447. this.length = length;
  53448. }
  53449. // Methods
  53450. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53451. var d = 0.0;
  53452. var maxValue = Number.MAX_VALUE;
  53453. var inv;
  53454. var min;
  53455. var max;
  53456. var temp;
  53457. if (Math.abs(this.direction.x) < 0.0000001) {
  53458. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53459. return false;
  53460. }
  53461. }
  53462. else {
  53463. inv = 1.0 / this.direction.x;
  53464. min = (minimum.x - this.origin.x) * inv;
  53465. max = (maximum.x - this.origin.x) * inv;
  53466. if (max === -Infinity) {
  53467. max = Infinity;
  53468. }
  53469. if (min > max) {
  53470. temp = min;
  53471. min = max;
  53472. max = temp;
  53473. }
  53474. d = Math.max(min, d);
  53475. maxValue = Math.min(max, maxValue);
  53476. if (d > maxValue) {
  53477. return false;
  53478. }
  53479. }
  53480. if (Math.abs(this.direction.y) < 0.0000001) {
  53481. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53482. return false;
  53483. }
  53484. }
  53485. else {
  53486. inv = 1.0 / this.direction.y;
  53487. min = (minimum.y - this.origin.y) * inv;
  53488. max = (maximum.y - this.origin.y) * inv;
  53489. if (max === -Infinity) {
  53490. max = Infinity;
  53491. }
  53492. if (min > max) {
  53493. temp = min;
  53494. min = max;
  53495. max = temp;
  53496. }
  53497. d = Math.max(min, d);
  53498. maxValue = Math.min(max, maxValue);
  53499. if (d > maxValue) {
  53500. return false;
  53501. }
  53502. }
  53503. if (Math.abs(this.direction.z) < 0.0000001) {
  53504. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53505. return false;
  53506. }
  53507. }
  53508. else {
  53509. inv = 1.0 / this.direction.z;
  53510. min = (minimum.z - this.origin.z) * inv;
  53511. max = (maximum.z - this.origin.z) * inv;
  53512. if (max === -Infinity) {
  53513. max = Infinity;
  53514. }
  53515. if (min > max) {
  53516. temp = min;
  53517. min = max;
  53518. max = temp;
  53519. }
  53520. d = Math.max(min, d);
  53521. maxValue = Math.min(max, maxValue);
  53522. if (d > maxValue) {
  53523. return false;
  53524. }
  53525. }
  53526. return true;
  53527. };
  53528. Ray.prototype.intersectsBox = function (box) {
  53529. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53530. };
  53531. Ray.prototype.intersectsSphere = function (sphere) {
  53532. var x = sphere.center.x - this.origin.x;
  53533. var y = sphere.center.y - this.origin.y;
  53534. var z = sphere.center.z - this.origin.z;
  53535. var pyth = (x * x) + (y * y) + (z * z);
  53536. var rr = sphere.radius * sphere.radius;
  53537. if (pyth <= rr) {
  53538. return true;
  53539. }
  53540. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53541. if (dot < 0.0) {
  53542. return false;
  53543. }
  53544. var temp = pyth - (dot * dot);
  53545. return temp <= rr;
  53546. };
  53547. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53548. if (!this._edge1) {
  53549. this._edge1 = BABYLON.Vector3.Zero();
  53550. this._edge2 = BABYLON.Vector3.Zero();
  53551. this._pvec = BABYLON.Vector3.Zero();
  53552. this._tvec = BABYLON.Vector3.Zero();
  53553. this._qvec = BABYLON.Vector3.Zero();
  53554. }
  53555. vertex1.subtractToRef(vertex0, this._edge1);
  53556. vertex2.subtractToRef(vertex0, this._edge2);
  53557. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53558. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53559. if (det === 0) {
  53560. return null;
  53561. }
  53562. var invdet = 1 / det;
  53563. this.origin.subtractToRef(vertex0, this._tvec);
  53564. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53565. if (bu < 0 || bu > 1.0) {
  53566. return null;
  53567. }
  53568. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53569. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53570. if (bv < 0 || bu + bv > 1.0) {
  53571. return null;
  53572. }
  53573. //check if the distance is longer than the predefined length.
  53574. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53575. if (distance > this.length) {
  53576. return null;
  53577. }
  53578. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53579. };
  53580. Ray.prototype.intersectsPlane = function (plane) {
  53581. var distance;
  53582. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53583. if (Math.abs(result1) < 9.99999997475243E-07) {
  53584. return null;
  53585. }
  53586. else {
  53587. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53588. distance = (-plane.d - result2) / result1;
  53589. if (distance < 0.0) {
  53590. if (distance < -9.99999997475243E-07) {
  53591. return null;
  53592. }
  53593. else {
  53594. return 0;
  53595. }
  53596. }
  53597. return distance;
  53598. }
  53599. };
  53600. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53601. var tm = BABYLON.Tmp.Matrix[0];
  53602. mesh.getWorldMatrix().invertToRef(tm);
  53603. if (this._tmpRay) {
  53604. Ray.TransformToRef(this, tm, this._tmpRay);
  53605. }
  53606. else {
  53607. this._tmpRay = Ray.Transform(this, tm);
  53608. }
  53609. return mesh.intersects(this._tmpRay, fastCheck);
  53610. };
  53611. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53612. if (results) {
  53613. results.length = 0;
  53614. }
  53615. else {
  53616. results = [];
  53617. }
  53618. for (var i = 0; i < meshes.length; i++) {
  53619. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53620. if (pickInfo.hit) {
  53621. results.push(pickInfo);
  53622. }
  53623. }
  53624. results.sort(this._comparePickingInfo);
  53625. return results;
  53626. };
  53627. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53628. if (pickingInfoA.distance < pickingInfoB.distance) {
  53629. return -1;
  53630. }
  53631. else if (pickingInfoA.distance > pickingInfoB.distance) {
  53632. return 1;
  53633. }
  53634. else {
  53635. return 0;
  53636. }
  53637. };
  53638. /**
  53639. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  53640. * @param sega the first point of the segment to test the intersection against
  53641. * @param segb the second point of the segment to test the intersection against
  53642. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  53643. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  53644. */
  53645. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  53646. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  53647. var u = segb.subtract(sega);
  53648. var v = rsegb.subtract(this.origin);
  53649. var w = sega.subtract(this.origin);
  53650. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  53651. var b = BABYLON.Vector3.Dot(u, v);
  53652. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  53653. var d = BABYLON.Vector3.Dot(u, w);
  53654. var e = BABYLON.Vector3.Dot(v, w);
  53655. var D = a * c - b * b; // always >= 0
  53656. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  53657. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  53658. // compute the line parameters of the two closest points
  53659. if (D < Ray.smallnum) {
  53660. sN = 0.0; // force using point P0 on segment S1
  53661. sD = 1.0; // to prevent possible division by 0.0 later
  53662. tN = e;
  53663. tD = c;
  53664. }
  53665. else {
  53666. sN = (b * e - c * d);
  53667. tN = (a * e - b * d);
  53668. if (sN < 0.0) {
  53669. sN = 0.0;
  53670. tN = e;
  53671. tD = c;
  53672. }
  53673. else if (sN > sD) {
  53674. sN = sD;
  53675. tN = e + b;
  53676. tD = c;
  53677. }
  53678. }
  53679. if (tN < 0.0) {
  53680. tN = 0.0;
  53681. // recompute sc for this edge
  53682. if (-d < 0.0) {
  53683. sN = 0.0;
  53684. }
  53685. else if (-d > a)
  53686. sN = sD;
  53687. else {
  53688. sN = -d;
  53689. sD = a;
  53690. }
  53691. }
  53692. else if (tN > tD) {
  53693. tN = tD;
  53694. // recompute sc for this edge
  53695. if ((-d + b) < 0.0) {
  53696. sN = 0;
  53697. }
  53698. else if ((-d + b) > a) {
  53699. sN = sD;
  53700. }
  53701. else {
  53702. sN = (-d + b);
  53703. sD = a;
  53704. }
  53705. }
  53706. // finally do the division to get sc and tc
  53707. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  53708. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  53709. // get the difference of the two closest points
  53710. var qtc = v.multiplyByFloats(tc, tc, tc);
  53711. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  53712. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  53713. if (isIntersected) {
  53714. return qtc.length();
  53715. }
  53716. return -1;
  53717. };
  53718. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53719. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  53720. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  53721. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  53722. this.direction.normalize();
  53723. return this;
  53724. };
  53725. // Statics
  53726. Ray.Zero = function () {
  53727. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  53728. };
  53729. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53730. var result = Ray.Zero();
  53731. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  53732. };
  53733. /**
  53734. * 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
  53735. * transformed to the given world matrix.
  53736. * @param origin The origin point
  53737. * @param end The end point
  53738. * @param world a matrix to transform the ray to. Default is the identity matrix.
  53739. */
  53740. Ray.CreateNewFromTo = function (origin, end, world) {
  53741. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  53742. var direction = end.subtract(origin);
  53743. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  53744. direction.normalize();
  53745. return Ray.Transform(new Ray(origin, direction, length), world);
  53746. };
  53747. Ray.Transform = function (ray, matrix) {
  53748. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  53749. Ray.TransformToRef(ray, matrix, result);
  53750. return result;
  53751. };
  53752. Ray.TransformToRef = function (ray, matrix, result) {
  53753. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  53754. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  53755. result.length = ray.length;
  53756. var dir = result.direction;
  53757. var len = dir.length();
  53758. if (!(len === 0 || len === 1)) {
  53759. var num = 1.0 / len;
  53760. dir.x *= num;
  53761. dir.y *= num;
  53762. dir.z *= num;
  53763. result.length *= len;
  53764. }
  53765. };
  53766. Ray.smallnum = 0.00000001;
  53767. Ray.rayl = 10e8;
  53768. return Ray;
  53769. }());
  53770. BABYLON.Ray = Ray;
  53771. })(BABYLON || (BABYLON = {}));
  53772. //# sourceMappingURL=babylon.ray.js.map
  53773. "use strict";
  53774. var BABYLON;
  53775. (function (BABYLON) {
  53776. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  53777. if (boxMin.x > sphereCenter.x + sphereRadius)
  53778. return false;
  53779. if (sphereCenter.x - sphereRadius > boxMax.x)
  53780. return false;
  53781. if (boxMin.y > sphereCenter.y + sphereRadius)
  53782. return false;
  53783. if (sphereCenter.y - sphereRadius > boxMax.y)
  53784. return false;
  53785. if (boxMin.z > sphereCenter.z + sphereRadius)
  53786. return false;
  53787. if (sphereCenter.z - sphereRadius > boxMax.z)
  53788. return false;
  53789. return true;
  53790. };
  53791. var getLowestRoot = (function () {
  53792. var result = { root: 0, found: false };
  53793. return function (a, b, c, maxR) {
  53794. result.root = 0;
  53795. result.found = false;
  53796. var determinant = b * b - 4.0 * a * c;
  53797. if (determinant < 0)
  53798. return result;
  53799. var sqrtD = Math.sqrt(determinant);
  53800. var r1 = (-b - sqrtD) / (2.0 * a);
  53801. var r2 = (-b + sqrtD) / (2.0 * a);
  53802. if (r1 > r2) {
  53803. var temp = r2;
  53804. r2 = r1;
  53805. r1 = temp;
  53806. }
  53807. if (r1 > 0 && r1 < maxR) {
  53808. result.root = r1;
  53809. result.found = true;
  53810. return result;
  53811. }
  53812. if (r2 > 0 && r2 < maxR) {
  53813. result.root = r2;
  53814. result.found = true;
  53815. return result;
  53816. }
  53817. return result;
  53818. };
  53819. })();
  53820. var Collider = /** @class */ (function () {
  53821. function Collider() {
  53822. this._collisionPoint = BABYLON.Vector3.Zero();
  53823. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  53824. this._tempVector = BABYLON.Vector3.Zero();
  53825. this._tempVector2 = BABYLON.Vector3.Zero();
  53826. this._tempVector3 = BABYLON.Vector3.Zero();
  53827. this._tempVector4 = BABYLON.Vector3.Zero();
  53828. this._edge = BABYLON.Vector3.Zero();
  53829. this._baseToVertex = BABYLON.Vector3.Zero();
  53830. this._destinationPoint = BABYLON.Vector3.Zero();
  53831. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  53832. this._displacementVector = BABYLON.Vector3.Zero();
  53833. this._radius = BABYLON.Vector3.One();
  53834. this._retry = 0;
  53835. this._basePointWorld = BABYLON.Vector3.Zero();
  53836. this._velocityWorld = BABYLON.Vector3.Zero();
  53837. this._normalizedVelocity = BABYLON.Vector3.Zero();
  53838. this._collisionMask = -1;
  53839. }
  53840. Object.defineProperty(Collider.prototype, "collisionMask", {
  53841. get: function () {
  53842. return this._collisionMask;
  53843. },
  53844. set: function (mask) {
  53845. this._collisionMask = !isNaN(mask) ? mask : -1;
  53846. },
  53847. enumerable: true,
  53848. configurable: true
  53849. });
  53850. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  53851. /**
  53852. * Gets the plane normal used to compute the sliding response (in local space)
  53853. */
  53854. get: function () {
  53855. return this._slidePlaneNormal;
  53856. },
  53857. enumerable: true,
  53858. configurable: true
  53859. });
  53860. // Methods
  53861. Collider.prototype._initialize = function (source, dir, e) {
  53862. this._velocity = dir;
  53863. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  53864. this._basePoint = source;
  53865. source.multiplyToRef(this._radius, this._basePointWorld);
  53866. dir.multiplyToRef(this._radius, this._velocityWorld);
  53867. this._velocityWorldLength = this._velocityWorld.length();
  53868. this._epsilon = e;
  53869. this.collisionFound = false;
  53870. };
  53871. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  53872. pa.subtractToRef(point, this._tempVector);
  53873. pb.subtractToRef(point, this._tempVector2);
  53874. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  53875. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53876. if (d < 0)
  53877. return false;
  53878. pc.subtractToRef(point, this._tempVector3);
  53879. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  53880. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53881. if (d < 0)
  53882. return false;
  53883. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  53884. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53885. return d >= 0;
  53886. };
  53887. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  53888. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  53889. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  53890. if (distance > this._velocityWorldLength + max + sphereRadius) {
  53891. return false;
  53892. }
  53893. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  53894. return false;
  53895. return true;
  53896. };
  53897. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  53898. var t0;
  53899. var embeddedInPlane = false;
  53900. //defensive programming, actually not needed.
  53901. if (!trianglePlaneArray) {
  53902. trianglePlaneArray = [];
  53903. }
  53904. if (!trianglePlaneArray[faceIndex]) {
  53905. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  53906. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  53907. }
  53908. var trianglePlane = trianglePlaneArray[faceIndex];
  53909. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  53910. return;
  53911. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  53912. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  53913. if (normalDotVelocity == 0) {
  53914. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  53915. return;
  53916. embeddedInPlane = true;
  53917. t0 = 0;
  53918. }
  53919. else {
  53920. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53921. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53922. if (t0 > t1) {
  53923. var temp = t1;
  53924. t1 = t0;
  53925. t0 = temp;
  53926. }
  53927. if (t0 > 1.0 || t1 < 0.0)
  53928. return;
  53929. if (t0 < 0)
  53930. t0 = 0;
  53931. if (t0 > 1.0)
  53932. t0 = 1.0;
  53933. }
  53934. this._collisionPoint.copyFromFloats(0, 0, 0);
  53935. var found = false;
  53936. var t = 1.0;
  53937. if (!embeddedInPlane) {
  53938. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  53939. this._velocity.scaleToRef(t0, this._tempVector);
  53940. this._planeIntersectionPoint.addInPlace(this._tempVector);
  53941. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  53942. found = true;
  53943. t = t0;
  53944. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  53945. }
  53946. }
  53947. if (!found) {
  53948. var velocitySquaredLength = this._velocity.lengthSquared();
  53949. var a = velocitySquaredLength;
  53950. this._basePoint.subtractToRef(p1, this._tempVector);
  53951. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53952. var c = this._tempVector.lengthSquared() - 1.0;
  53953. var lowestRoot = getLowestRoot(a, b, c, t);
  53954. if (lowestRoot.found) {
  53955. t = lowestRoot.root;
  53956. found = true;
  53957. this._collisionPoint.copyFrom(p1);
  53958. }
  53959. this._basePoint.subtractToRef(p2, this._tempVector);
  53960. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53961. c = this._tempVector.lengthSquared() - 1.0;
  53962. lowestRoot = getLowestRoot(a, b, c, t);
  53963. if (lowestRoot.found) {
  53964. t = lowestRoot.root;
  53965. found = true;
  53966. this._collisionPoint.copyFrom(p2);
  53967. }
  53968. this._basePoint.subtractToRef(p3, this._tempVector);
  53969. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53970. c = this._tempVector.lengthSquared() - 1.0;
  53971. lowestRoot = getLowestRoot(a, b, c, t);
  53972. if (lowestRoot.found) {
  53973. t = lowestRoot.root;
  53974. found = true;
  53975. this._collisionPoint.copyFrom(p3);
  53976. }
  53977. p2.subtractToRef(p1, this._edge);
  53978. p1.subtractToRef(this._basePoint, this._baseToVertex);
  53979. var edgeSquaredLength = this._edge.lengthSquared();
  53980. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53981. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53982. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53983. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53984. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53985. lowestRoot = getLowestRoot(a, b, c, t);
  53986. if (lowestRoot.found) {
  53987. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  53988. if (f >= 0.0 && f <= 1.0) {
  53989. t = lowestRoot.root;
  53990. found = true;
  53991. this._edge.scaleInPlace(f);
  53992. p1.addToRef(this._edge, this._collisionPoint);
  53993. }
  53994. }
  53995. p3.subtractToRef(p2, this._edge);
  53996. p2.subtractToRef(this._basePoint, this._baseToVertex);
  53997. edgeSquaredLength = this._edge.lengthSquared();
  53998. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53999. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54000. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54001. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54002. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54003. lowestRoot = getLowestRoot(a, b, c, t);
  54004. if (lowestRoot.found) {
  54005. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54006. if (f >= 0.0 && f <= 1.0) {
  54007. t = lowestRoot.root;
  54008. found = true;
  54009. this._edge.scaleInPlace(f);
  54010. p2.addToRef(this._edge, this._collisionPoint);
  54011. }
  54012. }
  54013. p1.subtractToRef(p3, this._edge);
  54014. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54015. edgeSquaredLength = this._edge.lengthSquared();
  54016. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54017. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54018. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54019. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54020. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54021. lowestRoot = getLowestRoot(a, b, c, t);
  54022. if (lowestRoot.found) {
  54023. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54024. if (f >= 0.0 && f <= 1.0) {
  54025. t = lowestRoot.root;
  54026. found = true;
  54027. this._edge.scaleInPlace(f);
  54028. p3.addToRef(this._edge, this._collisionPoint);
  54029. }
  54030. }
  54031. }
  54032. if (found) {
  54033. var distToCollision = t * this._velocity.length();
  54034. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54035. if (!this.intersectionPoint) {
  54036. this.intersectionPoint = this._collisionPoint.clone();
  54037. }
  54038. else {
  54039. this.intersectionPoint.copyFrom(this._collisionPoint);
  54040. }
  54041. this._nearestDistance = distToCollision;
  54042. this.collisionFound = true;
  54043. }
  54044. }
  54045. };
  54046. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54047. for (var i = indexStart; i < indexEnd; i += 3) {
  54048. var p1 = pts[indices[i] - decal];
  54049. var p2 = pts[indices[i + 1] - decal];
  54050. var p3 = pts[indices[i + 2] - decal];
  54051. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54052. }
  54053. };
  54054. Collider.prototype._getResponse = function (pos, vel) {
  54055. pos.addToRef(vel, this._destinationPoint);
  54056. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54057. this._basePoint.addToRef(vel, pos);
  54058. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54059. this._slidePlaneNormal.normalize();
  54060. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54061. pos.addInPlace(this._displacementVector);
  54062. this.intersectionPoint.addInPlace(this._displacementVector);
  54063. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54064. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54065. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54066. };
  54067. return Collider;
  54068. }());
  54069. BABYLON.Collider = Collider;
  54070. })(BABYLON || (BABYLON = {}));
  54071. //# sourceMappingURL=babylon.collider.js.map
  54072. "use strict";
  54073. var BABYLON;
  54074. (function (BABYLON) {
  54075. //WebWorker code will be inserted to this variable.
  54076. BABYLON.CollisionWorker = "";
  54077. var WorkerTaskType;
  54078. (function (WorkerTaskType) {
  54079. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54080. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54081. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54082. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54083. var WorkerReplyType;
  54084. (function (WorkerReplyType) {
  54085. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54086. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54087. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54088. var CollisionCoordinatorWorker = /** @class */ (function () {
  54089. function CollisionCoordinatorWorker() {
  54090. var _this = this;
  54091. this._scaledPosition = BABYLON.Vector3.Zero();
  54092. this._scaledVelocity = BABYLON.Vector3.Zero();
  54093. this.onMeshUpdated = function (transformNode) {
  54094. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54095. };
  54096. this.onGeometryUpdated = function (geometry) {
  54097. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54098. };
  54099. this._afterRender = function () {
  54100. if (!_this._init)
  54101. return;
  54102. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54103. return;
  54104. }
  54105. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54106. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54107. if (_this._runningUpdated > 4) {
  54108. return;
  54109. }
  54110. ++_this._runningUpdated;
  54111. var payload = {
  54112. updatedMeshes: _this._addUpdateMeshesList,
  54113. updatedGeometries: _this._addUpdateGeometriesList,
  54114. removedGeometries: _this._toRemoveGeometryArray,
  54115. removedMeshes: _this._toRemoveMeshesArray
  54116. };
  54117. var message = {
  54118. payload: payload,
  54119. taskType: WorkerTaskType.UPDATE
  54120. };
  54121. var serializable = [];
  54122. for (var id in payload.updatedGeometries) {
  54123. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54124. //prepare transferables
  54125. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54126. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54127. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54128. }
  54129. }
  54130. _this._worker.postMessage(message, serializable);
  54131. _this._addUpdateMeshesList = {};
  54132. _this._addUpdateGeometriesList = {};
  54133. _this._toRemoveGeometryArray = [];
  54134. _this._toRemoveMeshesArray = [];
  54135. };
  54136. this._onMessageFromWorker = function (e) {
  54137. var returnData = e.data;
  54138. if (returnData.error != WorkerReplyType.SUCCESS) {
  54139. //TODO what errors can be returned from the worker?
  54140. BABYLON.Tools.Warn("error returned from worker!");
  54141. return;
  54142. }
  54143. switch (returnData.taskType) {
  54144. case WorkerTaskType.INIT:
  54145. _this._init = true;
  54146. //Update the worked with ALL of the scene's current state
  54147. _this._scene.meshes.forEach(function (mesh) {
  54148. _this.onMeshAdded(mesh);
  54149. });
  54150. _this._scene.getGeometries().forEach(function (geometry) {
  54151. _this.onGeometryAdded(geometry);
  54152. });
  54153. break;
  54154. case WorkerTaskType.UPDATE:
  54155. _this._runningUpdated--;
  54156. break;
  54157. case WorkerTaskType.COLLIDE:
  54158. var returnPayload = returnData.payload;
  54159. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54160. return;
  54161. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54162. if (callback) {
  54163. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54164. if (mesh) {
  54165. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54166. }
  54167. }
  54168. //cleanup
  54169. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54170. break;
  54171. }
  54172. };
  54173. this._collisionsCallbackArray = [];
  54174. this._init = false;
  54175. this._runningUpdated = 0;
  54176. this._addUpdateMeshesList = {};
  54177. this._addUpdateGeometriesList = {};
  54178. this._toRemoveGeometryArray = [];
  54179. this._toRemoveMeshesArray = [];
  54180. }
  54181. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54182. if (!this._init)
  54183. return;
  54184. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54185. return;
  54186. position.divideToRef(collider._radius, this._scaledPosition);
  54187. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54188. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54189. var payload = {
  54190. collider: {
  54191. position: this._scaledPosition.asArray(),
  54192. velocity: this._scaledVelocity.asArray(),
  54193. radius: collider._radius.asArray()
  54194. },
  54195. collisionId: collisionIndex,
  54196. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54197. maximumRetry: maximumRetry
  54198. };
  54199. var message = {
  54200. payload: payload,
  54201. taskType: WorkerTaskType.COLLIDE
  54202. };
  54203. this._worker.postMessage(message);
  54204. };
  54205. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54206. this._scene = scene;
  54207. this._scene.registerAfterRender(this._afterRender);
  54208. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54209. this._worker = new Worker(workerUrl);
  54210. this._worker.onmessage = this._onMessageFromWorker;
  54211. var message = {
  54212. payload: {},
  54213. taskType: WorkerTaskType.INIT
  54214. };
  54215. this._worker.postMessage(message);
  54216. };
  54217. CollisionCoordinatorWorker.prototype.destroy = function () {
  54218. this._scene.unregisterAfterRender(this._afterRender);
  54219. this._worker.terminate();
  54220. };
  54221. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54222. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54223. this.onMeshUpdated(mesh);
  54224. };
  54225. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54226. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54227. };
  54228. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54229. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54230. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54231. this.onGeometryUpdated(geometry);
  54232. };
  54233. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54234. this._toRemoveGeometryArray.push(geometry.id);
  54235. };
  54236. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54237. var submeshes = [];
  54238. if (mesh.subMeshes) {
  54239. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54240. var boundingInfo = sm.getBoundingInfo();
  54241. return {
  54242. position: idx,
  54243. verticesStart: sm.verticesStart,
  54244. verticesCount: sm.verticesCount,
  54245. indexStart: sm.indexStart,
  54246. indexCount: sm.indexCount,
  54247. hasMaterial: !!sm.getMaterial(),
  54248. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54249. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54250. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54251. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54252. };
  54253. });
  54254. }
  54255. var geometryId = null;
  54256. if (mesh instanceof BABYLON.Mesh) {
  54257. var geometry = mesh.geometry;
  54258. geometryId = geometry ? geometry.id : null;
  54259. }
  54260. else if (mesh instanceof BABYLON.InstancedMesh) {
  54261. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54262. geometryId = geometry ? geometry.id : null;
  54263. }
  54264. var boundingInfo = mesh.getBoundingInfo();
  54265. return {
  54266. uniqueId: mesh.uniqueId,
  54267. id: mesh.id,
  54268. name: mesh.name,
  54269. geometryId: geometryId,
  54270. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54271. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54272. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54273. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54274. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54275. subMeshes: submeshes,
  54276. checkCollisions: mesh.checkCollisions
  54277. };
  54278. };
  54279. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54280. return {
  54281. id: geometry.id,
  54282. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54283. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54284. indices: new Uint32Array(geometry.getIndices() || []),
  54285. };
  54286. };
  54287. return CollisionCoordinatorWorker;
  54288. }());
  54289. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54290. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54291. function CollisionCoordinatorLegacy() {
  54292. this._scaledPosition = BABYLON.Vector3.Zero();
  54293. this._scaledVelocity = BABYLON.Vector3.Zero();
  54294. this._finalPosition = BABYLON.Vector3.Zero();
  54295. }
  54296. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54297. position.divideToRef(collider._radius, this._scaledPosition);
  54298. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54299. collider.collidedMesh = null;
  54300. collider._retry = 0;
  54301. collider._initialVelocity = this._scaledVelocity;
  54302. collider._initialPosition = this._scaledPosition;
  54303. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54304. this._finalPosition.multiplyInPlace(collider._radius);
  54305. //run the callback
  54306. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54307. };
  54308. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54309. this._scene = scene;
  54310. };
  54311. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54312. //Legacy need no destruction method.
  54313. };
  54314. //No update in legacy mode
  54315. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54316. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54317. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54318. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54319. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54320. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54321. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54322. if (excludedMesh === void 0) { excludedMesh = null; }
  54323. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54324. if (collider._retry >= maximumRetry) {
  54325. finalPosition.copyFrom(position);
  54326. return;
  54327. }
  54328. // Check if this is a mesh else camera or -1
  54329. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54330. collider._initialize(position, velocity, closeDistance);
  54331. // Check all meshes
  54332. for (var index = 0; index < this._scene.meshes.length; index++) {
  54333. var mesh = this._scene.meshes[index];
  54334. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54335. mesh._checkCollision(collider);
  54336. }
  54337. }
  54338. if (!collider.collisionFound) {
  54339. position.addToRef(velocity, finalPosition);
  54340. return;
  54341. }
  54342. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54343. collider._getResponse(position, velocity);
  54344. }
  54345. if (velocity.length() <= closeDistance) {
  54346. finalPosition.copyFrom(position);
  54347. return;
  54348. }
  54349. collider._retry++;
  54350. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54351. };
  54352. return CollisionCoordinatorLegacy;
  54353. }());
  54354. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54355. })(BABYLON || (BABYLON = {}));
  54356. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54357. "use strict";
  54358. var BABYLON;
  54359. (function (BABYLON) {
  54360. /**
  54361. * A particle represents one of the element emitted by a particle system.
  54362. * This is mainly define by its coordinates, direction, velocity and age.
  54363. */
  54364. var Particle = /** @class */ (function () {
  54365. /**
  54366. * Creates a new instance Particle
  54367. * @param particleSystem the particle system the particle belongs to
  54368. */
  54369. function Particle(
  54370. /**
  54371. * particleSystem the particle system the particle belongs to.
  54372. */
  54373. particleSystem) {
  54374. this.particleSystem = particleSystem;
  54375. /**
  54376. * The world position of the particle in the scene.
  54377. */
  54378. this.position = BABYLON.Vector3.Zero();
  54379. /**
  54380. * The world direction of the particle in the scene.
  54381. */
  54382. this.direction = BABYLON.Vector3.Zero();
  54383. /**
  54384. * The color of the particle.
  54385. */
  54386. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54387. /**
  54388. * The color change of the particle per step.
  54389. */
  54390. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54391. /**
  54392. * Defines how long will the life of the particle be.
  54393. */
  54394. this.lifeTime = 1.0;
  54395. /**
  54396. * The current age of the particle.
  54397. */
  54398. this.age = 0;
  54399. /**
  54400. * The current size of the particle.
  54401. */
  54402. this.size = 0;
  54403. /**
  54404. * The current angle of the particle.
  54405. */
  54406. this.angle = 0;
  54407. /**
  54408. * Defines how fast is the angle changing.
  54409. */
  54410. this.angularSpeed = 0;
  54411. /**
  54412. * Defines the cell index used by the particle to be rendered from a sprite.
  54413. */
  54414. this.cellIndex = 0;
  54415. this._currentFrameCounter = 0;
  54416. if (!this.particleSystem.isAnimationSheetEnabled) {
  54417. return;
  54418. }
  54419. this.updateCellInfoFromSystem();
  54420. }
  54421. Particle.prototype.updateCellInfoFromSystem = function () {
  54422. this.cellIndex = this.particleSystem.startSpriteCellID;
  54423. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  54424. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  54425. }
  54426. else {
  54427. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  54428. }
  54429. };
  54430. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  54431. // (ageOffset / scaledUpdateSpeed) / available cells
  54432. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  54433. this._currentFrameCounter += scaledUpdateSpeed;
  54434. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  54435. this._currentFrameCounter = 0;
  54436. this.cellIndex++;
  54437. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54438. this.cellIndex = this.particleSystem.endSpriteCellID;
  54439. }
  54440. }
  54441. };
  54442. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  54443. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  54444. this.cellIndex++;
  54445. this._currentFrameCounter = 0;
  54446. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54447. if (this.particleSystem.spriteCellLoop) {
  54448. this.cellIndex = this.particleSystem.startSpriteCellID;
  54449. }
  54450. else {
  54451. this.cellIndex = this.particleSystem.endSpriteCellID;
  54452. }
  54453. }
  54454. }
  54455. else {
  54456. this._currentFrameCounter++;
  54457. }
  54458. };
  54459. /**
  54460. * Copy the properties of particle to another one.
  54461. * @param other the particle to copy the information to.
  54462. */
  54463. Particle.prototype.copyTo = function (other) {
  54464. other.position.copyFrom(this.position);
  54465. other.direction.copyFrom(this.direction);
  54466. other.color.copyFrom(this.color);
  54467. other.colorStep.copyFrom(this.colorStep);
  54468. other.lifeTime = this.lifeTime;
  54469. other.age = this.age;
  54470. other.size = this.size;
  54471. other.angle = this.angle;
  54472. other.angularSpeed = this.angularSpeed;
  54473. other.particleSystem = this.particleSystem;
  54474. other.cellIndex = this.cellIndex;
  54475. };
  54476. return Particle;
  54477. }());
  54478. BABYLON.Particle = Particle;
  54479. })(BABYLON || (BABYLON = {}));
  54480. //# sourceMappingURL=babylon.particle.js.map
  54481. "use strict";
  54482. var BABYLON;
  54483. (function (BABYLON) {
  54484. /**
  54485. * This represents a particle system in Babylon.
  54486. * 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.
  54487. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54488. * @example https://doc.babylonjs.com/babylon101/particles
  54489. */
  54490. var ParticleSystem = /** @class */ (function () {
  54491. /**
  54492. * Instantiates a particle system.
  54493. * 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.
  54494. * @param name The name of the particle system
  54495. * @param capacity The max number of particles alive at the same time
  54496. * @param scene The scene the particle system belongs to
  54497. * @param customEffect a custom effect used to change the way particles are rendered by default
  54498. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54499. * @param epsilon Offset used to render the particles
  54500. */
  54501. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54502. if (customEffect === void 0) { customEffect = null; }
  54503. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54504. if (epsilon === void 0) { epsilon = 0.01; }
  54505. var _this = this;
  54506. /**
  54507. * List of animations used by the particle system.
  54508. */
  54509. this.animations = [];
  54510. /**
  54511. * The rendering group used by the Particle system to chose when to render.
  54512. */
  54513. this.renderingGroupId = 0;
  54514. /**
  54515. * The emitter represents the Mesh or position we are attaching the particle system to.
  54516. */
  54517. this.emitter = null;
  54518. /**
  54519. * The maximum number of particles to emit per frame
  54520. */
  54521. this.emitRate = 10;
  54522. /**
  54523. * If you want to launch only a few particles at once, that can be done, as well.
  54524. */
  54525. this.manualEmitCount = -1;
  54526. /**
  54527. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54528. */
  54529. this.updateSpeed = 0.01;
  54530. /**
  54531. * The amount of time the particle system is running (depends of the overall update speed).
  54532. */
  54533. this.targetStopDuration = 0;
  54534. /**
  54535. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54536. */
  54537. this.disposeOnStop = false;
  54538. /**
  54539. * Minimum power of emitting particles.
  54540. */
  54541. this.minEmitPower = 1;
  54542. /**
  54543. * Maximum power of emitting particles.
  54544. */
  54545. this.maxEmitPower = 1;
  54546. /**
  54547. * Minimum life time of emitting particles.
  54548. */
  54549. this.minLifeTime = 1;
  54550. /**
  54551. * Maximum life time of emitting particles.
  54552. */
  54553. this.maxLifeTime = 1;
  54554. /**
  54555. * Minimum Size of emitting particles.
  54556. */
  54557. this.minSize = 1;
  54558. /**
  54559. * Maximum Size of emitting particles.
  54560. */
  54561. this.maxSize = 1;
  54562. /**
  54563. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54564. */
  54565. this.minAngularSpeed = 0;
  54566. /**
  54567. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54568. */
  54569. this.maxAngularSpeed = 0;
  54570. /**
  54571. * The layer mask we are rendering the particles through.
  54572. */
  54573. this.layerMask = 0x0FFFFFFF;
  54574. /**
  54575. * This can help using your own shader to render the particle system.
  54576. * The according effect will be created
  54577. */
  54578. this.customShader = null;
  54579. /**
  54580. * By default particle system starts as soon as they are created. This prevents the
  54581. * automatic start to happen and let you decide when to start emitting particles.
  54582. */
  54583. this.preventAutoStart = false;
  54584. /**
  54585. * Callback triggered when the particle animation is ending.
  54586. */
  54587. this.onAnimationEnd = null;
  54588. /**
  54589. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  54590. */
  54591. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  54592. /**
  54593. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  54594. * to override the particles.
  54595. */
  54596. this.forceDepthWrite = false;
  54597. /**
  54598. * You can use gravity if you want to give an orientation to your particles.
  54599. */
  54600. this.gravity = BABYLON.Vector3.Zero();
  54601. /**
  54602. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  54603. */
  54604. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54605. /**
  54606. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  54607. */
  54608. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54609. /**
  54610. * Color the particle will have at the end of its lifetime.
  54611. */
  54612. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  54613. /**
  54614. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  54615. */
  54616. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54617. /**
  54618. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  54619. */
  54620. this.spriteCellLoop = true;
  54621. /**
  54622. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  54623. */
  54624. this.spriteCellChangeSpeed = 0;
  54625. /**
  54626. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  54627. */
  54628. this.startSpriteCellID = 0;
  54629. /**
  54630. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  54631. */
  54632. this.endSpriteCellID = 0;
  54633. /**
  54634. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  54635. */
  54636. this.spriteCellWidth = 0;
  54637. /**
  54638. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  54639. */
  54640. this.spriteCellHeight = 0;
  54641. /**
  54642. * An event triggered when the system is disposed.
  54643. */
  54644. this.onDisposeObservable = new BABYLON.Observable();
  54645. this._particles = new Array();
  54646. this._stockParticles = new Array();
  54647. this._newPartsExcess = 0;
  54648. this._vertexBuffers = {};
  54649. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  54650. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  54651. this._scaledDirection = BABYLON.Vector3.Zero();
  54652. this._scaledGravity = BABYLON.Vector3.Zero();
  54653. this._currentRenderId = -1;
  54654. this._started = false;
  54655. this._stopped = false;
  54656. this._actualFrame = 0;
  54657. this._vertexBufferSize = 11;
  54658. // start of sub system methods
  54659. /**
  54660. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  54661. * Its lifetime will start back at 0.
  54662. */
  54663. this.recycleParticle = function (particle) {
  54664. var lastParticle = _this._particles.pop();
  54665. if (lastParticle !== particle) {
  54666. lastParticle.copyTo(particle);
  54667. }
  54668. _this._stockParticles.push(lastParticle);
  54669. };
  54670. this._createParticle = function () {
  54671. var particle;
  54672. if (_this._stockParticles.length !== 0) {
  54673. particle = _this._stockParticles.pop();
  54674. particle.age = 0;
  54675. particle.cellIndex = _this.startSpriteCellID;
  54676. }
  54677. else {
  54678. particle = new BABYLON.Particle(_this);
  54679. }
  54680. return particle;
  54681. };
  54682. this._emitFromParticle = function (particle) {
  54683. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  54684. return;
  54685. }
  54686. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  54687. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  54688. subSystem._rootParticleSystem = _this;
  54689. _this.activeSubSystems.push(subSystem);
  54690. subSystem.start();
  54691. };
  54692. this._appendParticleVertexes = null;
  54693. this.id = name;
  54694. this.name = name;
  54695. this._capacity = capacity;
  54696. this._epsilon = epsilon;
  54697. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  54698. if (isAnimationSheetEnabled) {
  54699. this._vertexBufferSize = 12;
  54700. }
  54701. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54702. this._customEffect = customEffect;
  54703. scene.particleSystems.push(this);
  54704. this._createIndexBuffer();
  54705. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  54706. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  54707. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  54708. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  54709. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  54710. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  54711. if (this._isAnimationSheetEnabled) {
  54712. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  54713. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  54714. }
  54715. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54716. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54717. this._vertexBuffers["options"] = options;
  54718. // Default emitter type
  54719. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  54720. this.updateFunction = function (particles) {
  54721. for (var index = 0; index < particles.length; index++) {
  54722. var particle = particles[index];
  54723. particle.age += _this._scaledUpdateSpeed;
  54724. if (particle.age >= particle.lifeTime) {
  54725. _this._emitFromParticle(particle);
  54726. _this.recycleParticle(particle);
  54727. index--;
  54728. continue;
  54729. }
  54730. else {
  54731. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  54732. particle.color.addInPlace(_this._scaledColorStep);
  54733. if (particle.color.a < 0)
  54734. particle.color.a = 0;
  54735. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  54736. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  54737. particle.position.addInPlace(_this._scaledDirection);
  54738. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  54739. particle.direction.addInPlace(_this._scaledGravity);
  54740. if (_this._isAnimationSheetEnabled) {
  54741. particle.updateCellIndex(_this._scaledUpdateSpeed);
  54742. }
  54743. }
  54744. }
  54745. };
  54746. }
  54747. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  54748. /**
  54749. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54750. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54751. */
  54752. get: function () {
  54753. if (this.particleEmitterType.direction1) {
  54754. return this.particleEmitterType.direction1;
  54755. }
  54756. return BABYLON.Vector3.Zero();
  54757. },
  54758. set: function (value) {
  54759. if (this.particleEmitterType.direction1) {
  54760. this.particleEmitterType.direction1 = value;
  54761. }
  54762. },
  54763. enumerable: true,
  54764. configurable: true
  54765. });
  54766. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  54767. /**
  54768. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54769. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54770. */
  54771. get: function () {
  54772. if (this.particleEmitterType.direction2) {
  54773. return this.particleEmitterType.direction2;
  54774. }
  54775. return BABYLON.Vector3.Zero();
  54776. },
  54777. set: function (value) {
  54778. if (this.particleEmitterType.direction2) {
  54779. this.particleEmitterType.direction2 = value;
  54780. }
  54781. },
  54782. enumerable: true,
  54783. configurable: true
  54784. });
  54785. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  54786. /**
  54787. * 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.
  54788. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54789. */
  54790. get: function () {
  54791. if (this.particleEmitterType.minEmitBox) {
  54792. return this.particleEmitterType.minEmitBox;
  54793. }
  54794. return BABYLON.Vector3.Zero();
  54795. },
  54796. set: function (value) {
  54797. if (this.particleEmitterType.minEmitBox) {
  54798. this.particleEmitterType.minEmitBox = value;
  54799. }
  54800. },
  54801. enumerable: true,
  54802. configurable: true
  54803. });
  54804. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  54805. /**
  54806. * 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.
  54807. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54808. */
  54809. get: function () {
  54810. if (this.particleEmitterType.maxEmitBox) {
  54811. return this.particleEmitterType.maxEmitBox;
  54812. }
  54813. return BABYLON.Vector3.Zero();
  54814. },
  54815. set: function (value) {
  54816. if (this.particleEmitterType.maxEmitBox) {
  54817. this.particleEmitterType.maxEmitBox = value;
  54818. }
  54819. },
  54820. enumerable: true,
  54821. configurable: true
  54822. });
  54823. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  54824. /**
  54825. * Sets a callback that will be triggered when the system is disposed.
  54826. */
  54827. set: function (callback) {
  54828. if (this._onDisposeObserver) {
  54829. this.onDisposeObservable.remove(this._onDisposeObserver);
  54830. }
  54831. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54832. },
  54833. enumerable: true,
  54834. configurable: true
  54835. });
  54836. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  54837. /**
  54838. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  54839. */
  54840. get: function () {
  54841. return this._isAnimationSheetEnabled;
  54842. },
  54843. enumerable: true,
  54844. configurable: true
  54845. });
  54846. Object.defineProperty(ParticleSystem.prototype, "particles", {
  54847. //end of Sub-emitter
  54848. /**
  54849. * Gets the current list of active particles
  54850. */
  54851. get: function () {
  54852. return this._particles;
  54853. },
  54854. enumerable: true,
  54855. configurable: true
  54856. });
  54857. /**
  54858. * Returns the string "ParticleSystem"
  54859. * @returns a string containing the class name
  54860. */
  54861. ParticleSystem.prototype.getClassName = function () {
  54862. return "ParticleSystem";
  54863. };
  54864. ParticleSystem.prototype._createIndexBuffer = function () {
  54865. var indices = [];
  54866. var index = 0;
  54867. for (var count = 0; count < this._capacity; count++) {
  54868. indices.push(index);
  54869. indices.push(index + 1);
  54870. indices.push(index + 2);
  54871. indices.push(index);
  54872. indices.push(index + 2);
  54873. indices.push(index + 3);
  54874. index += 4;
  54875. }
  54876. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  54877. };
  54878. /**
  54879. * Gets the maximum number of particles active at the same time.
  54880. * @returns The max number of active particles.
  54881. */
  54882. ParticleSystem.prototype.getCapacity = function () {
  54883. return this._capacity;
  54884. };
  54885. /**
  54886. * Gets Wether there are still active particles in the system.
  54887. * @returns True if it is alive, otherwise false.
  54888. */
  54889. ParticleSystem.prototype.isAlive = function () {
  54890. return this._alive;
  54891. };
  54892. /**
  54893. * Gets Wether the system has been started.
  54894. * @returns True if it has been started, otherwise false.
  54895. */
  54896. ParticleSystem.prototype.isStarted = function () {
  54897. return this._started;
  54898. };
  54899. /**
  54900. * Starts the particle system and begins to emit.
  54901. */
  54902. ParticleSystem.prototype.start = function () {
  54903. this._started = true;
  54904. this._stopped = false;
  54905. this._actualFrame = 0;
  54906. if (this.subEmitters && this.subEmitters.length != 0) {
  54907. this.activeSubSystems = new Array();
  54908. }
  54909. };
  54910. /**
  54911. * Stops the particle system.
  54912. * @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.
  54913. */
  54914. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  54915. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  54916. this._stopped = true;
  54917. if (stopSubEmitters) {
  54918. this._stopSubEmitters();
  54919. }
  54920. };
  54921. // animation sheet
  54922. /**
  54923. * Remove all active particles
  54924. */
  54925. ParticleSystem.prototype.reset = function () {
  54926. this._stockParticles = [];
  54927. this._particles = [];
  54928. };
  54929. /**
  54930. * @ignore (for internal use only)
  54931. */
  54932. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  54933. var offset = index * this._vertexBufferSize;
  54934. this._vertexData[offset] = particle.position.x;
  54935. this._vertexData[offset + 1] = particle.position.y;
  54936. this._vertexData[offset + 2] = particle.position.z;
  54937. this._vertexData[offset + 3] = particle.color.r;
  54938. this._vertexData[offset + 4] = particle.color.g;
  54939. this._vertexData[offset + 5] = particle.color.b;
  54940. this._vertexData[offset + 6] = particle.color.a;
  54941. this._vertexData[offset + 7] = particle.angle;
  54942. this._vertexData[offset + 8] = particle.size;
  54943. this._vertexData[offset + 9] = offsetX;
  54944. this._vertexData[offset + 10] = offsetY;
  54945. };
  54946. /**
  54947. * @ignore (for internal use only)
  54948. */
  54949. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  54950. if (offsetX === 0)
  54951. offsetX = this._epsilon;
  54952. else if (offsetX === 1)
  54953. offsetX = 1 - this._epsilon;
  54954. if (offsetY === 0)
  54955. offsetY = this._epsilon;
  54956. else if (offsetY === 1)
  54957. offsetY = 1 - this._epsilon;
  54958. var offset = index * this._vertexBufferSize;
  54959. this._vertexData[offset] = particle.position.x;
  54960. this._vertexData[offset + 1] = particle.position.y;
  54961. this._vertexData[offset + 2] = particle.position.z;
  54962. this._vertexData[offset + 3] = particle.color.r;
  54963. this._vertexData[offset + 4] = particle.color.g;
  54964. this._vertexData[offset + 5] = particle.color.b;
  54965. this._vertexData[offset + 6] = particle.color.a;
  54966. this._vertexData[offset + 7] = particle.angle;
  54967. this._vertexData[offset + 8] = particle.size;
  54968. this._vertexData[offset + 9] = offsetX;
  54969. this._vertexData[offset + 10] = offsetY;
  54970. this._vertexData[offset + 11] = particle.cellIndex;
  54971. };
  54972. ParticleSystem.prototype._stopSubEmitters = function () {
  54973. if (!this.activeSubSystems) {
  54974. return;
  54975. }
  54976. this.activeSubSystems.forEach(function (subSystem) {
  54977. subSystem.stop(true);
  54978. });
  54979. this.activeSubSystems = new Array();
  54980. };
  54981. ParticleSystem.prototype._removeFromRoot = function () {
  54982. if (!this._rootParticleSystem) {
  54983. return;
  54984. }
  54985. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  54986. if (index !== -1) {
  54987. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  54988. }
  54989. };
  54990. // end of sub system methods
  54991. ParticleSystem.prototype._update = function (newParticles) {
  54992. // Update current
  54993. this._alive = this._particles.length > 0;
  54994. this.updateFunction(this._particles);
  54995. // Add new ones
  54996. var worldMatrix;
  54997. if (this.emitter.position) {
  54998. var emitterMesh = this.emitter;
  54999. worldMatrix = emitterMesh.getWorldMatrix();
  55000. }
  55001. else {
  55002. var emitterPosition = this.emitter;
  55003. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55004. }
  55005. var particle;
  55006. for (var index = 0; index < newParticles; index++) {
  55007. if (this._particles.length === this._capacity) {
  55008. break;
  55009. }
  55010. particle = this._createParticle();
  55011. this._particles.push(particle);
  55012. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  55013. if (this.startPositionFunction) {
  55014. this.startPositionFunction(worldMatrix, particle.position, particle);
  55015. }
  55016. else {
  55017. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55018. }
  55019. if (this.startDirectionFunction) {
  55020. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55021. }
  55022. else {
  55023. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55024. }
  55025. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  55026. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  55027. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  55028. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  55029. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  55030. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  55031. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55032. }
  55033. };
  55034. ParticleSystem.prototype._getEffect = function () {
  55035. if (this._customEffect) {
  55036. return this._customEffect;
  55037. }
  55038. ;
  55039. var defines = [];
  55040. if (this._scene.clipPlane) {
  55041. defines.push("#define CLIPPLANE");
  55042. }
  55043. if (this._isAnimationSheetEnabled) {
  55044. defines.push("#define ANIMATESHEET");
  55045. }
  55046. // Effect
  55047. var join = defines.join("\n");
  55048. if (this._cachedDefines !== join) {
  55049. this._cachedDefines = join;
  55050. var attributesNamesOrOptions;
  55051. var effectCreationOption;
  55052. if (this._isAnimationSheetEnabled) {
  55053. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  55054. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  55055. }
  55056. else {
  55057. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  55058. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55059. }
  55060. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55061. }
  55062. return this._effect;
  55063. };
  55064. /**
  55065. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55066. */
  55067. ParticleSystem.prototype.animate = function () {
  55068. if (!this._started)
  55069. return;
  55070. var effect = this._getEffect();
  55071. // Check
  55072. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55073. return;
  55074. if (this._currentRenderId === this._scene.getRenderId()) {
  55075. return;
  55076. }
  55077. this._currentRenderId = this._scene.getRenderId();
  55078. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  55079. // determine the number of particles we need to create
  55080. var newParticles;
  55081. if (this.manualEmitCount > -1) {
  55082. newParticles = this.manualEmitCount;
  55083. this._newPartsExcess = 0;
  55084. this.manualEmitCount = 0;
  55085. }
  55086. else {
  55087. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55088. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55089. }
  55090. if (this._newPartsExcess > 1.0) {
  55091. newParticles += this._newPartsExcess >> 0;
  55092. this._newPartsExcess -= this._newPartsExcess >> 0;
  55093. }
  55094. this._alive = false;
  55095. if (!this._stopped) {
  55096. this._actualFrame += this._scaledUpdateSpeed;
  55097. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55098. this.stop();
  55099. }
  55100. else {
  55101. newParticles = 0;
  55102. }
  55103. this._update(newParticles);
  55104. // Stopped?
  55105. if (this._stopped) {
  55106. if (!this._alive) {
  55107. this._started = false;
  55108. if (this.onAnimationEnd) {
  55109. this.onAnimationEnd();
  55110. }
  55111. if (this.disposeOnStop) {
  55112. this._scene._toBeDisposed.push(this);
  55113. }
  55114. }
  55115. }
  55116. // Animation sheet
  55117. if (this._isAnimationSheetEnabled) {
  55118. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  55119. }
  55120. else {
  55121. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  55122. }
  55123. // Update VBO
  55124. var offset = 0;
  55125. for (var index = 0; index < this._particles.length; index++) {
  55126. var particle = this._particles[index];
  55127. this._appendParticleVertexes(offset, particle);
  55128. offset += 4;
  55129. }
  55130. if (this._vertexBuffer) {
  55131. this._vertexBuffer.update(this._vertexData);
  55132. }
  55133. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55134. this.stop();
  55135. }
  55136. };
  55137. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  55138. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  55139. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  55140. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  55141. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  55142. };
  55143. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  55144. this._appendParticleVertex(offset++, particle, 0, 0);
  55145. this._appendParticleVertex(offset++, particle, 1, 0);
  55146. this._appendParticleVertex(offset++, particle, 1, 1);
  55147. this._appendParticleVertex(offset++, particle, 0, 1);
  55148. };
  55149. /**
  55150. * Rebuilds the particle system.
  55151. */
  55152. ParticleSystem.prototype.rebuild = function () {
  55153. this._createIndexBuffer();
  55154. if (this._vertexBuffer) {
  55155. this._vertexBuffer._rebuild();
  55156. }
  55157. };
  55158. /**
  55159. * Is this system ready to be used/rendered
  55160. * @return true if the system is ready
  55161. */
  55162. ParticleSystem.prototype.isReady = function () {
  55163. var effect = this._getEffect();
  55164. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55165. return false;
  55166. }
  55167. return true;
  55168. };
  55169. /**
  55170. * Renders the particle system in its current state.
  55171. * @returns the current number of particles
  55172. */
  55173. ParticleSystem.prototype.render = function () {
  55174. var effect = this._getEffect();
  55175. // Check
  55176. if (!this.isReady() || !this._particles.length) {
  55177. return 0;
  55178. }
  55179. var engine = this._scene.getEngine();
  55180. // Render
  55181. engine.enableEffect(effect);
  55182. engine.setState(false);
  55183. var viewMatrix = this._scene.getViewMatrix();
  55184. effect.setTexture("diffuseSampler", this.particleTexture);
  55185. effect.setMatrix("view", viewMatrix);
  55186. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55187. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55188. var baseSize = this.particleTexture.getBaseSize();
  55189. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55190. }
  55191. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55192. if (this._scene.clipPlane) {
  55193. var clipPlane = this._scene.clipPlane;
  55194. var invView = viewMatrix.clone();
  55195. invView.invert();
  55196. effect.setMatrix("invView", invView);
  55197. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55198. }
  55199. // VBOs
  55200. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55201. // Draw order
  55202. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  55203. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55204. }
  55205. else {
  55206. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55207. }
  55208. if (this.forceDepthWrite) {
  55209. engine.setDepthWrite(true);
  55210. }
  55211. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55212. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55213. return this._particles.length;
  55214. };
  55215. /**
  55216. * Disposes the particle system and free the associated resources
  55217. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55218. */
  55219. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55220. if (disposeTexture === void 0) { disposeTexture = true; }
  55221. if (this._vertexBuffer) {
  55222. this._vertexBuffer.dispose();
  55223. this._vertexBuffer = null;
  55224. }
  55225. if (this._indexBuffer) {
  55226. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55227. this._indexBuffer = null;
  55228. }
  55229. if (disposeTexture && this.particleTexture) {
  55230. this.particleTexture.dispose();
  55231. this.particleTexture = null;
  55232. }
  55233. this._removeFromRoot();
  55234. // Remove from scene
  55235. var index = this._scene.particleSystems.indexOf(this);
  55236. if (index > -1) {
  55237. this._scene.particleSystems.splice(index, 1);
  55238. }
  55239. // Callback
  55240. this.onDisposeObservable.notifyObservers(this);
  55241. this.onDisposeObservable.clear();
  55242. };
  55243. /**
  55244. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55245. * @param radius The radius of the sphere to emit from
  55246. * @returns the emitter
  55247. */
  55248. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55249. if (radius === void 0) { radius = 1; }
  55250. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55251. this.particleEmitterType = particleEmitter;
  55252. return particleEmitter;
  55253. };
  55254. /**
  55255. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55256. * @param radius The radius of the sphere to emit from
  55257. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55258. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55259. * @returns the emitter
  55260. */
  55261. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55262. if (radius === void 0) { radius = 1; }
  55263. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55264. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55265. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55266. this.particleEmitterType = particleEmitter;
  55267. return particleEmitter;
  55268. };
  55269. /**
  55270. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55271. * @param radius The radius of the cone to emit from
  55272. * @param angle The base angle of the cone
  55273. * @returns the emitter
  55274. */
  55275. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55276. if (radius === void 0) { radius = 1; }
  55277. if (angle === void 0) { angle = Math.PI / 4; }
  55278. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55279. this.particleEmitterType = particleEmitter;
  55280. return particleEmitter;
  55281. };
  55282. // 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.
  55283. /**
  55284. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55285. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55286. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55287. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55288. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55289. * @returns the emitter
  55290. */
  55291. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55292. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55293. this.particleEmitterType = particleEmitter;
  55294. this.direction1 = direction1;
  55295. this.direction2 = direction2;
  55296. this.minEmitBox = minEmitBox;
  55297. this.maxEmitBox = maxEmitBox;
  55298. return particleEmitter;
  55299. };
  55300. // Clone
  55301. /**
  55302. * Clones the particle system.
  55303. * @param name The name of the cloned object
  55304. * @param newEmitter The new emitter to use
  55305. * @returns the cloned particle system
  55306. */
  55307. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55308. var custom = null;
  55309. var program = null;
  55310. if (this.customShader != null) {
  55311. program = this.customShader;
  55312. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55313. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55314. }
  55315. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55316. result.customShader = program;
  55317. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  55318. if (newEmitter === undefined) {
  55319. newEmitter = this.emitter;
  55320. }
  55321. result.emitter = newEmitter;
  55322. if (this.particleTexture) {
  55323. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55324. }
  55325. if (!this.preventAutoStart) {
  55326. result.start();
  55327. }
  55328. return result;
  55329. };
  55330. /**
  55331. * Serializes the particle system to a JSON object.
  55332. * @returns the JSON object
  55333. */
  55334. ParticleSystem.prototype.serialize = function () {
  55335. var serializationObject = {};
  55336. serializationObject.name = this.name;
  55337. serializationObject.id = this.id;
  55338. // Emitter
  55339. if (this.emitter.position) {
  55340. var emitterMesh = this.emitter;
  55341. serializationObject.emitterId = emitterMesh.id;
  55342. }
  55343. else {
  55344. var emitterPosition = this.emitter;
  55345. serializationObject.emitter = emitterPosition.asArray();
  55346. }
  55347. serializationObject.capacity = this.getCapacity();
  55348. if (this.particleTexture) {
  55349. serializationObject.textureName = this.particleTexture.name;
  55350. }
  55351. // Animations
  55352. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  55353. // Particle system
  55354. serializationObject.minAngularSpeed = this.minAngularSpeed;
  55355. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  55356. serializationObject.minSize = this.minSize;
  55357. serializationObject.maxSize = this.maxSize;
  55358. serializationObject.minEmitPower = this.minEmitPower;
  55359. serializationObject.maxEmitPower = this.maxEmitPower;
  55360. serializationObject.minLifeTime = this.minLifeTime;
  55361. serializationObject.maxLifeTime = this.maxLifeTime;
  55362. serializationObject.emitRate = this.emitRate;
  55363. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55364. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55365. serializationObject.gravity = this.gravity.asArray();
  55366. serializationObject.direction1 = this.direction1.asArray();
  55367. serializationObject.direction2 = this.direction2.asArray();
  55368. serializationObject.color1 = this.color1.asArray();
  55369. serializationObject.color2 = this.color2.asArray();
  55370. serializationObject.colorDead = this.colorDead.asArray();
  55371. serializationObject.updateSpeed = this.updateSpeed;
  55372. serializationObject.targetStopDuration = this.targetStopDuration;
  55373. serializationObject.textureMask = this.textureMask.asArray();
  55374. serializationObject.blendMode = this.blendMode;
  55375. serializationObject.customShader = this.customShader;
  55376. serializationObject.preventAutoStart = this.preventAutoStart;
  55377. serializationObject.startSpriteCellID = this.startSpriteCellID;
  55378. serializationObject.endSpriteCellID = this.endSpriteCellID;
  55379. serializationObject.spriteCellLoop = this.spriteCellLoop;
  55380. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  55381. serializationObject.spriteCellWidth = this.spriteCellWidth;
  55382. serializationObject.spriteCellHeight = this.spriteCellHeight;
  55383. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  55384. // Emitter
  55385. if (this.particleEmitterType) {
  55386. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  55387. }
  55388. return serializationObject;
  55389. };
  55390. /**
  55391. * Parses a JSON object to create a particle system.
  55392. * @param parsedParticleSystem The JSON object to parse
  55393. * @param scene The scene to create the particle system in
  55394. * @param rootUrl The root url to use to load external dependencies like texture
  55395. * @returns the Parsed particle system
  55396. */
  55397. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  55398. var name = parsedParticleSystem.name;
  55399. var custom = null;
  55400. var program = null;
  55401. if (parsedParticleSystem.customShader) {
  55402. program = parsedParticleSystem.customShader;
  55403. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55404. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55405. }
  55406. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  55407. particleSystem.customShader = program;
  55408. if (parsedParticleSystem.id) {
  55409. particleSystem.id = parsedParticleSystem.id;
  55410. }
  55411. // Auto start
  55412. if (parsedParticleSystem.preventAutoStart) {
  55413. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  55414. }
  55415. // Texture
  55416. if (parsedParticleSystem.textureName) {
  55417. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  55418. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  55419. }
  55420. // Emitter
  55421. if (parsedParticleSystem.emitterId) {
  55422. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  55423. }
  55424. else {
  55425. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  55426. }
  55427. // Animations
  55428. if (parsedParticleSystem.animations) {
  55429. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  55430. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  55431. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  55432. }
  55433. }
  55434. if (parsedParticleSystem.autoAnimate) {
  55435. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  55436. }
  55437. // Particle system
  55438. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  55439. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  55440. particleSystem.minSize = parsedParticleSystem.minSize;
  55441. particleSystem.maxSize = parsedParticleSystem.maxSize;
  55442. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  55443. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  55444. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  55445. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  55446. particleSystem.emitRate = parsedParticleSystem.emitRate;
  55447. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  55448. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  55449. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  55450. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  55451. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  55452. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  55453. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  55454. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  55455. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  55456. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  55457. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  55458. particleSystem.blendMode = parsedParticleSystem.blendMode;
  55459. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  55460. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  55461. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  55462. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  55463. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  55464. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  55465. if (!particleSystem.preventAutoStart) {
  55466. particleSystem.start();
  55467. }
  55468. return particleSystem;
  55469. };
  55470. /**
  55471. * Source color is added to the destination color without alpha affecting the result.
  55472. */
  55473. ParticleSystem.BLENDMODE_ONEONE = 0;
  55474. /**
  55475. * Blend current color and particle color using particle’s alpha.
  55476. */
  55477. ParticleSystem.BLENDMODE_STANDARD = 1;
  55478. return ParticleSystem;
  55479. }());
  55480. BABYLON.ParticleSystem = ParticleSystem;
  55481. })(BABYLON || (BABYLON = {}));
  55482. //# sourceMappingURL=babylon.particleSystem.js.map
  55483. "use strict";
  55484. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  55485. "use strict";
  55486. var BABYLON;
  55487. (function (BABYLON) {
  55488. /**
  55489. * Particle emitter emitting particles from the inside of a box.
  55490. * It emits the particles randomly between 2 given directions.
  55491. */
  55492. var BoxParticleEmitter = /** @class */ (function () {
  55493. /**
  55494. * Creates a new instance BoxParticleEmitter
  55495. */
  55496. function BoxParticleEmitter() {
  55497. /**
  55498. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55499. */
  55500. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  55501. /**
  55502. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55503. */
  55504. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  55505. /**
  55506. * 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.
  55507. */
  55508. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  55509. /**
  55510. * 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.
  55511. */
  55512. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  55513. }
  55514. /**
  55515. * Called by the particle System when the direction is computed for the created particle.
  55516. * @param emitPower is the power of the particle (speed)
  55517. * @param worldMatrix is the world matrix of the particle system
  55518. * @param directionToUpdate is the direction vector to update with the result
  55519. * @param particle is the particle we are computed the direction for
  55520. */
  55521. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55522. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  55523. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  55524. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  55525. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  55526. };
  55527. /**
  55528. * Called by the particle System when the position is computed for the created particle.
  55529. * @param worldMatrix is the world matrix of the particle system
  55530. * @param positionToUpdate is the position vector to update with the result
  55531. * @param particle is the particle we are computed the position for
  55532. */
  55533. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55534. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  55535. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  55536. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  55537. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55538. };
  55539. /**
  55540. * Clones the current emitter and returns a copy of it
  55541. * @returns the new emitter
  55542. */
  55543. BoxParticleEmitter.prototype.clone = function () {
  55544. var newOne = new BoxParticleEmitter();
  55545. BABYLON.Tools.DeepCopy(this, newOne);
  55546. return newOne;
  55547. };
  55548. /**
  55549. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55550. * @param effect defines the update shader
  55551. */
  55552. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  55553. effect.setVector3("direction1", this.direction1);
  55554. effect.setVector3("direction2", this.direction2);
  55555. effect.setVector3("minEmitBox", this.minEmitBox);
  55556. effect.setVector3("maxEmitBox", this.maxEmitBox);
  55557. };
  55558. /**
  55559. * Returns a string to use to update the GPU particles update shader
  55560. * @returns a string containng the defines string
  55561. */
  55562. BoxParticleEmitter.prototype.getEffectDefines = function () {
  55563. return "#define BOXEMITTER";
  55564. };
  55565. /**
  55566. * Returns the string "BoxEmitter"
  55567. * @returns a string containing the class name
  55568. */
  55569. BoxParticleEmitter.prototype.getClassName = function () {
  55570. return "BoxEmitter";
  55571. };
  55572. /**
  55573. * Serializes the particle system to a JSON object.
  55574. * @returns the JSON object
  55575. */
  55576. BoxParticleEmitter.prototype.serialize = function () {
  55577. var serializationObject = {};
  55578. serializationObject.type = this.getClassName();
  55579. serializationObject.direction1 = this.direction1.asArray();
  55580. ;
  55581. serializationObject.direction2 = this.direction2.asArray();
  55582. ;
  55583. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55584. ;
  55585. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55586. ;
  55587. return serializationObject;
  55588. };
  55589. /**
  55590. * Parse properties from a JSON object
  55591. * @param serializationObject defines the JSON object
  55592. */
  55593. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  55594. this.direction1.copyFrom(serializationObject.direction1);
  55595. this.direction2.copyFrom(serializationObject.direction2);
  55596. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  55597. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  55598. };
  55599. return BoxParticleEmitter;
  55600. }());
  55601. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  55602. })(BABYLON || (BABYLON = {}));
  55603. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  55604. "use strict";
  55605. var BABYLON;
  55606. (function (BABYLON) {
  55607. /**
  55608. * Particle emitter emitting particles from the inside of a cone.
  55609. * It emits the particles alongside the cone volume from the base to the particle.
  55610. * The emission direction might be randomized.
  55611. */
  55612. var ConeParticleEmitter = /** @class */ (function () {
  55613. /**
  55614. * Creates a new instance ConeParticleEmitter
  55615. * @param radius the radius of the emission cone (1 by default)
  55616. * @param angles the cone base angle (PI by default)
  55617. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  55618. */
  55619. function ConeParticleEmitter(radius,
  55620. /**
  55621. * The radius of the emission cone.
  55622. */
  55623. angle,
  55624. /**
  55625. * The cone base angle.
  55626. */
  55627. directionRandomizer) {
  55628. if (radius === void 0) { radius = 1; }
  55629. if (angle === void 0) { angle = Math.PI; }
  55630. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55631. this.angle = angle;
  55632. this.directionRandomizer = directionRandomizer;
  55633. this.radius = radius;
  55634. }
  55635. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  55636. /**
  55637. * Gets the radius of the emission cone.
  55638. */
  55639. get: function () {
  55640. return this._radius;
  55641. },
  55642. /**
  55643. * Sets the radius of the emission cone.
  55644. */
  55645. set: function (value) {
  55646. this._radius = value;
  55647. if (this.angle !== 0) {
  55648. this._height = value / Math.tan(this.angle / 2);
  55649. }
  55650. else {
  55651. this._height = 1;
  55652. }
  55653. },
  55654. enumerable: true,
  55655. configurable: true
  55656. });
  55657. /**
  55658. * Called by the particle System when the direction is computed for the created particle.
  55659. * @param emitPower is the power of the particle (speed)
  55660. * @param worldMatrix is the world matrix of the particle system
  55661. * @param directionToUpdate is the direction vector to update with the result
  55662. * @param particle is the particle we are computed the direction for
  55663. */
  55664. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55665. if (this.angle === 0) {
  55666. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  55667. }
  55668. else {
  55669. // measure the direction Vector from the emitter to the particle.
  55670. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  55671. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55672. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55673. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55674. direction.x += randX;
  55675. direction.y += randY;
  55676. direction.z += randZ;
  55677. direction.normalize();
  55678. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  55679. }
  55680. };
  55681. /**
  55682. * Called by the particle System when the position is computed for the created particle.
  55683. * @param worldMatrix is the world matrix of the particle system
  55684. * @param positionToUpdate is the position vector to update with the result
  55685. * @param particle is the particle we are computed the position for
  55686. */
  55687. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55688. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  55689. var h = BABYLON.Scalar.RandomRange(0, 1);
  55690. // Better distribution in a cone at normal angles.
  55691. h = 1 - h * h;
  55692. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  55693. radius = radius * h;
  55694. var randX = radius * Math.sin(s);
  55695. var randZ = radius * Math.cos(s);
  55696. var randY = h * this._height;
  55697. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55698. };
  55699. /**
  55700. * Clones the current emitter and returns a copy of it
  55701. * @returns the new emitter
  55702. */
  55703. ConeParticleEmitter.prototype.clone = function () {
  55704. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  55705. BABYLON.Tools.DeepCopy(this, newOne);
  55706. return newOne;
  55707. };
  55708. /**
  55709. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55710. * @param effect defines the update shader
  55711. */
  55712. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  55713. effect.setFloat("radius", this.radius);
  55714. effect.setFloat("angle", this.angle);
  55715. effect.setFloat("height", this._height);
  55716. effect.setFloat("directionRandomizer", this.directionRandomizer);
  55717. };
  55718. /**
  55719. * Returns a string to use to update the GPU particles update shader
  55720. * @returns a string containng the defines string
  55721. */
  55722. ConeParticleEmitter.prototype.getEffectDefines = function () {
  55723. return "#define CONEEMITTER";
  55724. };
  55725. /**
  55726. * Returns the string "BoxEmitter"
  55727. * @returns a string containing the class name
  55728. */
  55729. ConeParticleEmitter.prototype.getClassName = function () {
  55730. return "ConeEmitter";
  55731. };
  55732. /**
  55733. * Serializes the particle system to a JSON object.
  55734. * @returns the JSON object
  55735. */
  55736. ConeParticleEmitter.prototype.serialize = function () {
  55737. var serializationObject = {};
  55738. serializationObject.type = this.getClassName();
  55739. serializationObject.radius = this.radius;
  55740. serializationObject.angle = this.angle;
  55741. serializationObject.directionRandomizer = this.directionRandomizer;
  55742. return serializationObject;
  55743. };
  55744. /**
  55745. * Parse properties from a JSON object
  55746. * @param serializationObject defines the JSON object
  55747. */
  55748. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  55749. this.radius = serializationObject.radius;
  55750. this.angle = serializationObject.angle;
  55751. this.directionRandomizer = serializationObject.directionRandomizer;
  55752. };
  55753. return ConeParticleEmitter;
  55754. }());
  55755. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  55756. })(BABYLON || (BABYLON = {}));
  55757. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  55758. "use strict";
  55759. var BABYLON;
  55760. (function (BABYLON) {
  55761. /**
  55762. * Particle emitter emitting particles from the inside of a sphere.
  55763. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  55764. */
  55765. var SphereParticleEmitter = /** @class */ (function () {
  55766. /**
  55767. * Creates a new instance SphereParticleEmitter
  55768. * @param radius the radius of the emission sphere (1 by default)
  55769. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  55770. */
  55771. function SphereParticleEmitter(
  55772. /**
  55773. * The radius of the emission sphere.
  55774. */
  55775. radius,
  55776. /**
  55777. * How much to randomize the particle direction [0-1].
  55778. */
  55779. directionRandomizer) {
  55780. if (radius === void 0) { radius = 1; }
  55781. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55782. this.radius = radius;
  55783. this.directionRandomizer = directionRandomizer;
  55784. }
  55785. /**
  55786. * Called by the particle System when the direction is computed for the created particle.
  55787. * @param emitPower is the power of the particle (speed)
  55788. * @param worldMatrix is the world matrix of the particle system
  55789. * @param directionToUpdate is the direction vector to update with the result
  55790. * @param particle is the particle we are computed the direction for
  55791. */
  55792. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55793. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  55794. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55795. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55796. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55797. direction.x += randX;
  55798. direction.y += randY;
  55799. direction.z += randZ;
  55800. direction.normalize();
  55801. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  55802. };
  55803. /**
  55804. * Called by the particle System when the position is computed for the created particle.
  55805. * @param worldMatrix is the world matrix of the particle system
  55806. * @param positionToUpdate is the position vector to update with the result
  55807. * @param particle is the particle we are computed the position for
  55808. */
  55809. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55810. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  55811. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  55812. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  55813. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  55814. var randY = randRadius * Math.cos(theta);
  55815. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  55816. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55817. };
  55818. /**
  55819. * Clones the current emitter and returns a copy of it
  55820. * @returns the new emitter
  55821. */
  55822. SphereParticleEmitter.prototype.clone = function () {
  55823. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  55824. BABYLON.Tools.DeepCopy(this, newOne);
  55825. return newOne;
  55826. };
  55827. /**
  55828. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55829. * @param effect defines the update shader
  55830. */
  55831. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  55832. effect.setFloat("radius", this.radius);
  55833. effect.setFloat("directionRandomizer", this.directionRandomizer);
  55834. };
  55835. /**
  55836. * Returns a string to use to update the GPU particles update shader
  55837. * @returns a string containng the defines string
  55838. */
  55839. SphereParticleEmitter.prototype.getEffectDefines = function () {
  55840. return "#define SPHEREEMITTER";
  55841. };
  55842. /**
  55843. * Returns the string "SphereParticleEmitter"
  55844. * @returns a string containing the class name
  55845. */
  55846. SphereParticleEmitter.prototype.getClassName = function () {
  55847. return "SphereParticleEmitter";
  55848. };
  55849. /**
  55850. * Serializes the particle system to a JSON object.
  55851. * @returns the JSON object
  55852. */
  55853. SphereParticleEmitter.prototype.serialize = function () {
  55854. var serializationObject = {};
  55855. serializationObject.type = this.getClassName();
  55856. serializationObject.radius = this.radius;
  55857. serializationObject.directionRandomizer = this.directionRandomizer;
  55858. return serializationObject;
  55859. };
  55860. /**
  55861. * Parse properties from a JSON object
  55862. * @param serializationObject defines the JSON object
  55863. */
  55864. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  55865. this.radius = serializationObject.radius;
  55866. this.directionRandomizer = serializationObject.directionRandomizer;
  55867. };
  55868. return SphereParticleEmitter;
  55869. }());
  55870. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  55871. /**
  55872. * Particle emitter emitting particles from the inside of a sphere.
  55873. * It emits the particles randomly between two vectors.
  55874. */
  55875. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  55876. __extends(SphereDirectedParticleEmitter, _super);
  55877. /**
  55878. * Creates a new instance SphereDirectedParticleEmitter
  55879. * @param radius the radius of the emission sphere (1 by default)
  55880. * @param direction1 the min limit of the emission direction (up vector by default)
  55881. * @param direction2 the max limit of the emission direction (up vector by default)
  55882. */
  55883. function SphereDirectedParticleEmitter(radius,
  55884. /**
  55885. * The min limit of the emission direction.
  55886. */
  55887. direction1,
  55888. /**
  55889. * The max limit of the emission direction.
  55890. */
  55891. direction2) {
  55892. if (radius === void 0) { radius = 1; }
  55893. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  55894. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  55895. var _this = _super.call(this, radius) || this;
  55896. _this.direction1 = direction1;
  55897. _this.direction2 = direction2;
  55898. return _this;
  55899. }
  55900. /**
  55901. * Called by the particle System when the direction is computed for the created particle.
  55902. * @param emitPower is the power of the particle (speed)
  55903. * @param worldMatrix is the world matrix of the particle system
  55904. * @param directionToUpdate is the direction vector to update with the result
  55905. * @param particle is the particle we are computed the direction for
  55906. */
  55907. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55908. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  55909. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  55910. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  55911. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  55912. };
  55913. /**
  55914. * Clones the current emitter and returns a copy of it
  55915. * @returns the new emitter
  55916. */
  55917. SphereDirectedParticleEmitter.prototype.clone = function () {
  55918. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  55919. BABYLON.Tools.DeepCopy(this, newOne);
  55920. return newOne;
  55921. };
  55922. /**
  55923. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55924. * @param effect defines the update shader
  55925. */
  55926. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  55927. effect.setFloat("radius", this.radius);
  55928. effect.setVector3("direction1", this.direction1);
  55929. effect.setVector3("direction2", this.direction2);
  55930. };
  55931. /**
  55932. * Returns a string to use to update the GPU particles update shader
  55933. * @returns a string containng the defines string
  55934. */
  55935. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  55936. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  55937. };
  55938. /**
  55939. * Returns the string "SphereDirectedParticleEmitter"
  55940. * @returns a string containing the class name
  55941. */
  55942. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  55943. return "SphereDirectedParticleEmitter";
  55944. };
  55945. /**
  55946. * Serializes the particle system to a JSON object.
  55947. * @returns the JSON object
  55948. */
  55949. SphereDirectedParticleEmitter.prototype.serialize = function () {
  55950. var serializationObject = _super.prototype.serialize.call(this);
  55951. ;
  55952. serializationObject.direction1 = this.direction1.asArray();
  55953. ;
  55954. serializationObject.direction2 = this.direction2.asArray();
  55955. ;
  55956. return serializationObject;
  55957. };
  55958. /**
  55959. * Parse properties from a JSON object
  55960. * @param serializationObject defines the JSON object
  55961. */
  55962. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  55963. _super.prototype.parse.call(this, serializationObject);
  55964. this.direction1.copyFrom(serializationObject.direction1);
  55965. this.direction2.copyFrom(serializationObject.direction2);
  55966. };
  55967. return SphereDirectedParticleEmitter;
  55968. }(SphereParticleEmitter));
  55969. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  55970. })(BABYLON || (BABYLON = {}));
  55971. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  55972. "use strict";
  55973. var __assign = (this && this.__assign) || Object.assign || function(t) {
  55974. for (var s, i = 1, n = arguments.length; i < n; i++) {
  55975. s = arguments[i];
  55976. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  55977. t[p] = s[p];
  55978. }
  55979. return t;
  55980. };
  55981. var BABYLON;
  55982. (function (BABYLON) {
  55983. /**
  55984. * This represents a GPU particle system in Babylon
  55985. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  55986. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  55987. */
  55988. var GPUParticleSystem = /** @class */ (function () {
  55989. /**
  55990. * Instantiates a GPU particle system.
  55991. * 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.
  55992. * @param name The name of the particle system
  55993. * @param capacity The max number of particles alive at the same time
  55994. * @param scene The scene the particle system belongs to
  55995. */
  55996. function GPUParticleSystem(name, options, scene) {
  55997. /**
  55998. * The emitter represents the Mesh or position we are attaching the particle system to.
  55999. */
  56000. this.emitter = null;
  56001. /**
  56002. * The rendering group used by the Particle system to chose when to render.
  56003. */
  56004. this.renderingGroupId = 0;
  56005. /**
  56006. * The layer mask we are rendering the particles through.
  56007. */
  56008. this.layerMask = 0x0FFFFFFF;
  56009. this._targetIndex = 0;
  56010. this._currentRenderId = -1;
  56011. this._started = false;
  56012. this._stopped = false;
  56013. this._timeDelta = 0;
  56014. this._attributesStrideSize = 14;
  56015. this._actualFrame = 0;
  56016. /**
  56017. * List of animations used by the particle system.
  56018. */
  56019. this.animations = [];
  56020. /**
  56021. * An event triggered when the system is disposed.
  56022. */
  56023. this.onDisposeObservable = new BABYLON.Observable();
  56024. /**
  56025. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56026. */
  56027. this.updateSpeed = 0.01;
  56028. /**
  56029. * The amount of time the particle system is running (depends of the overall update speed).
  56030. */
  56031. this.targetStopDuration = 0;
  56032. /**
  56033. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56034. */
  56035. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56036. /**
  56037. * Minimum life time of emitting particles.
  56038. */
  56039. this.minLifeTime = 1;
  56040. /**
  56041. * Maximum life time of emitting particles.
  56042. */
  56043. this.maxLifeTime = 1;
  56044. /**
  56045. * Minimum Size of emitting particles.
  56046. */
  56047. this.minSize = 1;
  56048. /**
  56049. * Maximum Size of emitting particles.
  56050. */
  56051. this.maxSize = 1;
  56052. /**
  56053. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56054. */
  56055. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56056. /**
  56057. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56058. */
  56059. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56060. /**
  56061. * Color the particle will have at the end of its lifetime.
  56062. */
  56063. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56064. /**
  56065. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56066. */
  56067. this.emitRate = 100;
  56068. /**
  56069. * You can use gravity if you want to give an orientation to your particles.
  56070. */
  56071. this.gravity = BABYLON.Vector3.Zero();
  56072. /**
  56073. * Minimum power of emitting particles.
  56074. */
  56075. this.minEmitPower = 1;
  56076. /**
  56077. * Maximum power of emitting particles.
  56078. */
  56079. this.maxEmitPower = 1;
  56080. /**
  56081. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56082. * to override the particles.
  56083. */
  56084. this.forceDepthWrite = false;
  56085. this.id = name;
  56086. this.name = name;
  56087. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56088. this._engine = this._scene.getEngine();
  56089. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56090. this._capacity = fullOptions.capacity;
  56091. this._activeCount = fullOptions.capacity;
  56092. this._currentActiveCount = 0;
  56093. this._scene.particleSystems.push(this);
  56094. this._updateEffectOptions = {
  56095. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  56096. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  56097. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  56098. uniformBuffersNames: [],
  56099. samplers: ["randomSampler"],
  56100. defines: "",
  56101. fallbacks: null,
  56102. onCompiled: null,
  56103. onError: null,
  56104. indexParameters: null,
  56105. maxSimultaneousLights: 0,
  56106. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  56107. };
  56108. // Random data
  56109. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56110. var d = [];
  56111. for (var i = 0; i < maxTextureSize; ++i) {
  56112. d.push(Math.random());
  56113. d.push(Math.random());
  56114. d.push(Math.random());
  56115. d.push(Math.random());
  56116. }
  56117. 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);
  56118. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56119. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56120. this._randomTextureSize = maxTextureSize;
  56121. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56122. }
  56123. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  56124. /**
  56125. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  56126. */
  56127. get: function () {
  56128. if (!BABYLON.Engine.LastCreatedEngine) {
  56129. return false;
  56130. }
  56131. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  56132. },
  56133. enumerable: true,
  56134. configurable: true
  56135. });
  56136. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  56137. /**
  56138. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56139. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56140. */
  56141. get: function () {
  56142. if (this.particleEmitterType.direction1) {
  56143. return this.particleEmitterType.direction1;
  56144. }
  56145. return BABYLON.Vector3.Zero();
  56146. },
  56147. set: function (value) {
  56148. if (this.particleEmitterType.direction1) {
  56149. this.particleEmitterType.direction1 = value;
  56150. }
  56151. },
  56152. enumerable: true,
  56153. configurable: true
  56154. });
  56155. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  56156. /**
  56157. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56158. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56159. */
  56160. get: function () {
  56161. if (this.particleEmitterType.direction2) {
  56162. return this.particleEmitterType.direction2;
  56163. }
  56164. return BABYLON.Vector3.Zero();
  56165. },
  56166. set: function (value) {
  56167. if (this.particleEmitterType.direction2) {
  56168. this.particleEmitterType.direction2 = value;
  56169. }
  56170. },
  56171. enumerable: true,
  56172. configurable: true
  56173. });
  56174. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  56175. /**
  56176. * 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.
  56177. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56178. */
  56179. get: function () {
  56180. if (this.particleEmitterType.minEmitBox) {
  56181. return this.particleEmitterType.minEmitBox;
  56182. }
  56183. return BABYLON.Vector3.Zero();
  56184. },
  56185. set: function (value) {
  56186. if (this.particleEmitterType.minEmitBox) {
  56187. this.particleEmitterType.minEmitBox = value;
  56188. }
  56189. },
  56190. enumerable: true,
  56191. configurable: true
  56192. });
  56193. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  56194. /**
  56195. * 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.
  56196. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56197. */
  56198. get: function () {
  56199. if (this.particleEmitterType.maxEmitBox) {
  56200. return this.particleEmitterType.maxEmitBox;
  56201. }
  56202. return BABYLON.Vector3.Zero();
  56203. },
  56204. set: function (value) {
  56205. if (this.particleEmitterType.maxEmitBox) {
  56206. this.particleEmitterType.maxEmitBox = value;
  56207. }
  56208. },
  56209. enumerable: true,
  56210. configurable: true
  56211. });
  56212. /**
  56213. * Gets the maximum number of particles active at the same time.
  56214. * @returns The max number of active particles.
  56215. */
  56216. GPUParticleSystem.prototype.getCapacity = function () {
  56217. return this._capacity;
  56218. };
  56219. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  56220. /**
  56221. * Gets or set the number of active particles
  56222. */
  56223. get: function () {
  56224. return this._activeCount;
  56225. },
  56226. set: function (value) {
  56227. this._activeCount = Math.min(value, this._capacity);
  56228. },
  56229. enumerable: true,
  56230. configurable: true
  56231. });
  56232. /**
  56233. * Is this system ready to be used/rendered
  56234. * @return true if the system is ready
  56235. */
  56236. GPUParticleSystem.prototype.isReady = function () {
  56237. if (!this._updateEffect) {
  56238. this._recreateUpdateEffect();
  56239. this._recreateRenderEffect();
  56240. return false;
  56241. }
  56242. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56243. return false;
  56244. }
  56245. return true;
  56246. };
  56247. /**
  56248. * Gets Wether the system has been started.
  56249. * @returns True if it has been started, otherwise false.
  56250. */
  56251. GPUParticleSystem.prototype.isStarted = function () {
  56252. return this._started;
  56253. };
  56254. /**
  56255. * Starts the particle system and begins to emit.
  56256. */
  56257. GPUParticleSystem.prototype.start = function () {
  56258. this._started = true;
  56259. this._stopped = false;
  56260. };
  56261. /**
  56262. * Stops the particle system.
  56263. */
  56264. GPUParticleSystem.prototype.stop = function () {
  56265. this._stopped = true;
  56266. };
  56267. /**
  56268. * Remove all active particles
  56269. */
  56270. GPUParticleSystem.prototype.reset = function () {
  56271. this._releaseBuffers();
  56272. this._releaseVAOs();
  56273. this._currentActiveCount = 0;
  56274. this._targetIndex = 0;
  56275. };
  56276. /**
  56277. * Returns the string "GPUParticleSystem"
  56278. * @returns a string containing the class name
  56279. */
  56280. GPUParticleSystem.prototype.getClassName = function () {
  56281. return "GPUParticleSystem";
  56282. };
  56283. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  56284. var updateVertexBuffers = {};
  56285. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  56286. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  56287. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  56288. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  56289. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  56290. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  56291. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  56292. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  56293. this._engine.bindArrayBuffer(null);
  56294. return vao;
  56295. };
  56296. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  56297. var renderVertexBuffers = {};
  56298. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  56299. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  56300. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  56301. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  56302. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  56303. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  56304. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  56305. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  56306. this._engine.bindArrayBuffer(null);
  56307. return vao;
  56308. };
  56309. GPUParticleSystem.prototype._initialize = function (force) {
  56310. if (force === void 0) { force = false; }
  56311. if (this._buffer0 && !force) {
  56312. return;
  56313. }
  56314. var engine = this._scene.getEngine();
  56315. var data = new Array();
  56316. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  56317. // position
  56318. data.push(0.0);
  56319. data.push(0.0);
  56320. data.push(0.0);
  56321. // Age and life
  56322. data.push(0.0); // create the particle as a dead one to create a new one at start
  56323. data.push(0.0);
  56324. // Seed
  56325. data.push(Math.random());
  56326. // Size
  56327. data.push(0.0);
  56328. // color
  56329. data.push(0.0);
  56330. data.push(0.0);
  56331. data.push(0.0);
  56332. data.push(0.0);
  56333. // direction
  56334. data.push(0.0);
  56335. data.push(0.0);
  56336. data.push(0.0);
  56337. }
  56338. // Sprite data
  56339. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  56340. -0.5, 0.5, 0, 1,
  56341. -0.5, -0.5, 0, 0,
  56342. 0.5, -0.5, 1, 0]);
  56343. // Buffers
  56344. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56345. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56346. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  56347. // Update VAO
  56348. this._updateVAO = [];
  56349. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  56350. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  56351. // Render VAO
  56352. this._renderVAO = [];
  56353. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  56354. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  56355. // Links
  56356. this._sourceBuffer = this._buffer0;
  56357. this._targetBuffer = this._buffer1;
  56358. };
  56359. /** @ignore */
  56360. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  56361. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  56362. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  56363. return;
  56364. }
  56365. this._updateEffectOptions.defines = defines;
  56366. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  56367. };
  56368. /** @ignore */
  56369. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  56370. var defines = "";
  56371. if (this._scene.clipPlane) {
  56372. defines = "\n#define CLIPPLANE";
  56373. }
  56374. if (this._renderEffect && this._renderEffect.defines === defines) {
  56375. return;
  56376. }
  56377. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  56378. };
  56379. /**
  56380. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56381. */
  56382. GPUParticleSystem.prototype.animate = function () {
  56383. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  56384. this._actualFrame += this._timeDelta;
  56385. if (!this._stopped) {
  56386. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  56387. this.stop();
  56388. }
  56389. }
  56390. };
  56391. /**
  56392. * Renders the particle system in its current state.
  56393. * @returns the current number of particles
  56394. */
  56395. GPUParticleSystem.prototype.render = function () {
  56396. if (!this._started) {
  56397. return 0;
  56398. }
  56399. this._recreateUpdateEffect();
  56400. this._recreateRenderEffect();
  56401. if (!this.isReady()) {
  56402. return 0;
  56403. }
  56404. if (this._currentRenderId === this._scene.getRenderId()) {
  56405. return 0;
  56406. }
  56407. this._currentRenderId = this._scene.getRenderId();
  56408. // Get everything ready to render
  56409. this._initialize();
  56410. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  56411. // Enable update effect
  56412. this._engine.enableEffect(this._updateEffect);
  56413. this._engine.setState(false);
  56414. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  56415. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  56416. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  56417. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  56418. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  56419. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  56420. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  56421. this._updateEffect.setDirectColor4("color1", this.color1);
  56422. this._updateEffect.setDirectColor4("color2", this.color2);
  56423. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  56424. this._updateEffect.setVector3("gravity", this.gravity);
  56425. if (this.particleEmitterType) {
  56426. this.particleEmitterType.applyToShader(this._updateEffect);
  56427. }
  56428. var emitterWM;
  56429. if (this.emitter.position) {
  56430. var emitterMesh = this.emitter;
  56431. emitterWM = emitterMesh.getWorldMatrix();
  56432. }
  56433. else {
  56434. var emitterPosition = this.emitter;
  56435. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56436. }
  56437. this._updateEffect.setMatrix("emitterWM", emitterWM);
  56438. // Bind source VAO
  56439. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  56440. // Update
  56441. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  56442. this._engine.setRasterizerState(false);
  56443. this._engine.beginTransformFeedback();
  56444. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  56445. this._engine.endTransformFeedback();
  56446. this._engine.setRasterizerState(true);
  56447. this._engine.bindTransformFeedbackBuffer(null);
  56448. // Enable render effect
  56449. this._engine.enableEffect(this._renderEffect);
  56450. var viewMatrix = this._scene.getViewMatrix();
  56451. this._renderEffect.setMatrix("view", viewMatrix);
  56452. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  56453. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  56454. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  56455. if (this._scene.clipPlane) {
  56456. var clipPlane = this._scene.clipPlane;
  56457. var invView = viewMatrix.clone();
  56458. invView.invert();
  56459. this._renderEffect.setMatrix("invView", invView);
  56460. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56461. }
  56462. // Draw order
  56463. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  56464. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56465. }
  56466. else {
  56467. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56468. }
  56469. if (this.forceDepthWrite) {
  56470. this._engine.setDepthWrite(true);
  56471. }
  56472. // Bind source VAO
  56473. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  56474. // Render
  56475. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  56476. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56477. // Switch VAOs
  56478. this._targetIndex++;
  56479. if (this._targetIndex === 2) {
  56480. this._targetIndex = 0;
  56481. }
  56482. // Switch buffers
  56483. var tmpBuffer = this._sourceBuffer;
  56484. this._sourceBuffer = this._targetBuffer;
  56485. this._targetBuffer = tmpBuffer;
  56486. return this._currentActiveCount;
  56487. };
  56488. /**
  56489. * Rebuilds the particle system
  56490. */
  56491. GPUParticleSystem.prototype.rebuild = function () {
  56492. this._initialize(true);
  56493. };
  56494. GPUParticleSystem.prototype._releaseBuffers = function () {
  56495. if (this._buffer0) {
  56496. this._buffer0.dispose();
  56497. this._buffer0 = null;
  56498. }
  56499. if (this._buffer1) {
  56500. this._buffer1.dispose();
  56501. this._buffer1 = null;
  56502. }
  56503. if (this._spriteBuffer) {
  56504. this._spriteBuffer.dispose();
  56505. this._spriteBuffer = null;
  56506. }
  56507. };
  56508. GPUParticleSystem.prototype._releaseVAOs = function () {
  56509. if (!this._updateVAO) {
  56510. return;
  56511. }
  56512. for (var index = 0; index < this._updateVAO.length; index++) {
  56513. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  56514. }
  56515. this._updateVAO = [];
  56516. for (var index = 0; index < this._renderVAO.length; index++) {
  56517. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  56518. }
  56519. this._renderVAO = [];
  56520. };
  56521. /**
  56522. * Disposes the particle system and free the associated resources
  56523. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56524. */
  56525. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  56526. if (disposeTexture === void 0) { disposeTexture = true; }
  56527. var index = this._scene.particleSystems.indexOf(this);
  56528. if (index > -1) {
  56529. this._scene.particleSystems.splice(index, 1);
  56530. }
  56531. this._releaseBuffers();
  56532. this._releaseVAOs();
  56533. if (this._randomTexture) {
  56534. this._randomTexture.dispose();
  56535. this._randomTexture = null;
  56536. }
  56537. if (disposeTexture && this.particleTexture) {
  56538. this.particleTexture.dispose();
  56539. this.particleTexture = null;
  56540. }
  56541. // Callback
  56542. this.onDisposeObservable.notifyObservers(this);
  56543. this.onDisposeObservable.clear();
  56544. };
  56545. /**
  56546. * Clones the particle system.
  56547. * @param name The name of the cloned object
  56548. * @param newEmitter The new emitter to use
  56549. * @returns the cloned particle system
  56550. */
  56551. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  56552. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  56553. BABYLON.Tools.DeepCopy(this, result);
  56554. if (newEmitter === undefined) {
  56555. newEmitter = this.emitter;
  56556. }
  56557. result.emitter = newEmitter;
  56558. if (this.particleTexture) {
  56559. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56560. }
  56561. return result;
  56562. };
  56563. /**
  56564. * Serializes the particle system to a JSON object.
  56565. * @returns the JSON object
  56566. */
  56567. GPUParticleSystem.prototype.serialize = function () {
  56568. var serializationObject = {};
  56569. serializationObject.name = this.name;
  56570. serializationObject.id = this.id;
  56571. // Emitter
  56572. if (this.emitter.position) {
  56573. var emitterMesh = this.emitter;
  56574. serializationObject.emitterId = emitterMesh.id;
  56575. }
  56576. else {
  56577. var emitterPosition = this.emitter;
  56578. serializationObject.emitter = emitterPosition.asArray();
  56579. }
  56580. serializationObject.capacity = this.getCapacity();
  56581. if (this.particleTexture) {
  56582. serializationObject.textureName = this.particleTexture.name;
  56583. }
  56584. // Animations
  56585. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56586. // Particle system
  56587. serializationObject.activeParticleCount = this.activeParticleCount;
  56588. serializationObject.randomTextureSize = this._randomTextureSize;
  56589. serializationObject.minSize = this.minSize;
  56590. serializationObject.maxSize = this.maxSize;
  56591. serializationObject.minEmitPower = this.minEmitPower;
  56592. serializationObject.maxEmitPower = this.maxEmitPower;
  56593. serializationObject.minLifeTime = this.minLifeTime;
  56594. serializationObject.maxLifeTime = this.maxLifeTime;
  56595. serializationObject.emitRate = this.emitRate;
  56596. serializationObject.gravity = this.gravity.asArray();
  56597. serializationObject.color1 = this.color1.asArray();
  56598. serializationObject.color2 = this.color2.asArray();
  56599. serializationObject.colorDead = this.colorDead.asArray();
  56600. serializationObject.updateSpeed = this.updateSpeed;
  56601. serializationObject.targetStopDuration = this.targetStopDuration;
  56602. serializationObject.blendMode = this.blendMode;
  56603. // Emitter
  56604. if (this.particleEmitterType) {
  56605. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56606. }
  56607. return serializationObject;
  56608. };
  56609. /**
  56610. * Parses a JSON object to create a GPU particle system.
  56611. * @param parsedParticleSystem The JSON object to parse
  56612. * @param scene The scene to create the particle system in
  56613. * @param rootUrl The root url to use to load external dependencies like texture
  56614. * @returns the parsed GPU particle system
  56615. */
  56616. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56617. var name = parsedParticleSystem.name;
  56618. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  56619. if (parsedParticleSystem.id) {
  56620. particleSystem.id = parsedParticleSystem.id;
  56621. }
  56622. // Texture
  56623. if (parsedParticleSystem.textureName) {
  56624. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56625. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56626. }
  56627. // Emitter
  56628. if (parsedParticleSystem.emitterId) {
  56629. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56630. }
  56631. else {
  56632. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56633. }
  56634. // Animations
  56635. if (parsedParticleSystem.animations) {
  56636. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56637. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56638. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56639. }
  56640. }
  56641. // Particle system
  56642. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  56643. particleSystem.minSize = parsedParticleSystem.minSize;
  56644. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56645. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56646. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56647. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56648. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56649. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56650. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56651. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56652. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56653. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56654. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56655. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56656. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56657. // Emitter
  56658. if (parsedParticleSystem.particleEmitterType) {
  56659. var emitterType = void 0;
  56660. switch (parsedParticleSystem.particleEmitterType.type) {
  56661. case "SphereEmitter":
  56662. emitterType = new BABYLON.SphereParticleEmitter();
  56663. break;
  56664. case "SphereDirectedParticleEmitter":
  56665. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56666. break;
  56667. case "ConeEmitter":
  56668. emitterType = new BABYLON.ConeParticleEmitter();
  56669. break;
  56670. case "BoxEmitter":
  56671. default:
  56672. emitterType = new BABYLON.BoxParticleEmitter();
  56673. break;
  56674. }
  56675. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56676. particleSystem.particleEmitterType = emitterType;
  56677. }
  56678. return particleSystem;
  56679. };
  56680. return GPUParticleSystem;
  56681. }());
  56682. BABYLON.GPUParticleSystem = GPUParticleSystem;
  56683. })(BABYLON || (BABYLON = {}));
  56684. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  56685. "use strict";
  56686. var BABYLON;
  56687. (function (BABYLON) {
  56688. /**
  56689. * Represents one particle of a solid particle system.
  56690. */
  56691. var SolidParticle = /** @class */ (function () {
  56692. /**
  56693. * Creates a Solid Particle object.
  56694. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  56695. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  56696. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  56697. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  56698. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  56699. * @param shapeId (integer) is the model shape identifier in the SPS.
  56700. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  56701. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  56702. */
  56703. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  56704. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  56705. /**
  56706. * particle global index
  56707. */
  56708. this.idx = 0;
  56709. /**
  56710. * The color of the particle
  56711. */
  56712. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56713. /**
  56714. * The world space position of the particle.
  56715. */
  56716. this.position = BABYLON.Vector3.Zero();
  56717. /**
  56718. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  56719. */
  56720. this.rotation = BABYLON.Vector3.Zero();
  56721. /**
  56722. * The scaling of the particle.
  56723. */
  56724. this.scaling = BABYLON.Vector3.One();
  56725. /**
  56726. * The uvs of the particle.
  56727. */
  56728. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  56729. /**
  56730. * The current speed of the particle.
  56731. */
  56732. this.velocity = BABYLON.Vector3.Zero();
  56733. /**
  56734. * The pivot point in the particle local space.
  56735. */
  56736. this.pivot = BABYLON.Vector3.Zero();
  56737. /**
  56738. * Must the particle be translated from its pivot point in its local space ?
  56739. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  56740. * Default : false
  56741. */
  56742. this.translateFromPivot = false;
  56743. /**
  56744. * Is the particle active or not ?
  56745. */
  56746. this.alive = true;
  56747. /**
  56748. * Is the particle visible or not ?
  56749. */
  56750. this.isVisible = true;
  56751. /**
  56752. * Index of this particle in the global "positions" array (Internal use)
  56753. */
  56754. this._pos = 0;
  56755. /**
  56756. * Index of this particle in the global "indices" array (Internal use)
  56757. */
  56758. this._ind = 0;
  56759. /**
  56760. * ModelShape id of this particle
  56761. */
  56762. this.shapeId = 0;
  56763. /**
  56764. * Index of the particle in its shape id (Internal use)
  56765. */
  56766. this.idxInShape = 0;
  56767. /**
  56768. * Still set as invisible in order to skip useless computations (Internal use)
  56769. */
  56770. this._stillInvisible = false;
  56771. /**
  56772. * Last computed particle rotation matrix
  56773. */
  56774. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  56775. /**
  56776. * Parent particle Id, if any.
  56777. * Default null.
  56778. */
  56779. this.parentId = null;
  56780. /**
  56781. * Internal global position in the SPS.
  56782. */
  56783. this._globalPosition = BABYLON.Vector3.Zero();
  56784. this.idx = particleIndex;
  56785. this._pos = positionIndex;
  56786. this._ind = indiceIndex;
  56787. this._model = model;
  56788. this.shapeId = shapeId;
  56789. this.idxInShape = idxInShape;
  56790. this._sps = sps;
  56791. if (modelBoundingInfo) {
  56792. this._modelBoundingInfo = modelBoundingInfo;
  56793. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  56794. }
  56795. }
  56796. Object.defineProperty(SolidParticle.prototype, "scale", {
  56797. /**
  56798. * Legacy support, changed scale to scaling
  56799. */
  56800. get: function () {
  56801. return this.scaling;
  56802. },
  56803. /**
  56804. * Legacy support, changed scale to scaling
  56805. */
  56806. set: function (scale) {
  56807. this.scaling = scale;
  56808. },
  56809. enumerable: true,
  56810. configurable: true
  56811. });
  56812. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  56813. /**
  56814. * Legacy support, changed quaternion to rotationQuaternion
  56815. */
  56816. get: function () {
  56817. return this.rotationQuaternion;
  56818. },
  56819. /**
  56820. * Legacy support, changed quaternion to rotationQuaternion
  56821. */
  56822. set: function (q) {
  56823. this.rotationQuaternion = q;
  56824. },
  56825. enumerable: true,
  56826. configurable: true
  56827. });
  56828. /**
  56829. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  56830. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  56831. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  56832. * @returns true if it intersects
  56833. */
  56834. SolidParticle.prototype.intersectsMesh = function (target) {
  56835. if (!this._boundingInfo || !target._boundingInfo) {
  56836. return false;
  56837. }
  56838. if (this._sps._bSphereOnly) {
  56839. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  56840. }
  56841. return this._boundingInfo.intersects(target._boundingInfo, false);
  56842. };
  56843. return SolidParticle;
  56844. }());
  56845. BABYLON.SolidParticle = SolidParticle;
  56846. /**
  56847. * Represents the shape of the model used by one particle of a solid particle system.
  56848. * SPS internal tool, don't use it manually.
  56849. */
  56850. var ModelShape = /** @class */ (function () {
  56851. /**
  56852. * 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.
  56853. * SPS internal tool, don't use it manually.
  56854. * @ignore
  56855. */
  56856. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  56857. /**
  56858. * length of the shape in the model indices array (internal use)
  56859. */
  56860. this._indicesLength = 0;
  56861. this.shapeID = id;
  56862. this._shape = shape;
  56863. this._indicesLength = indicesLength;
  56864. this._shapeUV = shapeUV;
  56865. this._positionFunction = posFunction;
  56866. this._vertexFunction = vtxFunction;
  56867. }
  56868. return ModelShape;
  56869. }());
  56870. BABYLON.ModelShape = ModelShape;
  56871. /**
  56872. * Represents a Depth Sorted Particle in the solid particle system.
  56873. */
  56874. var DepthSortedParticle = /** @class */ (function () {
  56875. function DepthSortedParticle() {
  56876. /**
  56877. * Index of the particle in the "indices" array
  56878. */
  56879. this.ind = 0;
  56880. /**
  56881. * Length of the particle shape in the "indices" array
  56882. */
  56883. this.indicesLength = 0;
  56884. /**
  56885. * Squared distance from the particle to the camera
  56886. */
  56887. this.sqDistance = 0.0;
  56888. }
  56889. return DepthSortedParticle;
  56890. }());
  56891. BABYLON.DepthSortedParticle = DepthSortedParticle;
  56892. })(BABYLON || (BABYLON = {}));
  56893. //# sourceMappingURL=babylon.solidParticle.js.map
  56894. "use strict";
  56895. var BABYLON;
  56896. (function (BABYLON) {
  56897. /**
  56898. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  56899. *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.
  56900. * The SPS is also a particle system. It provides some methods to manage the particles.
  56901. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  56902. *
  56903. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  56904. */
  56905. var SolidParticleSystem = /** @class */ (function () {
  56906. /**
  56907. * Creates a SPS (Solid Particle System) object.
  56908. * @param name (String) is the SPS name, this will be the underlying mesh name.
  56909. * @param scene (Scene) is the scene in which the SPS is added.
  56910. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  56911. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  56912. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  56913. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  56914. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  56915. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  56916. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  56917. */
  56918. function SolidParticleSystem(name, scene, options) {
  56919. /**
  56920. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  56921. * Example : var p = SPS.particles[i];
  56922. */
  56923. this.particles = new Array();
  56924. /**
  56925. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  56926. */
  56927. this.nbParticles = 0;
  56928. /**
  56929. * If the particles must ever face the camera (default false). Useful for planar particles.
  56930. */
  56931. this.billboard = false;
  56932. /**
  56933. * Recompute normals when adding a shape
  56934. */
  56935. this.recomputeNormals = true;
  56936. /**
  56937. * This a counter ofr your own usage. It's not set by any SPS functions.
  56938. */
  56939. this.counter = 0;
  56940. /**
  56941. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  56942. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  56943. */
  56944. this.vars = {};
  56945. /**
  56946. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  56947. */
  56948. this._bSphereOnly = false;
  56949. /**
  56950. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  56951. */
  56952. this._bSphereRadiusFactor = 1.0;
  56953. this._positions = new Array();
  56954. this._indices = new Array();
  56955. this._normals = new Array();
  56956. this._colors = new Array();
  56957. this._uvs = new Array();
  56958. this._index = 0; // indices index
  56959. this._updatable = true;
  56960. this._pickable = false;
  56961. this._isVisibilityBoxLocked = false;
  56962. this._alwaysVisible = false;
  56963. this._depthSort = false;
  56964. this._shapeCounter = 0;
  56965. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  56966. this._color = new BABYLON.Color4(0, 0, 0, 0);
  56967. this._computeParticleColor = true;
  56968. this._computeParticleTexture = true;
  56969. this._computeParticleRotation = true;
  56970. this._computeParticleVertex = false;
  56971. this._computeBoundingBox = false;
  56972. this._depthSortParticles = true;
  56973. this._cam_axisZ = BABYLON.Vector3.Zero();
  56974. this._cam_axisY = BABYLON.Vector3.Zero();
  56975. this._cam_axisX = BABYLON.Vector3.Zero();
  56976. this._axisZ = BABYLON.Axis.Z;
  56977. this._camDir = BABYLON.Vector3.Zero();
  56978. this._camInvertedPosition = BABYLON.Vector3.Zero();
  56979. this._rotMatrix = new BABYLON.Matrix();
  56980. this._invertMatrix = new BABYLON.Matrix();
  56981. this._rotated = BABYLON.Vector3.Zero();
  56982. this._quaternion = new BABYLON.Quaternion();
  56983. this._vertex = BABYLON.Vector3.Zero();
  56984. this._normal = BABYLON.Vector3.Zero();
  56985. this._yaw = 0.0;
  56986. this._pitch = 0.0;
  56987. this._roll = 0.0;
  56988. this._halfroll = 0.0;
  56989. this._halfpitch = 0.0;
  56990. this._halfyaw = 0.0;
  56991. this._sinRoll = 0.0;
  56992. this._cosRoll = 0.0;
  56993. this._sinPitch = 0.0;
  56994. this._cosPitch = 0.0;
  56995. this._sinYaw = 0.0;
  56996. this._cosYaw = 0.0;
  56997. this._mustUnrotateFixedNormals = false;
  56998. this._minimum = BABYLON.Vector3.Zero();
  56999. this._maximum = BABYLON.Vector3.Zero();
  57000. this._minBbox = BABYLON.Vector3.Zero();
  57001. this._maxBbox = BABYLON.Vector3.Zero();
  57002. this._particlesIntersect = false;
  57003. this._depthSortFunction = function (p1, p2) {
  57004. return (p2.sqDistance - p1.sqDistance);
  57005. };
  57006. this._needs32Bits = false;
  57007. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  57008. this._scaledPivot = BABYLON.Vector3.Zero();
  57009. this._particleHasParent = false;
  57010. this.name = name;
  57011. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57012. this._camera = scene.activeCamera;
  57013. this._pickable = options ? options.isPickable : false;
  57014. this._depthSort = options ? options.enableDepthSort : false;
  57015. this._particlesIntersect = options ? options.particleIntersection : false;
  57016. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  57017. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  57018. if (options && options.updatable) {
  57019. this._updatable = options.updatable;
  57020. }
  57021. else {
  57022. this._updatable = true;
  57023. }
  57024. if (this._pickable) {
  57025. this.pickedParticles = [];
  57026. }
  57027. if (this._depthSort) {
  57028. this.depthSortedParticles = [];
  57029. }
  57030. }
  57031. /**
  57032. * Builds the SPS underlying mesh. Returns a standard Mesh.
  57033. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  57034. * @returns the created mesh
  57035. */
  57036. SolidParticleSystem.prototype.buildMesh = function () {
  57037. if (this.nbParticles === 0) {
  57038. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  57039. this.addShape(triangle, 1);
  57040. triangle.dispose();
  57041. }
  57042. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  57043. this._positions32 = new Float32Array(this._positions);
  57044. this._uvs32 = new Float32Array(this._uvs);
  57045. this._colors32 = new Float32Array(this._colors);
  57046. if (this.recomputeNormals) {
  57047. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  57048. }
  57049. this._normals32 = new Float32Array(this._normals);
  57050. this._fixedNormal32 = new Float32Array(this._normals);
  57051. if (this._mustUnrotateFixedNormals) {
  57052. this._unrotateFixedNormals();
  57053. }
  57054. var vertexData = new BABYLON.VertexData();
  57055. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  57056. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  57057. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  57058. if (this._uvs32) {
  57059. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  57060. ;
  57061. }
  57062. if (this._colors32) {
  57063. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  57064. }
  57065. var mesh = new BABYLON.Mesh(this.name, this._scene);
  57066. vertexData.applyToMesh(mesh, this._updatable);
  57067. this.mesh = mesh;
  57068. this.mesh.isPickable = this._pickable;
  57069. // free memory
  57070. if (!this._depthSort) {
  57071. this._indices = null;
  57072. }
  57073. this._positions = null;
  57074. this._normals = null;
  57075. this._uvs = null;
  57076. this._colors = null;
  57077. if (!this._updatable) {
  57078. this.particles.length = 0;
  57079. }
  57080. return mesh;
  57081. };
  57082. /**
  57083. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  57084. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  57085. * Thus the particles generated from `digest()` have their property `position` set yet.
  57086. * @param mesh ( Mesh ) is the mesh to be digested
  57087. * @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
  57088. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  57089. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  57090. * @returns the current SPS
  57091. */
  57092. SolidParticleSystem.prototype.digest = function (mesh, options) {
  57093. var size = (options && options.facetNb) || 1;
  57094. var number = (options && options.number) || 0;
  57095. var delta = (options && options.delta) || 0;
  57096. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57097. var meshInd = mesh.getIndices();
  57098. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57099. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57100. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57101. var f = 0; // facet counter
  57102. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57103. // compute size from number
  57104. if (number) {
  57105. number = (number > totalFacets) ? totalFacets : number;
  57106. size = Math.round(totalFacets / number);
  57107. delta = 0;
  57108. }
  57109. else {
  57110. size = (size > totalFacets) ? totalFacets : size;
  57111. }
  57112. var facetPos = []; // submesh positions
  57113. var facetInd = []; // submesh indices
  57114. var facetUV = []; // submesh UV
  57115. var facetCol = []; // submesh colors
  57116. var barycenter = BABYLON.Vector3.Zero();
  57117. var sizeO = size;
  57118. while (f < totalFacets) {
  57119. size = sizeO + Math.floor((1 + delta) * Math.random());
  57120. if (f > totalFacets - size) {
  57121. size = totalFacets - f;
  57122. }
  57123. // reset temp arrays
  57124. facetPos.length = 0;
  57125. facetInd.length = 0;
  57126. facetUV.length = 0;
  57127. facetCol.length = 0;
  57128. // iterate over "size" facets
  57129. var fi = 0;
  57130. for (var j = f * 3; j < (f + size) * 3; j++) {
  57131. facetInd.push(fi);
  57132. var i = meshInd[j];
  57133. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57134. if (meshUV) {
  57135. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57136. }
  57137. if (meshCol) {
  57138. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57139. }
  57140. fi++;
  57141. }
  57142. // create a model shape for each single particle
  57143. var idx = this.nbParticles;
  57144. var shape = this._posToShape(facetPos);
  57145. var shapeUV = this._uvsToShapeUV(facetUV);
  57146. // compute the barycenter of the shape
  57147. var v;
  57148. for (v = 0; v < shape.length; v++) {
  57149. barycenter.addInPlace(shape[v]);
  57150. }
  57151. barycenter.scaleInPlace(1 / shape.length);
  57152. // shift the shape from its barycenter to the origin
  57153. for (v = 0; v < shape.length; v++) {
  57154. shape[v].subtractInPlace(barycenter);
  57155. }
  57156. var bInfo;
  57157. if (this._particlesIntersect) {
  57158. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  57159. }
  57160. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  57161. // add the particle in the SPS
  57162. var currentPos = this._positions.length;
  57163. var currentInd = this._indices.length;
  57164. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  57165. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  57166. // initialize the particle position
  57167. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57168. this._index += shape.length;
  57169. idx++;
  57170. this.nbParticles++;
  57171. this._shapeCounter++;
  57172. f += size;
  57173. }
  57174. return this;
  57175. };
  57176. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  57177. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  57178. var index = 0;
  57179. var idx = 0;
  57180. for (var p = 0; p < this.particles.length; p++) {
  57181. this._particle = this.particles[p];
  57182. this._shape = this._particle._model._shape;
  57183. if (this._particle.rotationQuaternion) {
  57184. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57185. }
  57186. else {
  57187. this._yaw = this._particle.rotation.y;
  57188. this._pitch = this._particle.rotation.x;
  57189. this._roll = this._particle.rotation.z;
  57190. this._quaternionRotationYPR();
  57191. }
  57192. this._quaternionToRotationMatrix();
  57193. this._rotMatrix.invertToRef(this._invertMatrix);
  57194. for (var pt = 0; pt < this._shape.length; pt++) {
  57195. idx = index + pt * 3;
  57196. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  57197. this._fixedNormal32[idx] = this._normal.x;
  57198. this._fixedNormal32[idx + 1] = this._normal.y;
  57199. this._fixedNormal32[idx + 2] = this._normal.z;
  57200. }
  57201. index = idx + 3;
  57202. }
  57203. };
  57204. //reset copy
  57205. SolidParticleSystem.prototype._resetCopy = function () {
  57206. this._copy.position.x = 0;
  57207. this._copy.position.y = 0;
  57208. this._copy.position.z = 0;
  57209. this._copy.rotation.x = 0;
  57210. this._copy.rotation.y = 0;
  57211. this._copy.rotation.z = 0;
  57212. this._copy.rotationQuaternion = null;
  57213. this._copy.scaling.x = 1.0;
  57214. this._copy.scaling.y = 1.0;
  57215. this._copy.scaling.z = 1.0;
  57216. this._copy.uvs.x = 0;
  57217. this._copy.uvs.y = 0;
  57218. this._copy.uvs.z = 1.0;
  57219. this._copy.uvs.w = 1.0;
  57220. this._copy.color = null;
  57221. this._copy.translateFromPivot = false;
  57222. };
  57223. // _meshBuilder : inserts the shape model in the global SPS mesh
  57224. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  57225. var i;
  57226. var u = 0;
  57227. var c = 0;
  57228. var n = 0;
  57229. this._resetCopy();
  57230. if (options && options.positionFunction) {
  57231. options.positionFunction(this._copy, idx, idxInShape);
  57232. this._mustUnrotateFixedNormals = true;
  57233. }
  57234. if (this._copy.rotationQuaternion) {
  57235. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57236. }
  57237. else {
  57238. this._yaw = this._copy.rotation.y;
  57239. this._pitch = this._copy.rotation.x;
  57240. this._roll = this._copy.rotation.z;
  57241. this._quaternionRotationYPR();
  57242. }
  57243. this._quaternionToRotationMatrix();
  57244. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  57245. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  57246. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  57247. if (this._copy.translateFromPivot) {
  57248. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57249. }
  57250. else {
  57251. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57252. }
  57253. for (i = 0; i < shape.length; i++) {
  57254. this._vertex.x = shape[i].x;
  57255. this._vertex.y = shape[i].y;
  57256. this._vertex.z = shape[i].z;
  57257. if (options && options.vertexFunction) {
  57258. options.vertexFunction(this._copy, this._vertex, i);
  57259. }
  57260. this._vertex.x *= this._copy.scaling.x;
  57261. this._vertex.y *= this._copy.scaling.y;
  57262. this._vertex.z *= this._copy.scaling.z;
  57263. this._vertex.x -= this._scaledPivot.x;
  57264. this._vertex.y -= this._scaledPivot.y;
  57265. this._vertex.z -= this._scaledPivot.z;
  57266. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57267. this._rotated.addInPlace(this._pivotBackTranslation);
  57268. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  57269. if (meshUV) {
  57270. 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);
  57271. u += 2;
  57272. }
  57273. if (this._copy.color) {
  57274. this._color = this._copy.color;
  57275. }
  57276. else if (meshCol && meshCol[c] !== undefined) {
  57277. this._color.r = meshCol[c];
  57278. this._color.g = meshCol[c + 1];
  57279. this._color.b = meshCol[c + 2];
  57280. this._color.a = meshCol[c + 3];
  57281. }
  57282. else {
  57283. this._color.r = 1.0;
  57284. this._color.g = 1.0;
  57285. this._color.b = 1.0;
  57286. this._color.a = 1.0;
  57287. }
  57288. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  57289. c += 4;
  57290. if (!this.recomputeNormals && meshNor) {
  57291. this._normal.x = meshNor[n];
  57292. this._normal.y = meshNor[n + 1];
  57293. this._normal.z = meshNor[n + 2];
  57294. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  57295. normals.push(this._normal.x, this._normal.y, this._normal.z);
  57296. n += 3;
  57297. }
  57298. }
  57299. for (i = 0; i < meshInd.length; i++) {
  57300. var current_ind = p + meshInd[i];
  57301. indices.push(current_ind);
  57302. if (current_ind > 65535) {
  57303. this._needs32Bits = true;
  57304. }
  57305. }
  57306. if (this._pickable) {
  57307. var nbfaces = meshInd.length / 3;
  57308. for (i = 0; i < nbfaces; i++) {
  57309. this.pickedParticles.push({ idx: idx, faceId: i });
  57310. }
  57311. }
  57312. if (this._depthSort) {
  57313. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  57314. }
  57315. return this._copy;
  57316. };
  57317. // returns a shape array from positions array
  57318. SolidParticleSystem.prototype._posToShape = function (positions) {
  57319. var shape = [];
  57320. for (var i = 0; i < positions.length; i += 3) {
  57321. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  57322. }
  57323. return shape;
  57324. };
  57325. // returns a shapeUV array from a Vector4 uvs
  57326. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  57327. var shapeUV = [];
  57328. if (uvs) {
  57329. for (var i = 0; i < uvs.length; i++)
  57330. shapeUV.push(uvs[i]);
  57331. }
  57332. return shapeUV;
  57333. };
  57334. // adds a new particle object in the particles array
  57335. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  57336. if (bInfo === void 0) { bInfo = null; }
  57337. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  57338. this.particles.push(sp);
  57339. return sp;
  57340. };
  57341. /**
  57342. * Adds some particles to the SPS from the model shape. Returns the shape id.
  57343. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  57344. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  57345. * @param nb (positive integer) the number of particles to be created from this model
  57346. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  57347. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  57348. * @returns the number of shapes in the system
  57349. */
  57350. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  57351. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57352. var meshInd = mesh.getIndices();
  57353. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57354. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57355. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57356. var bbInfo;
  57357. if (this._particlesIntersect) {
  57358. bbInfo = mesh.getBoundingInfo();
  57359. }
  57360. var shape = this._posToShape(meshPos);
  57361. var shapeUV = this._uvsToShapeUV(meshUV);
  57362. var posfunc = options ? options.positionFunction : null;
  57363. var vtxfunc = options ? options.vertexFunction : null;
  57364. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  57365. // particles
  57366. var sp;
  57367. var currentCopy;
  57368. var idx = this.nbParticles;
  57369. for (var i = 0; i < nb; i++) {
  57370. var currentPos = this._positions.length;
  57371. var currentInd = this._indices.length;
  57372. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  57373. if (this._updatable) {
  57374. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  57375. sp.position.copyFrom(currentCopy.position);
  57376. sp.rotation.copyFrom(currentCopy.rotation);
  57377. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  57378. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  57379. }
  57380. if (currentCopy.color && sp.color) {
  57381. sp.color.copyFrom(currentCopy.color);
  57382. }
  57383. sp.scaling.copyFrom(currentCopy.scaling);
  57384. sp.uvs.copyFrom(currentCopy.uvs);
  57385. }
  57386. this._index += shape.length;
  57387. idx++;
  57388. }
  57389. this.nbParticles += nb;
  57390. this._shapeCounter++;
  57391. return this._shapeCounter - 1;
  57392. };
  57393. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  57394. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  57395. this._resetCopy();
  57396. if (particle._model._positionFunction) {
  57397. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  57398. }
  57399. if (this._copy.rotationQuaternion) {
  57400. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57401. }
  57402. else {
  57403. this._yaw = this._copy.rotation.y;
  57404. this._pitch = this._copy.rotation.x;
  57405. this._roll = this._copy.rotation.z;
  57406. this._quaternionRotationYPR();
  57407. }
  57408. this._quaternionToRotationMatrix();
  57409. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  57410. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  57411. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  57412. if (this._copy.translateFromPivot) {
  57413. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57414. }
  57415. else {
  57416. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57417. }
  57418. this._shape = particle._model._shape;
  57419. for (var pt = 0; pt < this._shape.length; pt++) {
  57420. this._vertex.x = this._shape[pt].x;
  57421. this._vertex.y = this._shape[pt].y;
  57422. this._vertex.z = this._shape[pt].z;
  57423. if (particle._model._vertexFunction) {
  57424. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  57425. }
  57426. this._vertex.x *= this._copy.scaling.x;
  57427. this._vertex.y *= this._copy.scaling.y;
  57428. this._vertex.z *= this._copy.scaling.z;
  57429. this._vertex.x -= this._scaledPivot.x;
  57430. this._vertex.y -= this._scaledPivot.y;
  57431. this._vertex.z -= this._scaledPivot.z;
  57432. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57433. this._rotated.addInPlace(this._pivotBackTranslation);
  57434. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  57435. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  57436. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  57437. }
  57438. particle.position.x = 0.0;
  57439. particle.position.y = 0.0;
  57440. particle.position.z = 0.0;
  57441. particle.rotation.x = 0.0;
  57442. particle.rotation.y = 0.0;
  57443. particle.rotation.z = 0.0;
  57444. particle.rotationQuaternion = null;
  57445. particle.scaling.x = 1.0;
  57446. particle.scaling.y = 1.0;
  57447. particle.scaling.z = 1.0;
  57448. particle.uvs.x = 0.0;
  57449. particle.uvs.y = 0.0;
  57450. particle.uvs.z = 1.0;
  57451. particle.uvs.w = 1.0;
  57452. particle.pivot.x = 0.0;
  57453. particle.pivot.y = 0.0;
  57454. particle.pivot.z = 0.0;
  57455. particle.translateFromPivot = false;
  57456. particle.parentId = null;
  57457. };
  57458. /**
  57459. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  57460. * @returns the SPS.
  57461. */
  57462. SolidParticleSystem.prototype.rebuildMesh = function () {
  57463. for (var p = 0; p < this.particles.length; p++) {
  57464. this._rebuildParticle(this.particles[p]);
  57465. }
  57466. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57467. return this;
  57468. };
  57469. /**
  57470. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  57471. * This method calls `updateParticle()` for each particle of the SPS.
  57472. * For an animated SPS, it is usually called within the render loop.
  57473. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  57474. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  57475. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  57476. * @returns the SPS.
  57477. */
  57478. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  57479. if (start === void 0) { start = 0; }
  57480. if (end === void 0) { end = this.nbParticles - 1; }
  57481. if (update === void 0) { update = true; }
  57482. if (!this._updatable) {
  57483. return this;
  57484. }
  57485. // custom beforeUpdate
  57486. this.beforeUpdateParticles(start, end, update);
  57487. this._cam_axisX.x = 1.0;
  57488. this._cam_axisX.y = 0.0;
  57489. this._cam_axisX.z = 0.0;
  57490. this._cam_axisY.x = 0.0;
  57491. this._cam_axisY.y = 1.0;
  57492. this._cam_axisY.z = 0.0;
  57493. this._cam_axisZ.x = 0.0;
  57494. this._cam_axisZ.y = 0.0;
  57495. this._cam_axisZ.z = 1.0;
  57496. // cases when the World Matrix is to be computed first
  57497. if (this.billboard || this._depthSort) {
  57498. this.mesh.computeWorldMatrix(true);
  57499. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  57500. }
  57501. // if the particles will always face the camera
  57502. if (this.billboard) {
  57503. // compute the camera position and un-rotate it by the current mesh rotation
  57504. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  57505. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  57506. this._cam_axisZ.normalize();
  57507. // same for camera up vector extracted from the cam view matrix
  57508. var view = this._camera.getViewMatrix(true);
  57509. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  57510. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  57511. this._cam_axisY.normalize();
  57512. this._cam_axisX.normalize();
  57513. }
  57514. // if depthSort, compute the camera global position in the mesh local system
  57515. if (this._depthSort) {
  57516. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  57517. }
  57518. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  57519. var idx = 0; // current position index in the global array positions32
  57520. var index = 0; // position start index in the global array positions32 of the current particle
  57521. var colidx = 0; // current color index in the global array colors32
  57522. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  57523. var uvidx = 0; // current uv index in the global array uvs32
  57524. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  57525. var pt = 0; // current index in the particle model shape
  57526. if (this.mesh.isFacetDataEnabled) {
  57527. this._computeBoundingBox = true;
  57528. }
  57529. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  57530. if (this._computeBoundingBox) {
  57531. if (start == 0 && end == this.nbParticles - 1) {
  57532. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  57533. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  57534. }
  57535. else {
  57536. if (this.mesh._boundingInfo) {
  57537. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  57538. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  57539. }
  57540. }
  57541. }
  57542. // particle loop
  57543. index = this.particles[start]._pos;
  57544. var vpos = (index / 3) | 0;
  57545. colorIndex = vpos * 4;
  57546. uvIndex = vpos * 2;
  57547. for (var p = start; p <= end; p++) {
  57548. this._particle = this.particles[p];
  57549. this._shape = this._particle._model._shape;
  57550. this._shapeUV = this._particle._model._shapeUV;
  57551. // call to custom user function to update the particle properties
  57552. this.updateParticle(this._particle);
  57553. // camera-particle distance for depth sorting
  57554. if (this._depthSort && this._depthSortParticles) {
  57555. var dsp = this.depthSortedParticles[p];
  57556. dsp.ind = this._particle._ind;
  57557. dsp.indicesLength = this._particle._model._indicesLength;
  57558. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  57559. }
  57560. // skip the computations for inactive or already invisible particles
  57561. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  57562. // increment indexes for the next particle
  57563. pt = this._shape.length;
  57564. index += pt * 3;
  57565. colorIndex += pt * 4;
  57566. uvIndex += pt * 2;
  57567. continue;
  57568. }
  57569. if (this._particle.isVisible) {
  57570. this._particle._stillInvisible = false; // un-mark permanent invisibility
  57571. this._particleHasParent = (this._particle.parentId !== null);
  57572. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  57573. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  57574. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  57575. // particle rotation matrix
  57576. if (this.billboard) {
  57577. this._particle.rotation.x = 0.0;
  57578. this._particle.rotation.y = 0.0;
  57579. }
  57580. if (this._computeParticleRotation || this.billboard) {
  57581. if (this._particle.rotationQuaternion) {
  57582. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57583. }
  57584. else {
  57585. this._yaw = this._particle.rotation.y;
  57586. this._pitch = this._particle.rotation.x;
  57587. this._roll = this._particle.rotation.z;
  57588. this._quaternionRotationYPR();
  57589. }
  57590. this._quaternionToRotationMatrix();
  57591. }
  57592. if (this._particleHasParent) {
  57593. this._parent = this.particles[this._particle.parentId];
  57594. 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];
  57595. 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];
  57596. 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];
  57597. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  57598. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  57599. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  57600. if (this._computeParticleRotation || this.billboard) {
  57601. 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];
  57602. 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];
  57603. 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];
  57604. 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];
  57605. 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];
  57606. 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];
  57607. 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];
  57608. 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];
  57609. 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];
  57610. }
  57611. }
  57612. else {
  57613. this._particle._globalPosition.x = this._particle.position.x;
  57614. this._particle._globalPosition.y = this._particle.position.y;
  57615. this._particle._globalPosition.z = this._particle.position.z;
  57616. if (this._computeParticleRotation || this.billboard) {
  57617. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  57618. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  57619. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  57620. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  57621. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  57622. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  57623. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  57624. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  57625. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  57626. }
  57627. }
  57628. if (this._particle.translateFromPivot) {
  57629. this._pivotBackTranslation.x = 0.0;
  57630. this._pivotBackTranslation.y = 0.0;
  57631. this._pivotBackTranslation.z = 0.0;
  57632. }
  57633. else {
  57634. this._pivotBackTranslation.x = this._scaledPivot.x;
  57635. this._pivotBackTranslation.y = this._scaledPivot.y;
  57636. this._pivotBackTranslation.z = this._scaledPivot.z;
  57637. }
  57638. // particle vertex loop
  57639. for (pt = 0; pt < this._shape.length; pt++) {
  57640. idx = index + pt * 3;
  57641. colidx = colorIndex + pt * 4;
  57642. uvidx = uvIndex + pt * 2;
  57643. this._vertex.x = this._shape[pt].x;
  57644. this._vertex.y = this._shape[pt].y;
  57645. this._vertex.z = this._shape[pt].z;
  57646. if (this._computeParticleVertex) {
  57647. this.updateParticleVertex(this._particle, this._vertex, pt);
  57648. }
  57649. // positions
  57650. this._vertex.x *= this._particle.scaling.x;
  57651. this._vertex.y *= this._particle.scaling.y;
  57652. this._vertex.z *= this._particle.scaling.z;
  57653. this._vertex.x -= this._scaledPivot.x;
  57654. this._vertex.y -= this._scaledPivot.y;
  57655. this._vertex.z -= this._scaledPivot.z;
  57656. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  57657. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  57658. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  57659. this._rotated.x += this._pivotBackTranslation.x;
  57660. this._rotated.y += this._pivotBackTranslation.y;
  57661. this._rotated.z += this._pivotBackTranslation.z;
  57662. 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;
  57663. 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;
  57664. 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;
  57665. if (this._computeBoundingBox) {
  57666. if (this._positions32[idx] < this._minimum.x) {
  57667. this._minimum.x = this._positions32[idx];
  57668. }
  57669. if (this._positions32[idx] > this._maximum.x) {
  57670. this._maximum.x = this._positions32[idx];
  57671. }
  57672. if (this._positions32[idx + 1] < this._minimum.y) {
  57673. this._minimum.y = this._positions32[idx + 1];
  57674. }
  57675. if (this._positions32[idx + 1] > this._maximum.y) {
  57676. this._maximum.y = this._positions32[idx + 1];
  57677. }
  57678. if (this._positions32[idx + 2] < this._minimum.z) {
  57679. this._minimum.z = this._positions32[idx + 2];
  57680. }
  57681. if (this._positions32[idx + 2] > this._maximum.z) {
  57682. this._maximum.z = this._positions32[idx + 2];
  57683. }
  57684. }
  57685. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  57686. if (!this._computeParticleVertex) {
  57687. this._normal.x = this._fixedNormal32[idx];
  57688. this._normal.y = this._fixedNormal32[idx + 1];
  57689. this._normal.z = this._fixedNormal32[idx + 2];
  57690. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  57691. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  57692. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  57693. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  57694. 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;
  57695. 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;
  57696. }
  57697. if (this._computeParticleColor && this._particle.color) {
  57698. this._colors32[colidx] = this._particle.color.r;
  57699. this._colors32[colidx + 1] = this._particle.color.g;
  57700. this._colors32[colidx + 2] = this._particle.color.b;
  57701. this._colors32[colidx + 3] = this._particle.color.a;
  57702. }
  57703. if (this._computeParticleTexture) {
  57704. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57705. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57706. }
  57707. }
  57708. }
  57709. else {
  57710. this._particle._stillInvisible = true; // mark the particle as invisible
  57711. for (pt = 0; pt < this._shape.length; pt++) {
  57712. idx = index + pt * 3;
  57713. colidx = colorIndex + pt * 4;
  57714. uvidx = uvIndex + pt * 2;
  57715. this._positions32[idx] = 0.0;
  57716. this._positions32[idx + 1] = 0.0;
  57717. this._positions32[idx + 2] = 0.0;
  57718. this._normals32[idx] = 0.0;
  57719. this._normals32[idx + 1] = 0.0;
  57720. this._normals32[idx + 2] = 0.0;
  57721. if (this._computeParticleColor && this._particle.color) {
  57722. this._colors32[colidx] = this._particle.color.r;
  57723. this._colors32[colidx + 1] = this._particle.color.g;
  57724. this._colors32[colidx + 2] = this._particle.color.b;
  57725. this._colors32[colidx + 3] = this._particle.color.a;
  57726. }
  57727. if (this._computeParticleTexture) {
  57728. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57729. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57730. }
  57731. }
  57732. }
  57733. // if the particle intersections must be computed : update the bbInfo
  57734. if (this._particlesIntersect) {
  57735. var bInfo = this._particle._boundingInfo;
  57736. var bBox = bInfo.boundingBox;
  57737. var bSphere = bInfo.boundingSphere;
  57738. if (!this._bSphereOnly) {
  57739. // place, scale and rotate the particle bbox within the SPS local system, then update it
  57740. for (var b = 0; b < bBox.vectors.length; b++) {
  57741. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  57742. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  57743. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  57744. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  57745. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  57746. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  57747. 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;
  57748. 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;
  57749. 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;
  57750. }
  57751. bBox._update(this.mesh._worldMatrix);
  57752. }
  57753. // place and scale the particle bouding sphere in the SPS local system, then update it
  57754. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  57755. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  57756. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  57757. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  57758. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  57759. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  57760. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  57761. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  57762. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  57763. 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));
  57764. bSphere._update(this.mesh._worldMatrix);
  57765. }
  57766. // increment indexes for the next particle
  57767. index = idx + 3;
  57768. colorIndex = colidx + 4;
  57769. uvIndex = uvidx + 2;
  57770. }
  57771. // if the VBO must be updated
  57772. if (update) {
  57773. if (this._computeParticleColor) {
  57774. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  57775. }
  57776. if (this._computeParticleTexture) {
  57777. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  57778. }
  57779. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57780. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  57781. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  57782. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  57783. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  57784. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  57785. for (var i = 0; i < this._normals32.length; i++) {
  57786. this._fixedNormal32[i] = this._normals32[i];
  57787. }
  57788. }
  57789. if (!this.mesh.areNormalsFrozen) {
  57790. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  57791. }
  57792. }
  57793. if (this._depthSort && this._depthSortParticles) {
  57794. this.depthSortedParticles.sort(this._depthSortFunction);
  57795. var dspl = this.depthSortedParticles.length;
  57796. var sorted = 0;
  57797. var lind = 0;
  57798. var sind = 0;
  57799. var sid = 0;
  57800. for (sorted = 0; sorted < dspl; sorted++) {
  57801. lind = this.depthSortedParticles[sorted].indicesLength;
  57802. sind = this.depthSortedParticles[sorted].ind;
  57803. for (var i = 0; i < lind; i++) {
  57804. this._indices32[sid] = this._indices[sind + i];
  57805. sid++;
  57806. }
  57807. }
  57808. this.mesh.updateIndices(this._indices32);
  57809. }
  57810. }
  57811. if (this._computeBoundingBox) {
  57812. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  57813. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  57814. }
  57815. this.afterUpdateParticles(start, end, update);
  57816. return this;
  57817. };
  57818. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  57819. this._halfroll = this._roll * 0.5;
  57820. this._halfpitch = this._pitch * 0.5;
  57821. this._halfyaw = this._yaw * 0.5;
  57822. this._sinRoll = Math.sin(this._halfroll);
  57823. this._cosRoll = Math.cos(this._halfroll);
  57824. this._sinPitch = Math.sin(this._halfpitch);
  57825. this._cosPitch = Math.cos(this._halfpitch);
  57826. this._sinYaw = Math.sin(this._halfyaw);
  57827. this._cosYaw = Math.cos(this._halfyaw);
  57828. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  57829. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  57830. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  57831. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  57832. };
  57833. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  57834. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  57835. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  57836. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  57837. this._rotMatrix.m[3] = 0;
  57838. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  57839. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  57840. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  57841. this._rotMatrix.m[7] = 0;
  57842. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  57843. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  57844. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  57845. this._rotMatrix.m[11] = 0;
  57846. this._rotMatrix.m[12] = 0;
  57847. this._rotMatrix.m[13] = 0;
  57848. this._rotMatrix.m[14] = 0;
  57849. this._rotMatrix.m[15] = 1.0;
  57850. };
  57851. /**
  57852. * Disposes the SPS.
  57853. */
  57854. SolidParticleSystem.prototype.dispose = function () {
  57855. this.mesh.dispose();
  57856. this.vars = null;
  57857. // drop references to internal big arrays for the GC
  57858. this._positions = null;
  57859. this._indices = null;
  57860. this._normals = null;
  57861. this._uvs = null;
  57862. this._colors = null;
  57863. this._indices32 = null;
  57864. this._positions32 = null;
  57865. this._normals32 = null;
  57866. this._fixedNormal32 = null;
  57867. this._uvs32 = null;
  57868. this._colors32 = null;
  57869. this.pickedParticles = null;
  57870. };
  57871. /**
  57872. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  57873. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57874. * @returns the SPS.
  57875. */
  57876. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  57877. if (!this._isVisibilityBoxLocked) {
  57878. this.mesh.refreshBoundingInfo();
  57879. }
  57880. return this;
  57881. };
  57882. /**
  57883. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  57884. * @param size the size (float) of the visibility box
  57885. * note : this doesn't lock the SPS mesh bounding box.
  57886. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57887. */
  57888. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  57889. var vis = size / 2;
  57890. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  57891. };
  57892. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  57893. /**
  57894. * Gets whether the SPS as always visible or not
  57895. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57896. */
  57897. get: function () {
  57898. return this._alwaysVisible;
  57899. },
  57900. /**
  57901. * Sets the SPS as always visible or not
  57902. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57903. */
  57904. set: function (val) {
  57905. this._alwaysVisible = val;
  57906. this.mesh.alwaysSelectAsActiveMesh = val;
  57907. },
  57908. enumerable: true,
  57909. configurable: true
  57910. });
  57911. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  57912. /**
  57913. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  57914. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57915. */
  57916. get: function () {
  57917. return this._isVisibilityBoxLocked;
  57918. },
  57919. /**
  57920. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  57921. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57922. */
  57923. set: function (val) {
  57924. this._isVisibilityBoxLocked = val;
  57925. var boundingInfo = this.mesh.getBoundingInfo();
  57926. boundingInfo.isLocked = val;
  57927. },
  57928. enumerable: true,
  57929. configurable: true
  57930. });
  57931. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  57932. /**
  57933. * Gets if `setParticles()` computes the particle rotations or not.
  57934. * Default value : true. The SPS is faster when it's set to false.
  57935. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  57936. */
  57937. get: function () {
  57938. return this._computeParticleRotation;
  57939. },
  57940. /**
  57941. * Tells to `setParticles()` to compute the particle rotations or not.
  57942. * Default value : true. The SPS is faster when it's set to false.
  57943. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  57944. */
  57945. set: function (val) {
  57946. this._computeParticleRotation = val;
  57947. },
  57948. enumerable: true,
  57949. configurable: true
  57950. });
  57951. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  57952. /**
  57953. * Gets if `setParticles()` computes the particle colors or not.
  57954. * Default value : true. The SPS is faster when it's set to false.
  57955. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  57956. */
  57957. get: function () {
  57958. return this._computeParticleColor;
  57959. },
  57960. /**
  57961. * Tells to `setParticles()` to compute the particle colors or not.
  57962. * Default value : true. The SPS is faster when it's set to false.
  57963. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  57964. */
  57965. set: function (val) {
  57966. this._computeParticleColor = val;
  57967. },
  57968. enumerable: true,
  57969. configurable: true
  57970. });
  57971. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  57972. /**
  57973. * Gets if `setParticles()` computes the particle textures or not.
  57974. * Default value : true. The SPS is faster when it's set to false.
  57975. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  57976. */
  57977. get: function () {
  57978. return this._computeParticleTexture;
  57979. },
  57980. set: function (val) {
  57981. this._computeParticleTexture = val;
  57982. },
  57983. enumerable: true,
  57984. configurable: true
  57985. });
  57986. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  57987. /**
  57988. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  57989. * Default value : false. The SPS is faster when it's set to false.
  57990. * Note : the particle custom vertex positions aren't stored values.
  57991. */
  57992. get: function () {
  57993. return this._computeParticleVertex;
  57994. },
  57995. /**
  57996. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  57997. * Default value : false. The SPS is faster when it's set to false.
  57998. * Note : the particle custom vertex positions aren't stored values.
  57999. */
  58000. set: function (val) {
  58001. this._computeParticleVertex = val;
  58002. },
  58003. enumerable: true,
  58004. configurable: true
  58005. });
  58006. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  58007. /**
  58008. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  58009. */
  58010. get: function () {
  58011. return this._computeBoundingBox;
  58012. },
  58013. /**
  58014. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  58015. */
  58016. set: function (val) {
  58017. this._computeBoundingBox = val;
  58018. },
  58019. enumerable: true,
  58020. configurable: true
  58021. });
  58022. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  58023. /**
  58024. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  58025. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58026. * Default : `true`
  58027. */
  58028. get: function () {
  58029. return this._depthSortParticles;
  58030. },
  58031. /**
  58032. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  58033. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58034. * Default : `true`
  58035. */
  58036. set: function (val) {
  58037. this._depthSortParticles = val;
  58038. },
  58039. enumerable: true,
  58040. configurable: true
  58041. });
  58042. // =======================================================================
  58043. // Particle behavior logic
  58044. // these following methods may be overwritten by the user to fit his needs
  58045. /**
  58046. * This function does nothing. It may be overwritten to set all the particle first values.
  58047. * The SPS doesn't call this function, you may have to call it by your own.
  58048. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58049. */
  58050. SolidParticleSystem.prototype.initParticles = function () {
  58051. };
  58052. /**
  58053. * This function does nothing. It may be overwritten to recycle a particle.
  58054. * The SPS doesn't call this function, you may have to call it by your own.
  58055. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58056. * @param particle The particle to recycle
  58057. * @returns the recycled particle
  58058. */
  58059. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  58060. return particle;
  58061. };
  58062. /**
  58063. * Updates a particle : this function should be overwritten by the user.
  58064. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  58065. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58066. * @example : just set a particle position or velocity and recycle conditions
  58067. * @param particle The particle to update
  58068. * @returns the updated particle
  58069. */
  58070. SolidParticleSystem.prototype.updateParticle = function (particle) {
  58071. return particle;
  58072. };
  58073. /**
  58074. * Updates a vertex of a particle : it can be overwritten by the user.
  58075. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  58076. * @param particle the current particle
  58077. * @param vertex the current index of the current particle
  58078. * @param pt the index of the current vertex in the particle shape
  58079. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  58080. * @example : just set a vertex particle position
  58081. * @returns the updated vertex
  58082. */
  58083. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  58084. return vertex;
  58085. };
  58086. /**
  58087. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  58088. * This does nothing and may be overwritten by the user.
  58089. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58090. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58091. * @param update the boolean update value actually passed to setParticles()
  58092. */
  58093. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  58094. };
  58095. /**
  58096. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  58097. * This will be passed three parameters.
  58098. * This does nothing and may be overwritten by the user.
  58099. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58100. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58101. * @param update the boolean update value actually passed to setParticles()
  58102. */
  58103. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  58104. };
  58105. return SolidParticleSystem;
  58106. }());
  58107. BABYLON.SolidParticleSystem = SolidParticleSystem;
  58108. })(BABYLON || (BABYLON = {}));
  58109. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  58110. "use strict";
  58111. var BABYLON;
  58112. (function (BABYLON) {
  58113. var ShaderMaterial = /** @class */ (function (_super) {
  58114. __extends(ShaderMaterial, _super);
  58115. function ShaderMaterial(name, scene, shaderPath, options) {
  58116. var _this = _super.call(this, name, scene) || this;
  58117. _this._textures = {};
  58118. _this._textureArrays = {};
  58119. _this._floats = {};
  58120. _this._ints = {};
  58121. _this._floatsArrays = {};
  58122. _this._colors3 = {};
  58123. _this._colors3Arrays = {};
  58124. _this._colors4 = {};
  58125. _this._vectors2 = {};
  58126. _this._vectors3 = {};
  58127. _this._vectors4 = {};
  58128. _this._matrices = {};
  58129. _this._matrices3x3 = {};
  58130. _this._matrices2x2 = {};
  58131. _this._vectors2Arrays = {};
  58132. _this._vectors3Arrays = {};
  58133. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58134. _this._shaderPath = shaderPath;
  58135. options.needAlphaBlending = options.needAlphaBlending || false;
  58136. options.needAlphaTesting = options.needAlphaTesting || false;
  58137. options.attributes = options.attributes || ["position", "normal", "uv"];
  58138. options.uniforms = options.uniforms || ["worldViewProjection"];
  58139. options.uniformBuffers = options.uniformBuffers || [];
  58140. options.samplers = options.samplers || [];
  58141. options.defines = options.defines || [];
  58142. _this._options = options;
  58143. return _this;
  58144. }
  58145. ShaderMaterial.prototype.getClassName = function () {
  58146. return "ShaderMaterial";
  58147. };
  58148. ShaderMaterial.prototype.needAlphaBlending = function () {
  58149. return this._options.needAlphaBlending;
  58150. };
  58151. ShaderMaterial.prototype.needAlphaTesting = function () {
  58152. return this._options.needAlphaTesting;
  58153. };
  58154. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58155. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58156. this._options.uniforms.push(uniformName);
  58157. }
  58158. };
  58159. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58160. if (this._options.samplers.indexOf(name) === -1) {
  58161. this._options.samplers.push(name);
  58162. }
  58163. this._textures[name] = texture;
  58164. return this;
  58165. };
  58166. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58167. if (this._options.samplers.indexOf(name) === -1) {
  58168. this._options.samplers.push(name);
  58169. }
  58170. this._checkUniform(name);
  58171. this._textureArrays[name] = textures;
  58172. return this;
  58173. };
  58174. ShaderMaterial.prototype.setFloat = function (name, value) {
  58175. this._checkUniform(name);
  58176. this._floats[name] = value;
  58177. return this;
  58178. };
  58179. ShaderMaterial.prototype.setInt = function (name, value) {
  58180. this._checkUniform(name);
  58181. this._ints[name] = value;
  58182. return this;
  58183. };
  58184. ShaderMaterial.prototype.setFloats = function (name, value) {
  58185. this._checkUniform(name);
  58186. this._floatsArrays[name] = value;
  58187. return this;
  58188. };
  58189. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58190. this._checkUniform(name);
  58191. this._colors3[name] = value;
  58192. return this;
  58193. };
  58194. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58195. this._checkUniform(name);
  58196. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58197. color.toArray(arr, arr.length);
  58198. return arr;
  58199. }, []);
  58200. return this;
  58201. };
  58202. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58203. this._checkUniform(name);
  58204. this._colors4[name] = value;
  58205. return this;
  58206. };
  58207. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58208. this._checkUniform(name);
  58209. this._vectors2[name] = value;
  58210. return this;
  58211. };
  58212. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58213. this._checkUniform(name);
  58214. this._vectors3[name] = value;
  58215. return this;
  58216. };
  58217. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58218. this._checkUniform(name);
  58219. this._vectors4[name] = value;
  58220. return this;
  58221. };
  58222. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58223. this._checkUniform(name);
  58224. this._matrices[name] = value;
  58225. return this;
  58226. };
  58227. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58228. this._checkUniform(name);
  58229. this._matrices3x3[name] = value;
  58230. return this;
  58231. };
  58232. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58233. this._checkUniform(name);
  58234. this._matrices2x2[name] = value;
  58235. return this;
  58236. };
  58237. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58238. this._checkUniform(name);
  58239. this._vectors2Arrays[name] = value;
  58240. return this;
  58241. };
  58242. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58243. this._checkUniform(name);
  58244. this._vectors3Arrays[name] = value;
  58245. return this;
  58246. };
  58247. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58248. if (!mesh) {
  58249. return true;
  58250. }
  58251. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58252. return false;
  58253. }
  58254. return false;
  58255. };
  58256. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58257. var scene = this.getScene();
  58258. var engine = scene.getEngine();
  58259. if (!this.checkReadyOnEveryCall) {
  58260. if (this._renderId === scene.getRenderId()) {
  58261. if (this._checkCache(scene, mesh, useInstances)) {
  58262. return true;
  58263. }
  58264. }
  58265. }
  58266. // Instances
  58267. var defines = [];
  58268. var attribs = [];
  58269. var fallbacks = new BABYLON.EffectFallbacks();
  58270. if (useInstances) {
  58271. defines.push("#define INSTANCES");
  58272. }
  58273. for (var index = 0; index < this._options.defines.length; index++) {
  58274. defines.push(this._options.defines[index]);
  58275. }
  58276. for (var index = 0; index < this._options.attributes.length; index++) {
  58277. attribs.push(this._options.attributes[index]);
  58278. }
  58279. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58280. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58281. defines.push("#define VERTEXCOLOR");
  58282. }
  58283. // Bones
  58284. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58285. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58286. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58287. if (mesh.numBoneInfluencers > 4) {
  58288. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58289. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58290. }
  58291. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58292. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58293. fallbacks.addCPUSkinningFallback(0, mesh);
  58294. if (this._options.uniforms.indexOf("mBones") === -1) {
  58295. this._options.uniforms.push("mBones");
  58296. }
  58297. }
  58298. else {
  58299. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58300. }
  58301. // Textures
  58302. for (var name in this._textures) {
  58303. if (!this._textures[name].isReady()) {
  58304. return false;
  58305. }
  58306. }
  58307. // Alpha test
  58308. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58309. defines.push("#define ALPHATEST");
  58310. }
  58311. var previousEffect = this._effect;
  58312. var join = defines.join("\n");
  58313. this._effect = engine.createEffect(this._shaderPath, {
  58314. attributes: attribs,
  58315. uniformsNames: this._options.uniforms,
  58316. uniformBuffersNames: this._options.uniformBuffers,
  58317. samplers: this._options.samplers,
  58318. defines: join,
  58319. fallbacks: fallbacks,
  58320. onCompiled: this.onCompiled,
  58321. onError: this.onError
  58322. }, engine);
  58323. if (!this._effect.isReady()) {
  58324. return false;
  58325. }
  58326. if (previousEffect !== this._effect) {
  58327. scene.resetCachedMaterial();
  58328. }
  58329. this._renderId = scene.getRenderId();
  58330. return true;
  58331. };
  58332. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58333. var scene = this.getScene();
  58334. if (!this._effect) {
  58335. return;
  58336. }
  58337. if (this._options.uniforms.indexOf("world") !== -1) {
  58338. this._effect.setMatrix("world", world);
  58339. }
  58340. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58341. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58342. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58343. }
  58344. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58345. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58346. }
  58347. };
  58348. ShaderMaterial.prototype.bind = function (world, mesh) {
  58349. // Std values
  58350. this.bindOnlyWorldMatrix(world);
  58351. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58352. if (this._options.uniforms.indexOf("view") !== -1) {
  58353. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58354. }
  58355. if (this._options.uniforms.indexOf("projection") !== -1) {
  58356. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58357. }
  58358. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58359. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58360. }
  58361. // Bones
  58362. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58363. var name;
  58364. // Texture
  58365. for (name in this._textures) {
  58366. this._effect.setTexture(name, this._textures[name]);
  58367. }
  58368. // Texture arrays
  58369. for (name in this._textureArrays) {
  58370. this._effect.setTextureArray(name, this._textureArrays[name]);
  58371. }
  58372. // Int
  58373. for (name in this._ints) {
  58374. this._effect.setInt(name, this._ints[name]);
  58375. }
  58376. // Float
  58377. for (name in this._floats) {
  58378. this._effect.setFloat(name, this._floats[name]);
  58379. }
  58380. // Floats
  58381. for (name in this._floatsArrays) {
  58382. this._effect.setArray(name, this._floatsArrays[name]);
  58383. }
  58384. // Color3
  58385. for (name in this._colors3) {
  58386. this._effect.setColor3(name, this._colors3[name]);
  58387. }
  58388. for (name in this._colors3Arrays) {
  58389. this._effect.setArray3(name, this._colors3Arrays[name]);
  58390. }
  58391. // Color4
  58392. for (name in this._colors4) {
  58393. var color = this._colors4[name];
  58394. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58395. }
  58396. // Vector2
  58397. for (name in this._vectors2) {
  58398. this._effect.setVector2(name, this._vectors2[name]);
  58399. }
  58400. // Vector3
  58401. for (name in this._vectors3) {
  58402. this._effect.setVector3(name, this._vectors3[name]);
  58403. }
  58404. // Vector4
  58405. for (name in this._vectors4) {
  58406. this._effect.setVector4(name, this._vectors4[name]);
  58407. }
  58408. // Matrix
  58409. for (name in this._matrices) {
  58410. this._effect.setMatrix(name, this._matrices[name]);
  58411. }
  58412. // Matrix 3x3
  58413. for (name in this._matrices3x3) {
  58414. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  58415. }
  58416. // Matrix 2x2
  58417. for (name in this._matrices2x2) {
  58418. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  58419. }
  58420. // Vector2Array
  58421. for (name in this._vectors2Arrays) {
  58422. this._effect.setArray2(name, this._vectors2Arrays[name]);
  58423. }
  58424. // Vector3Array
  58425. for (name in this._vectors3Arrays) {
  58426. this._effect.setArray3(name, this._vectors3Arrays[name]);
  58427. }
  58428. }
  58429. this._afterBind(mesh);
  58430. };
  58431. ShaderMaterial.prototype.getActiveTextures = function () {
  58432. var activeTextures = _super.prototype.getActiveTextures.call(this);
  58433. for (var name in this._textures) {
  58434. activeTextures.push(this._textures[name]);
  58435. }
  58436. for (var name in this._textureArrays) {
  58437. var array = this._textureArrays[name];
  58438. for (var index = 0; index < array.length; index++) {
  58439. activeTextures.push(array[index]);
  58440. }
  58441. }
  58442. return activeTextures;
  58443. };
  58444. ShaderMaterial.prototype.hasTexture = function (texture) {
  58445. if (_super.prototype.hasTexture.call(this, texture)) {
  58446. return true;
  58447. }
  58448. for (var name in this._textures) {
  58449. if (this._textures[name] === texture) {
  58450. return true;
  58451. }
  58452. }
  58453. for (var name in this._textureArrays) {
  58454. var array = this._textureArrays[name];
  58455. for (var index = 0; index < array.length; index++) {
  58456. if (array[index] === texture) {
  58457. return true;
  58458. }
  58459. }
  58460. }
  58461. return false;
  58462. };
  58463. ShaderMaterial.prototype.clone = function (name) {
  58464. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58465. return newShaderMaterial;
  58466. };
  58467. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58468. if (forceDisposeTextures) {
  58469. var name;
  58470. for (name in this._textures) {
  58471. this._textures[name].dispose();
  58472. }
  58473. for (name in this._textureArrays) {
  58474. var array = this._textureArrays[name];
  58475. for (var index = 0; index < array.length; index++) {
  58476. array[index].dispose();
  58477. }
  58478. }
  58479. }
  58480. this._textures = {};
  58481. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58482. };
  58483. ShaderMaterial.prototype.serialize = function () {
  58484. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58485. serializationObject.customType = "BABYLON.ShaderMaterial";
  58486. serializationObject.options = this._options;
  58487. serializationObject.shaderPath = this._shaderPath;
  58488. var name;
  58489. // Texture
  58490. serializationObject.textures = {};
  58491. for (name in this._textures) {
  58492. serializationObject.textures[name] = this._textures[name].serialize();
  58493. }
  58494. // Texture arrays
  58495. serializationObject.textureArrays = {};
  58496. for (name in this._textureArrays) {
  58497. serializationObject.textureArrays[name] = [];
  58498. var array = this._textureArrays[name];
  58499. for (var index = 0; index < array.length; index++) {
  58500. serializationObject.textureArrays[name].push(array[index].serialize());
  58501. }
  58502. }
  58503. // Float
  58504. serializationObject.floats = {};
  58505. for (name in this._floats) {
  58506. serializationObject.floats[name] = this._floats[name];
  58507. }
  58508. // Float s
  58509. serializationObject.FloatArrays = {};
  58510. for (name in this._floatsArrays) {
  58511. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  58512. }
  58513. // Color3
  58514. serializationObject.colors3 = {};
  58515. for (name in this._colors3) {
  58516. serializationObject.colors3[name] = this._colors3[name].asArray();
  58517. }
  58518. // Color3 array
  58519. serializationObject.colors3Arrays = {};
  58520. for (name in this._colors3Arrays) {
  58521. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  58522. }
  58523. // Color4
  58524. serializationObject.colors4 = {};
  58525. for (name in this._colors4) {
  58526. serializationObject.colors4[name] = this._colors4[name].asArray();
  58527. }
  58528. // Vector2
  58529. serializationObject.vectors2 = {};
  58530. for (name in this._vectors2) {
  58531. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  58532. }
  58533. // Vector3
  58534. serializationObject.vectors3 = {};
  58535. for (name in this._vectors3) {
  58536. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  58537. }
  58538. // Vector4
  58539. serializationObject.vectors4 = {};
  58540. for (name in this._vectors4) {
  58541. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  58542. }
  58543. // Matrix
  58544. serializationObject.matrices = {};
  58545. for (name in this._matrices) {
  58546. serializationObject.matrices[name] = this._matrices[name].asArray();
  58547. }
  58548. // Matrix 3x3
  58549. serializationObject.matrices3x3 = {};
  58550. for (name in this._matrices3x3) {
  58551. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  58552. }
  58553. // Matrix 2x2
  58554. serializationObject.matrices2x2 = {};
  58555. for (name in this._matrices2x2) {
  58556. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  58557. }
  58558. // Vector2Array
  58559. serializationObject.vectors2Arrays = {};
  58560. for (name in this._vectors2Arrays) {
  58561. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  58562. }
  58563. // Vector3Array
  58564. serializationObject.vectors3Arrays = {};
  58565. for (name in this._vectors3Arrays) {
  58566. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  58567. }
  58568. return serializationObject;
  58569. };
  58570. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  58571. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  58572. var name;
  58573. // Texture
  58574. for (name in source.textures) {
  58575. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  58576. }
  58577. // Texture arrays
  58578. for (name in source.textureArrays) {
  58579. var array = source.textureArrays[name];
  58580. var textureArray = new Array();
  58581. for (var index = 0; index < array.length; index++) {
  58582. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  58583. }
  58584. material.setTextureArray(name, textureArray);
  58585. }
  58586. // Float
  58587. for (name in source.floats) {
  58588. material.setFloat(name, source.floats[name]);
  58589. }
  58590. // Float s
  58591. for (name in source.floatsArrays) {
  58592. material.setFloats(name, source.floatsArrays[name]);
  58593. }
  58594. // Color3
  58595. for (name in source.colors3) {
  58596. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  58597. }
  58598. // Color3 arrays
  58599. for (name in source.colors3Arrays) {
  58600. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  58601. if (i % 3 === 0) {
  58602. arr.push([num]);
  58603. }
  58604. else {
  58605. arr[arr.length - 1].push(num);
  58606. }
  58607. return arr;
  58608. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  58609. material.setColor3Array(name, colors);
  58610. }
  58611. // Color4
  58612. for (name in source.colors4) {
  58613. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  58614. }
  58615. // Vector2
  58616. for (name in source.vectors2) {
  58617. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  58618. }
  58619. // Vector3
  58620. for (name in source.vectors3) {
  58621. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  58622. }
  58623. // Vector4
  58624. for (name in source.vectors4) {
  58625. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  58626. }
  58627. // Matrix
  58628. for (name in source.matrices) {
  58629. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  58630. }
  58631. // Matrix 3x3
  58632. for (name in source.matrices3x3) {
  58633. material.setMatrix3x3(name, source.matrices3x3[name]);
  58634. }
  58635. // Matrix 2x2
  58636. for (name in source.matrices2x2) {
  58637. material.setMatrix2x2(name, source.matrices2x2[name]);
  58638. }
  58639. // Vector2Array
  58640. for (name in source.vectors2Arrays) {
  58641. material.setArray2(name, source.vectors2Arrays[name]);
  58642. }
  58643. // Vector3Array
  58644. for (name in source.vectors3Arrays) {
  58645. material.setArray3(name, source.vectors3Arrays[name]);
  58646. }
  58647. return material;
  58648. };
  58649. return ShaderMaterial;
  58650. }(BABYLON.Material));
  58651. BABYLON.ShaderMaterial = ShaderMaterial;
  58652. })(BABYLON || (BABYLON = {}));
  58653. //# sourceMappingURL=babylon.shaderMaterial.js.map
  58654. "use strict";
  58655. var BABYLON;
  58656. (function (BABYLON) {
  58657. var GroundMesh = /** @class */ (function (_super) {
  58658. __extends(GroundMesh, _super);
  58659. function GroundMesh(name, scene) {
  58660. var _this = _super.call(this, name, scene) || this;
  58661. _this.generateOctree = false;
  58662. return _this;
  58663. }
  58664. GroundMesh.prototype.getClassName = function () {
  58665. return "GroundMesh";
  58666. };
  58667. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  58668. get: function () {
  58669. return Math.min(this._subdivisionsX, this._subdivisionsY);
  58670. },
  58671. enumerable: true,
  58672. configurable: true
  58673. });
  58674. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  58675. get: function () {
  58676. return this._subdivisionsX;
  58677. },
  58678. enumerable: true,
  58679. configurable: true
  58680. });
  58681. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  58682. get: function () {
  58683. return this._subdivisionsY;
  58684. },
  58685. enumerable: true,
  58686. configurable: true
  58687. });
  58688. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  58689. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  58690. this._subdivisionsX = chunksCount;
  58691. this._subdivisionsY = chunksCount;
  58692. this.subdivide(chunksCount);
  58693. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  58694. };
  58695. /**
  58696. * Returns a height (y) value in the Worl system :
  58697. * the ground altitude at the coordinates (x, z) expressed in the World system.
  58698. * Returns the ground y position if (x, z) are outside the ground surface.
  58699. */
  58700. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  58701. var world = this.getWorldMatrix();
  58702. var invMat = BABYLON.Tmp.Matrix[5];
  58703. world.invertToRef(invMat);
  58704. var tmpVect = BABYLON.Tmp.Vector3[8];
  58705. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  58706. x = tmpVect.x;
  58707. z = tmpVect.z;
  58708. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58709. return this.position.y;
  58710. }
  58711. if (!this._heightQuads || this._heightQuads.length == 0) {
  58712. this._initHeightQuads();
  58713. this._computeHeightQuads();
  58714. }
  58715. var facet = this._getFacetAt(x, z);
  58716. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  58717. // return y in the World system
  58718. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  58719. return tmpVect.y;
  58720. };
  58721. /**
  58722. * Returns a normalized vector (Vector3) orthogonal to the ground
  58723. * at the ground coordinates (x, z) expressed in the World system.
  58724. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  58725. */
  58726. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  58727. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  58728. this.getNormalAtCoordinatesToRef(x, z, normal);
  58729. return normal;
  58730. };
  58731. /**
  58732. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  58733. * at the ground coordinates (x, z) expressed in the World system.
  58734. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  58735. * Returns the GroundMesh.
  58736. */
  58737. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  58738. var world = this.getWorldMatrix();
  58739. var tmpMat = BABYLON.Tmp.Matrix[5];
  58740. world.invertToRef(tmpMat);
  58741. var tmpVect = BABYLON.Tmp.Vector3[8];
  58742. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  58743. x = tmpVect.x;
  58744. z = tmpVect.z;
  58745. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58746. return this;
  58747. }
  58748. if (!this._heightQuads || this._heightQuads.length == 0) {
  58749. this._initHeightQuads();
  58750. this._computeHeightQuads();
  58751. }
  58752. var facet = this._getFacetAt(x, z);
  58753. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  58754. return this;
  58755. };
  58756. /**
  58757. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  58758. * if the ground has been updated.
  58759. * This can be used in the render loop.
  58760. * Returns the GroundMesh.
  58761. */
  58762. GroundMesh.prototype.updateCoordinateHeights = function () {
  58763. if (!this._heightQuads || this._heightQuads.length == 0) {
  58764. this._initHeightQuads();
  58765. }
  58766. this._computeHeightQuads();
  58767. return this;
  58768. };
  58769. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  58770. GroundMesh.prototype._getFacetAt = function (x, z) {
  58771. // retrieve col and row from x, z coordinates in the ground local system
  58772. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  58773. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  58774. var quad = this._heightQuads[row * this._subdivisionsX + col];
  58775. var facet;
  58776. if (z < quad.slope.x * x + quad.slope.y) {
  58777. facet = quad.facet1;
  58778. }
  58779. else {
  58780. facet = quad.facet2;
  58781. }
  58782. return facet;
  58783. };
  58784. // Creates and populates the heightMap array with "facet" elements :
  58785. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  58786. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58787. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58788. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58789. // Returns the GroundMesh.
  58790. GroundMesh.prototype._initHeightQuads = function () {
  58791. var subdivisionsX = this._subdivisionsX;
  58792. var subdivisionsY = this._subdivisionsY;
  58793. this._heightQuads = new Array();
  58794. for (var row = 0; row < subdivisionsY; row++) {
  58795. for (var col = 0; col < subdivisionsX; col++) {
  58796. 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) };
  58797. this._heightQuads[row * subdivisionsX + col] = quad;
  58798. }
  58799. }
  58800. return this;
  58801. };
  58802. // Compute each quad element values and update the the heightMap array :
  58803. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58804. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58805. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58806. // Returns the GroundMesh.
  58807. GroundMesh.prototype._computeHeightQuads = function () {
  58808. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58809. if (!positions) {
  58810. return this;
  58811. }
  58812. var v1 = BABYLON.Tmp.Vector3[3];
  58813. var v2 = BABYLON.Tmp.Vector3[2];
  58814. var v3 = BABYLON.Tmp.Vector3[1];
  58815. var v4 = BABYLON.Tmp.Vector3[0];
  58816. var v1v2 = BABYLON.Tmp.Vector3[4];
  58817. var v1v3 = BABYLON.Tmp.Vector3[5];
  58818. var v1v4 = BABYLON.Tmp.Vector3[6];
  58819. var norm1 = BABYLON.Tmp.Vector3[7];
  58820. var norm2 = BABYLON.Tmp.Vector3[8];
  58821. var i = 0;
  58822. var j = 0;
  58823. var k = 0;
  58824. var cd = 0; // 2D slope coefficient : z = cd * x + h
  58825. var h = 0;
  58826. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  58827. var d2 = 0;
  58828. var subdivisionsX = this._subdivisionsX;
  58829. var subdivisionsY = this._subdivisionsY;
  58830. for (var row = 0; row < subdivisionsY; row++) {
  58831. for (var col = 0; col < subdivisionsX; col++) {
  58832. i = col * 3;
  58833. j = row * (subdivisionsX + 1) * 3;
  58834. k = (row + 1) * (subdivisionsX + 1) * 3;
  58835. v1.x = positions[j + i];
  58836. v1.y = positions[j + i + 1];
  58837. v1.z = positions[j + i + 2];
  58838. v2.x = positions[j + i + 3];
  58839. v2.y = positions[j + i + 4];
  58840. v2.z = positions[j + i + 5];
  58841. v3.x = positions[k + i];
  58842. v3.y = positions[k + i + 1];
  58843. v3.z = positions[k + i + 2];
  58844. v4.x = positions[k + i + 3];
  58845. v4.y = positions[k + i + 4];
  58846. v4.z = positions[k + i + 5];
  58847. // 2D slope V1V4
  58848. cd = (v4.z - v1.z) / (v4.x - v1.x);
  58849. h = v1.z - cd * v1.x; // v1 belongs to the slope
  58850. // facet equations :
  58851. // we compute each facet normal vector
  58852. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  58853. // we compute the value d by applying the equation to v1 which belongs to the plane
  58854. // then we store the facet equation in a Vector4
  58855. v2.subtractToRef(v1, v1v2);
  58856. v3.subtractToRef(v1, v1v3);
  58857. v4.subtractToRef(v1, v1v4);
  58858. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  58859. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  58860. norm1.normalize();
  58861. norm2.normalize();
  58862. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  58863. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  58864. var quad = this._heightQuads[row * subdivisionsX + col];
  58865. quad.slope.copyFromFloats(cd, h);
  58866. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  58867. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  58868. }
  58869. }
  58870. return this;
  58871. };
  58872. GroundMesh.prototype.serialize = function (serializationObject) {
  58873. _super.prototype.serialize.call(this, serializationObject);
  58874. serializationObject.subdivisionsX = this._subdivisionsX;
  58875. serializationObject.subdivisionsY = this._subdivisionsY;
  58876. serializationObject.minX = this._minX;
  58877. serializationObject.maxX = this._maxX;
  58878. serializationObject.minZ = this._minZ;
  58879. serializationObject.maxZ = this._maxZ;
  58880. serializationObject.width = this._width;
  58881. serializationObject.height = this._height;
  58882. };
  58883. GroundMesh.Parse = function (parsedMesh, scene) {
  58884. var result = new GroundMesh(parsedMesh.name, scene);
  58885. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  58886. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  58887. result._minX = parsedMesh.minX;
  58888. result._maxX = parsedMesh.maxX;
  58889. result._minZ = parsedMesh.minZ;
  58890. result._maxZ = parsedMesh.maxZ;
  58891. result._width = parsedMesh.width;
  58892. result._height = parsedMesh.height;
  58893. return result;
  58894. };
  58895. return GroundMesh;
  58896. }(BABYLON.Mesh));
  58897. BABYLON.GroundMesh = GroundMesh;
  58898. })(BABYLON || (BABYLON = {}));
  58899. //# sourceMappingURL=babylon.groundMesh.js.map
  58900. "use strict";
  58901. var BABYLON;
  58902. (function (BABYLON) {
  58903. /**
  58904. * Creates an instance based on a source mesh.
  58905. */
  58906. var InstancedMesh = /** @class */ (function (_super) {
  58907. __extends(InstancedMesh, _super);
  58908. function InstancedMesh(name, source) {
  58909. var _this = _super.call(this, name, source.getScene()) || this;
  58910. source.instances.push(_this);
  58911. _this._sourceMesh = source;
  58912. _this.position.copyFrom(source.position);
  58913. _this.rotation.copyFrom(source.rotation);
  58914. _this.scaling.copyFrom(source.scaling);
  58915. if (source.rotationQuaternion) {
  58916. _this.rotationQuaternion = source.rotationQuaternion.clone();
  58917. }
  58918. _this.infiniteDistance = source.infiniteDistance;
  58919. _this.setPivotMatrix(source.getPivotMatrix());
  58920. _this.refreshBoundingInfo();
  58921. _this._syncSubMeshes();
  58922. return _this;
  58923. }
  58924. /**
  58925. * Returns the string "InstancedMesh".
  58926. */
  58927. InstancedMesh.prototype.getClassName = function () {
  58928. return "InstancedMesh";
  58929. };
  58930. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  58931. // Methods
  58932. get: function () {
  58933. return this._sourceMesh.receiveShadows;
  58934. },
  58935. enumerable: true,
  58936. configurable: true
  58937. });
  58938. Object.defineProperty(InstancedMesh.prototype, "material", {
  58939. get: function () {
  58940. return this._sourceMesh.material;
  58941. },
  58942. enumerable: true,
  58943. configurable: true
  58944. });
  58945. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  58946. get: function () {
  58947. return this._sourceMesh.visibility;
  58948. },
  58949. enumerable: true,
  58950. configurable: true
  58951. });
  58952. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  58953. get: function () {
  58954. return this._sourceMesh.skeleton;
  58955. },
  58956. enumerable: true,
  58957. configurable: true
  58958. });
  58959. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  58960. get: function () {
  58961. return this._sourceMesh.renderingGroupId;
  58962. },
  58963. set: function (value) {
  58964. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  58965. return;
  58966. }
  58967. //no-op with warning
  58968. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  58969. },
  58970. enumerable: true,
  58971. configurable: true
  58972. });
  58973. /**
  58974. * Returns the total number of vertices (integer).
  58975. */
  58976. InstancedMesh.prototype.getTotalVertices = function () {
  58977. return this._sourceMesh.getTotalVertices();
  58978. };
  58979. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  58980. get: function () {
  58981. return this._sourceMesh;
  58982. },
  58983. enumerable: true,
  58984. configurable: true
  58985. });
  58986. /**
  58987. * Is this node ready to be used/rendered
  58988. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  58989. * @return {boolean} is it ready
  58990. */
  58991. InstancedMesh.prototype.isReady = function (completeCheck) {
  58992. if (completeCheck === void 0) { completeCheck = false; }
  58993. return this._sourceMesh.isReady(completeCheck, true);
  58994. };
  58995. /**
  58996. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  58997. */
  58998. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  58999. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59000. };
  59001. /**
  59002. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59003. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59004. * The `data` are either a numeric array either a Float32Array.
  59005. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59006. * 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).
  59007. * Note that a new underlying VertexBuffer object is created each call.
  59008. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59009. *
  59010. * Possible `kind` values :
  59011. * - BABYLON.VertexBuffer.PositionKind
  59012. * - BABYLON.VertexBuffer.UVKind
  59013. * - BABYLON.VertexBuffer.UV2Kind
  59014. * - BABYLON.VertexBuffer.UV3Kind
  59015. * - BABYLON.VertexBuffer.UV4Kind
  59016. * - BABYLON.VertexBuffer.UV5Kind
  59017. * - BABYLON.VertexBuffer.UV6Kind
  59018. * - BABYLON.VertexBuffer.ColorKind
  59019. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59020. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59021. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59022. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59023. *
  59024. * Returns the Mesh.
  59025. */
  59026. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59027. if (this.sourceMesh) {
  59028. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59029. }
  59030. return this.sourceMesh;
  59031. };
  59032. /**
  59033. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59034. * If the mesh has no geometry, it is simply returned as it is.
  59035. * The `data` are either a numeric array either a Float32Array.
  59036. * No new underlying VertexBuffer object is created.
  59037. * 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.
  59038. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59039. *
  59040. * Possible `kind` values :
  59041. * - BABYLON.VertexBuffer.PositionKind
  59042. * - BABYLON.VertexBuffer.UVKind
  59043. * - BABYLON.VertexBuffer.UV2Kind
  59044. * - BABYLON.VertexBuffer.UV3Kind
  59045. * - BABYLON.VertexBuffer.UV4Kind
  59046. * - BABYLON.VertexBuffer.UV5Kind
  59047. * - BABYLON.VertexBuffer.UV6Kind
  59048. * - BABYLON.VertexBuffer.ColorKind
  59049. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59050. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59051. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59052. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59053. *
  59054. * Returns the Mesh.
  59055. */
  59056. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59057. if (this.sourceMesh) {
  59058. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59059. }
  59060. return this.sourceMesh;
  59061. };
  59062. /**
  59063. * Sets the mesh indices.
  59064. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59065. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59066. * This method creates a new index buffer each call.
  59067. * Returns the Mesh.
  59068. */
  59069. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59070. if (totalVertices === void 0) { totalVertices = null; }
  59071. if (this.sourceMesh) {
  59072. this.sourceMesh.setIndices(indices, totalVertices);
  59073. }
  59074. return this.sourceMesh;
  59075. };
  59076. /**
  59077. * Boolean : True if the mesh owns the requested kind of data.
  59078. */
  59079. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59080. return this._sourceMesh.isVerticesDataPresent(kind);
  59081. };
  59082. /**
  59083. * Returns an array of indices (IndicesArray).
  59084. */
  59085. InstancedMesh.prototype.getIndices = function () {
  59086. return this._sourceMesh.getIndices();
  59087. };
  59088. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59089. get: function () {
  59090. return this._sourceMesh._positions;
  59091. },
  59092. enumerable: true,
  59093. configurable: true
  59094. });
  59095. /**
  59096. * Sets a new updated BoundingInfo to the mesh.
  59097. * Returns the mesh.
  59098. */
  59099. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59100. var meshBB = this._sourceMesh.getBoundingInfo();
  59101. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59102. this._updateBoundingInfo();
  59103. return this;
  59104. };
  59105. InstancedMesh.prototype._preActivate = function () {
  59106. if (this._currentLOD) {
  59107. this._currentLOD._preActivate();
  59108. }
  59109. return this;
  59110. };
  59111. InstancedMesh.prototype._activate = function (renderId) {
  59112. if (this._currentLOD) {
  59113. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59114. }
  59115. return this;
  59116. };
  59117. /**
  59118. * Returns the current associated LOD AbstractMesh.
  59119. */
  59120. InstancedMesh.prototype.getLOD = function (camera) {
  59121. if (!camera) {
  59122. return this;
  59123. }
  59124. var boundingInfo = this.getBoundingInfo();
  59125. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59126. if (this._currentLOD === this.sourceMesh) {
  59127. return this;
  59128. }
  59129. return this._currentLOD;
  59130. };
  59131. InstancedMesh.prototype._syncSubMeshes = function () {
  59132. this.releaseSubMeshes();
  59133. if (this._sourceMesh.subMeshes) {
  59134. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59135. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59136. }
  59137. }
  59138. return this;
  59139. };
  59140. InstancedMesh.prototype._generatePointsArray = function () {
  59141. return this._sourceMesh._generatePointsArray();
  59142. };
  59143. /**
  59144. * Creates a new InstancedMesh from the current mesh.
  59145. * - name (string) : the cloned mesh name
  59146. * - newParent (optional Node) : the optional Node to parent the clone to.
  59147. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59148. *
  59149. * Returns the clone.
  59150. */
  59151. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59152. var result = this._sourceMesh.createInstance(name);
  59153. // Deep copy
  59154. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59155. // Bounding info
  59156. this.refreshBoundingInfo();
  59157. // Parent
  59158. if (newParent) {
  59159. result.parent = newParent;
  59160. }
  59161. if (!doNotCloneChildren) {
  59162. // Children
  59163. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59164. var mesh = this.getScene().meshes[index];
  59165. if (mesh.parent === this) {
  59166. mesh.clone(mesh.name, result);
  59167. }
  59168. }
  59169. }
  59170. result.computeWorldMatrix(true);
  59171. return result;
  59172. };
  59173. /**
  59174. * Disposes the InstancedMesh.
  59175. * Returns nothing.
  59176. */
  59177. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59178. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59179. // Remove from mesh
  59180. var index = this._sourceMesh.instances.indexOf(this);
  59181. this._sourceMesh.instances.splice(index, 1);
  59182. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59183. };
  59184. return InstancedMesh;
  59185. }(BABYLON.AbstractMesh));
  59186. BABYLON.InstancedMesh = InstancedMesh;
  59187. })(BABYLON || (BABYLON = {}));
  59188. //# sourceMappingURL=babylon.instancedMesh.js.map
  59189. "use strict";
  59190. var BABYLON;
  59191. (function (BABYLON) {
  59192. var LinesMesh = /** @class */ (function (_super) {
  59193. __extends(LinesMesh, _super);
  59194. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59195. if (scene === void 0) { scene = null; }
  59196. if (parent === void 0) { parent = null; }
  59197. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59198. _this.useVertexColor = useVertexColor;
  59199. _this.useVertexAlpha = useVertexAlpha;
  59200. _this.color = new BABYLON.Color3(1, 1, 1);
  59201. _this.alpha = 1;
  59202. if (source) {
  59203. _this.color = source.color.clone();
  59204. _this.alpha = source.alpha;
  59205. _this.useVertexColor = source.useVertexColor;
  59206. _this.useVertexAlpha = source.useVertexAlpha;
  59207. }
  59208. _this._intersectionThreshold = 0.1;
  59209. var defines = [];
  59210. var options = {
  59211. attributes: [BABYLON.VertexBuffer.PositionKind],
  59212. uniforms: ["world", "viewProjection"],
  59213. needAlphaBlending: true,
  59214. defines: defines
  59215. };
  59216. if (useVertexAlpha === false) {
  59217. options.needAlphaBlending = false;
  59218. }
  59219. if (!useVertexColor) {
  59220. options.uniforms.push("color");
  59221. }
  59222. else {
  59223. options.defines.push("#define VERTEXCOLOR");
  59224. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59225. }
  59226. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59227. return _this;
  59228. }
  59229. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59230. /**
  59231. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59232. * This margin is expressed in world space coordinates, so its value may vary.
  59233. * Default value is 0.1
  59234. * @returns the intersection Threshold value.
  59235. */
  59236. get: function () {
  59237. return this._intersectionThreshold;
  59238. },
  59239. /**
  59240. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59241. * This margin is expressed in world space coordinates, so its value may vary.
  59242. * @param value the new threshold to apply
  59243. */
  59244. set: function (value) {
  59245. if (this._intersectionThreshold === value) {
  59246. return;
  59247. }
  59248. this._intersectionThreshold = value;
  59249. if (this.geometry) {
  59250. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59251. }
  59252. },
  59253. enumerable: true,
  59254. configurable: true
  59255. });
  59256. /**
  59257. * Returns the string "LineMesh"
  59258. */
  59259. LinesMesh.prototype.getClassName = function () {
  59260. return "LinesMesh";
  59261. };
  59262. Object.defineProperty(LinesMesh.prototype, "material", {
  59263. get: function () {
  59264. return this._colorShader;
  59265. },
  59266. set: function (value) {
  59267. // Do nothing
  59268. },
  59269. enumerable: true,
  59270. configurable: true
  59271. });
  59272. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59273. get: function () {
  59274. return false;
  59275. },
  59276. enumerable: true,
  59277. configurable: true
  59278. });
  59279. LinesMesh.prototype.createInstance = function (name) {
  59280. throw new Error("LinesMeshes do not support createInstance.");
  59281. };
  59282. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59283. if (!this._geometry) {
  59284. return this;
  59285. }
  59286. // VBOs
  59287. this._geometry._bind(this._colorShader.getEffect());
  59288. // Color
  59289. if (!this.useVertexColor) {
  59290. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59291. }
  59292. return this;
  59293. };
  59294. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59295. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59296. return this;
  59297. }
  59298. var engine = this.getScene().getEngine();
  59299. // Draw order
  59300. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59301. return this;
  59302. };
  59303. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59304. this._colorShader.dispose();
  59305. _super.prototype.dispose.call(this, doNotRecurse);
  59306. };
  59307. /**
  59308. * Returns a new LineMesh object cloned from the current one.
  59309. */
  59310. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59311. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59312. };
  59313. return LinesMesh;
  59314. }(BABYLON.Mesh));
  59315. BABYLON.LinesMesh = LinesMesh;
  59316. })(BABYLON || (BABYLON = {}));
  59317. //# sourceMappingURL=babylon.linesMesh.js.map
  59318. "use strict";
  59319. var BABYLON;
  59320. (function (BABYLON) {
  59321. /**
  59322. * Class containing static functions to help procedurally build meshes
  59323. */
  59324. var MeshBuilder = /** @class */ (function () {
  59325. function MeshBuilder() {
  59326. }
  59327. MeshBuilder.updateSideOrientation = function (orientation) {
  59328. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  59329. return BABYLON.Mesh.DOUBLESIDE;
  59330. }
  59331. if (orientation === undefined || orientation === null) {
  59332. return BABYLON.Mesh.FRONTSIDE;
  59333. }
  59334. return orientation;
  59335. };
  59336. /**
  59337. * Creates a box mesh
  59338. * * The parameter `size` sets the size (float) of each box side (default 1)
  59339. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  59340. * * 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)
  59341. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  59342. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59343. * * 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
  59344. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59345. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  59346. * @param name defines the name of the mesh
  59347. * @param options defines the options used to create the mesh
  59348. * @param scene defines the hosting scene
  59349. * @returns the box mesh
  59350. */
  59351. MeshBuilder.CreateBox = function (name, options, scene) {
  59352. if (scene === void 0) { scene = null; }
  59353. var box = new BABYLON.Mesh(name, scene);
  59354. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59355. box._originalBuilderSideOrientation = options.sideOrientation;
  59356. var vertexData = BABYLON.VertexData.CreateBox(options);
  59357. vertexData.applyToMesh(box, options.updatable);
  59358. return box;
  59359. };
  59360. /**
  59361. * Creates a sphere mesh
  59362. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  59363. * * 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`)
  59364. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  59365. * * 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
  59366. * * 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)
  59367. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59368. * * 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
  59369. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59370. * @param name defines the name of the mesh
  59371. * @param options defines the options used to create the mesh
  59372. * @param scene defines the hosting scene
  59373. * @returns the sphere mesh
  59374. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  59375. */
  59376. MeshBuilder.CreateSphere = function (name, options, scene) {
  59377. var sphere = new BABYLON.Mesh(name, scene);
  59378. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59379. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59380. var vertexData = BABYLON.VertexData.CreateSphere(options);
  59381. vertexData.applyToMesh(sphere, options.updatable);
  59382. return sphere;
  59383. };
  59384. /**
  59385. * Creates a plane polygonal mesh. By default, this is a disc
  59386. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  59387. * * 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
  59388. * * 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
  59389. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59390. * * 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
  59391. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59392. * @param name defines the name of the mesh
  59393. * @param options defines the options used to create the mesh
  59394. * @param scene defines the hosting scene
  59395. * @returns the plane polygonal mesh
  59396. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  59397. */
  59398. MeshBuilder.CreateDisc = function (name, options, scene) {
  59399. if (scene === void 0) { scene = null; }
  59400. var disc = new BABYLON.Mesh(name, scene);
  59401. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59402. disc._originalBuilderSideOrientation = options.sideOrientation;
  59403. var vertexData = BABYLON.VertexData.CreateDisc(options);
  59404. vertexData.applyToMesh(disc, options.updatable);
  59405. return disc;
  59406. };
  59407. /**
  59408. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  59409. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  59410. * * 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`)
  59411. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  59412. * * 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
  59413. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59414. * * 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
  59415. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59416. * @param name defines the name of the mesh
  59417. * @param options defines the options used to create the mesh
  59418. * @param scene defines the hosting scene
  59419. * @returns the icosahedron mesh
  59420. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  59421. */
  59422. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  59423. var sphere = new BABYLON.Mesh(name, scene);
  59424. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59425. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59426. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  59427. vertexData.applyToMesh(sphere, options.updatable);
  59428. return sphere;
  59429. };
  59430. ;
  59431. /**
  59432. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  59433. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  59434. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  59435. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  59436. * * 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
  59437. * * 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
  59438. * * 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
  59439. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59440. * * 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
  59441. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59442. * * 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
  59443. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  59444. * * 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
  59445. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  59446. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59447. * @param name defines the name of the mesh
  59448. * @param options defines the options used to create the mesh
  59449. * @param scene defines the hosting scene
  59450. * @returns the ribbon mesh
  59451. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  59452. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59453. */
  59454. MeshBuilder.CreateRibbon = function (name, options, scene) {
  59455. if (scene === void 0) { scene = null; }
  59456. var pathArray = options.pathArray;
  59457. var closeArray = options.closeArray;
  59458. var closePath = options.closePath;
  59459. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59460. var instance = options.instance;
  59461. var updatable = options.updatable;
  59462. if (instance) {
  59463. // positionFunction : ribbon case
  59464. // only pathArray and sideOrientation parameters are taken into account for positions update
  59465. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  59466. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  59467. var positionFunction = function (positions) {
  59468. var minlg = pathArray[0].length;
  59469. var i = 0;
  59470. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  59471. for (var si = 1; si <= ns; si++) {
  59472. for (var p = 0; p < pathArray.length; p++) {
  59473. var path = pathArray[p];
  59474. var l = path.length;
  59475. minlg = (minlg < l) ? minlg : l;
  59476. var j = 0;
  59477. while (j < minlg) {
  59478. positions[i] = path[j].x;
  59479. positions[i + 1] = path[j].y;
  59480. positions[i + 2] = path[j].z;
  59481. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  59482. BABYLON.Tmp.Vector3[0].x = path[j].x;
  59483. }
  59484. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  59485. BABYLON.Tmp.Vector3[1].x = path[j].x;
  59486. }
  59487. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  59488. BABYLON.Tmp.Vector3[0].y = path[j].y;
  59489. }
  59490. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  59491. BABYLON.Tmp.Vector3[1].y = path[j].y;
  59492. }
  59493. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  59494. BABYLON.Tmp.Vector3[0].z = path[j].z;
  59495. }
  59496. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  59497. BABYLON.Tmp.Vector3[1].z = path[j].z;
  59498. }
  59499. j++;
  59500. i += 3;
  59501. }
  59502. if (instance._closePath) {
  59503. positions[i] = path[0].x;
  59504. positions[i + 1] = path[0].y;
  59505. positions[i + 2] = path[0].z;
  59506. i += 3;
  59507. }
  59508. }
  59509. }
  59510. };
  59511. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59512. positionFunction(positions);
  59513. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  59514. instance._boundingInfo.update(instance._worldMatrix);
  59515. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  59516. if (options.colors) {
  59517. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59518. for (var c = 0; c < options.colors.length; c++) {
  59519. colors[c * 4] = options.colors[c].r;
  59520. colors[c * 4 + 1] = options.colors[c].g;
  59521. colors[c * 4 + 2] = options.colors[c].b;
  59522. colors[c * 4 + 3] = options.colors[c].a;
  59523. }
  59524. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  59525. }
  59526. if (options.uvs) {
  59527. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59528. for (var i = 0; i < options.uvs.length; i++) {
  59529. uvs[i * 2] = options.uvs[i].x;
  59530. uvs[i * 2 + 1] = options.uvs[i].y;
  59531. }
  59532. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  59533. }
  59534. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  59535. var indices = instance.getIndices();
  59536. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59537. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  59538. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  59539. if (instance._closePath) {
  59540. var indexFirst = 0;
  59541. var indexLast = 0;
  59542. for (var p = 0; p < pathArray.length; p++) {
  59543. indexFirst = instance._idx[p] * 3;
  59544. if (p + 1 < pathArray.length) {
  59545. indexLast = (instance._idx[p + 1] - 1) * 3;
  59546. }
  59547. else {
  59548. indexLast = normals.length - 3;
  59549. }
  59550. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  59551. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  59552. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  59553. normals[indexLast] = normals[indexFirst];
  59554. normals[indexLast + 1] = normals[indexFirst + 1];
  59555. normals[indexLast + 2] = normals[indexFirst + 2];
  59556. }
  59557. }
  59558. if (!(instance.areNormalsFrozen)) {
  59559. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  59560. }
  59561. }
  59562. return instance;
  59563. }
  59564. else {
  59565. var ribbon = new BABYLON.Mesh(name, scene);
  59566. ribbon._originalBuilderSideOrientation = sideOrientation;
  59567. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  59568. if (closePath) {
  59569. ribbon._idx = vertexData._idx;
  59570. }
  59571. ribbon._closePath = closePath;
  59572. ribbon._closeArray = closeArray;
  59573. vertexData.applyToMesh(ribbon, updatable);
  59574. return ribbon;
  59575. }
  59576. };
  59577. /**
  59578. * Creates a cylinder or a cone mesh
  59579. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  59580. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  59581. * * 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.
  59582. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  59583. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  59584. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  59585. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  59586. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  59587. * * 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).
  59588. * * 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
  59589. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  59590. * * 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
  59591. * * 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.
  59592. * * If `enclose` is false, a ring surface is one element.
  59593. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  59594. * * 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
  59595. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59596. * * 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
  59597. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59598. * @param name defines the name of the mesh
  59599. * @param options defines the options used to create the mesh
  59600. * @param scene defines the hosting scene
  59601. * @returns the cylinder mesh
  59602. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  59603. */
  59604. MeshBuilder.CreateCylinder = function (name, options, scene) {
  59605. var cylinder = new BABYLON.Mesh(name, scene);
  59606. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59607. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  59608. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  59609. vertexData.applyToMesh(cylinder, options.updatable);
  59610. return cylinder;
  59611. };
  59612. /**
  59613. * Creates a torus mesh
  59614. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  59615. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  59616. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  59617. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59618. * * 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
  59619. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59620. * @param name defines the name of the mesh
  59621. * @param options defines the options used to create the mesh
  59622. * @param scene defines the hosting scene
  59623. * @returns the torus mesh
  59624. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  59625. */
  59626. MeshBuilder.CreateTorus = function (name, options, scene) {
  59627. var torus = new BABYLON.Mesh(name, scene);
  59628. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59629. torus._originalBuilderSideOrientation = options.sideOrientation;
  59630. var vertexData = BABYLON.VertexData.CreateTorus(options);
  59631. vertexData.applyToMesh(torus, options.updatable);
  59632. return torus;
  59633. };
  59634. /**
  59635. * Creates a torus knot mesh
  59636. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  59637. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  59638. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  59639. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  59640. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59641. * * 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
  59642. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59643. * @param name defines the name of the mesh
  59644. * @param options defines the options used to create the mesh
  59645. * @param scene defines the hosting scene
  59646. * @returns the torus knot mesh
  59647. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  59648. */
  59649. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  59650. var torusKnot = new BABYLON.Mesh(name, scene);
  59651. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59652. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  59653. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  59654. vertexData.applyToMesh(torusKnot, options.updatable);
  59655. return torusKnot;
  59656. };
  59657. /**
  59658. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  59659. * * 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
  59660. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  59661. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  59662. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  59663. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  59664. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  59665. * * 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
  59666. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  59667. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59668. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  59669. * @param name defines the name of the new line system
  59670. * @param options defines the options used to create the line system
  59671. * @param scene defines the hosting scene
  59672. * @returns a new line system mesh
  59673. */
  59674. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  59675. var instance = options.instance;
  59676. var lines = options.lines;
  59677. var colors = options.colors;
  59678. if (instance) {
  59679. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59680. var vertexColor;
  59681. var lineColors;
  59682. if (colors) {
  59683. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59684. }
  59685. var i = 0;
  59686. var c = 0;
  59687. for (var l = 0; l < lines.length; l++) {
  59688. var points = lines[l];
  59689. for (var p = 0; p < points.length; p++) {
  59690. positions[i] = points[p].x;
  59691. positions[i + 1] = points[p].y;
  59692. positions[i + 2] = points[p].z;
  59693. if (colors && vertexColor) {
  59694. lineColors = colors[l];
  59695. vertexColor[c] = lineColors[p].r;
  59696. vertexColor[c + 1] = lineColors[p].g;
  59697. vertexColor[c + 2] = lineColors[p].b;
  59698. vertexColor[c + 3] = lineColors[p].a;
  59699. c += 4;
  59700. }
  59701. i += 3;
  59702. }
  59703. }
  59704. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  59705. if (colors && vertexColor) {
  59706. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  59707. }
  59708. return instance;
  59709. }
  59710. // line system creation
  59711. var useVertexColor = (colors) ? true : false;
  59712. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  59713. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  59714. vertexData.applyToMesh(lineSystem, options.updatable);
  59715. return lineSystem;
  59716. };
  59717. /**
  59718. * Creates a line mesh
  59719. * 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
  59720. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  59721. * * The parameter `points` is an array successive Vector3
  59722. * * 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
  59723. * * The optional parameter `colors` is an array of successive Color4, one per line point
  59724. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  59725. * * When updating an instance, remember that only point positions can change, not the number of points
  59726. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59727. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  59728. * @param name defines the name of the new line system
  59729. * @param options defines the options used to create the line system
  59730. * @param scene defines the hosting scene
  59731. * @returns a new line mesh
  59732. */
  59733. MeshBuilder.CreateLines = function (name, options, scene) {
  59734. if (scene === void 0) { scene = null; }
  59735. var colors = (options.colors) ? [options.colors] : null;
  59736. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  59737. return lines;
  59738. };
  59739. /**
  59740. * Creates a dashed line mesh
  59741. * * 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
  59742. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  59743. * * The parameter `points` is an array successive Vector3
  59744. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  59745. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  59746. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  59747. * * 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
  59748. * * When updating an instance, remember that only point positions can change, not the number of points
  59749. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59750. * @param name defines the name of the mesh
  59751. * @param options defines the options used to create the mesh
  59752. * @param scene defines the hosting scene
  59753. * @returns the dashed line mesh
  59754. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  59755. */
  59756. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  59757. if (scene === void 0) { scene = null; }
  59758. var points = options.points;
  59759. var instance = options.instance;
  59760. var gapSize = options.gapSize || 1;
  59761. var dashSize = options.dashSize || 3;
  59762. if (instance) {
  59763. var positionFunction = function (positions) {
  59764. var curvect = BABYLON.Vector3.Zero();
  59765. var nbSeg = positions.length / 6;
  59766. var lg = 0;
  59767. var nb = 0;
  59768. var shft = 0;
  59769. var dashshft = 0;
  59770. var curshft = 0;
  59771. var p = 0;
  59772. var i = 0;
  59773. var j = 0;
  59774. for (i = 0; i < points.length - 1; i++) {
  59775. points[i + 1].subtractToRef(points[i], curvect);
  59776. lg += curvect.length();
  59777. }
  59778. shft = lg / nbSeg;
  59779. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  59780. for (i = 0; i < points.length - 1; i++) {
  59781. points[i + 1].subtractToRef(points[i], curvect);
  59782. nb = Math.floor(curvect.length() / shft);
  59783. curvect.normalize();
  59784. j = 0;
  59785. while (j < nb && p < positions.length) {
  59786. curshft = shft * j;
  59787. positions[p] = points[i].x + curshft * curvect.x;
  59788. positions[p + 1] = points[i].y + curshft * curvect.y;
  59789. positions[p + 2] = points[i].z + curshft * curvect.z;
  59790. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  59791. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  59792. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  59793. p += 6;
  59794. j++;
  59795. }
  59796. }
  59797. while (p < positions.length) {
  59798. positions[p] = points[i].x;
  59799. positions[p + 1] = points[i].y;
  59800. positions[p + 2] = points[i].z;
  59801. p += 3;
  59802. }
  59803. };
  59804. instance.updateMeshPositions(positionFunction, false);
  59805. return instance;
  59806. }
  59807. // dashed lines creation
  59808. var dashedLines = new BABYLON.LinesMesh(name, scene);
  59809. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  59810. vertexData.applyToMesh(dashedLines, options.updatable);
  59811. dashedLines.dashSize = dashSize;
  59812. dashedLines.gapSize = gapSize;
  59813. return dashedLines;
  59814. };
  59815. /**
  59816. * 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.
  59817. * * 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.
  59818. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  59819. * * 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.
  59820. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  59821. * * 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
  59822. * * 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
  59823. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  59824. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59825. * * 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
  59826. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  59827. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59828. * @param name defines the name of the mesh
  59829. * @param options defines the options used to create the mesh
  59830. * @param scene defines the hosting scene
  59831. * @returns the extruded shape mesh
  59832. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59833. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  59834. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  59835. */
  59836. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  59837. if (scene === void 0) { scene = null; }
  59838. var path = options.path;
  59839. var shape = options.shape;
  59840. var scale = options.scale || 1;
  59841. var rotation = options.rotation || 0;
  59842. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  59843. var updatable = options.updatable;
  59844. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59845. var instance = options.instance || null;
  59846. var invertUV = options.invertUV || false;
  59847. 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);
  59848. };
  59849. /**
  59850. * Creates an custom extruded shape mesh.
  59851. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  59852. * * 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.
  59853. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  59854. * * 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
  59855. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  59856. * * 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
  59857. * * It must returns a float value that will be the scale value applied to the shape on each path point
  59858. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  59859. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  59860. * * 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
  59861. * * 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
  59862. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  59863. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59864. * * 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
  59865. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59866. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59867. * @param name defines the name of the mesh
  59868. * @param options defines the options used to create the mesh
  59869. * @param scene defines the hosting scene
  59870. * @returns the custom extruded shape mesh
  59871. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  59872. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59873. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  59874. */
  59875. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  59876. var path = options.path;
  59877. var shape = options.shape;
  59878. var scaleFunction = options.scaleFunction || (function () { return 1; });
  59879. var rotationFunction = options.rotationFunction || (function () { return 0; });
  59880. var ribbonCloseArray = options.ribbonCloseArray || false;
  59881. var ribbonClosePath = options.ribbonClosePath || false;
  59882. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  59883. var updatable = options.updatable;
  59884. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59885. var instance = options.instance;
  59886. var invertUV = options.invertUV || false;
  59887. 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);
  59888. };
  59889. /**
  59890. * Creates lathe mesh.
  59891. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  59892. * * 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
  59893. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  59894. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  59895. * * 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
  59896. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  59897. * * 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
  59898. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59899. * * 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
  59900. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59901. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59902. * @param name defines the name of the mesh
  59903. * @param options defines the options used to create the mesh
  59904. * @param scene defines the hosting scene
  59905. * @returns the lathe mesh
  59906. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  59907. */
  59908. MeshBuilder.CreateLathe = function (name, options, scene) {
  59909. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  59910. var closed = (options.closed === undefined) ? true : options.closed;
  59911. var shape = options.shape;
  59912. var radius = options.radius || 1;
  59913. var tessellation = options.tessellation || 64;
  59914. var updatable = options.updatable;
  59915. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59916. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  59917. var pi2 = Math.PI * 2;
  59918. var paths = new Array();
  59919. var invertUV = options.invertUV || false;
  59920. var i = 0;
  59921. var p = 0;
  59922. var step = pi2 / tessellation * arc;
  59923. var rotated;
  59924. var path = new Array();
  59925. ;
  59926. for (i = 0; i <= tessellation; i++) {
  59927. var path = [];
  59928. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  59929. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  59930. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  59931. }
  59932. for (p = 0; p < shape.length; p++) {
  59933. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  59934. path.push(rotated);
  59935. }
  59936. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  59937. 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));
  59938. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  59939. }
  59940. paths.push(path);
  59941. }
  59942. // lathe ribbon
  59943. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  59944. return lathe;
  59945. };
  59946. /**
  59947. * Creates a plane mesh
  59948. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  59949. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  59950. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  59951. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59952. * * 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
  59953. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59954. * @param name defines the name of the mesh
  59955. * @param options defines the options used to create the mesh
  59956. * @param scene defines the hosting scene
  59957. * @returns the plane mesh
  59958. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  59959. */
  59960. MeshBuilder.CreatePlane = function (name, options, scene) {
  59961. var plane = new BABYLON.Mesh(name, scene);
  59962. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59963. plane._originalBuilderSideOrientation = options.sideOrientation;
  59964. var vertexData = BABYLON.VertexData.CreatePlane(options);
  59965. vertexData.applyToMesh(plane, options.updatable);
  59966. if (options.sourcePlane) {
  59967. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  59968. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  59969. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  59970. plane.rotate(vectorProduct, product);
  59971. }
  59972. return plane;
  59973. };
  59974. /**
  59975. * Creates a ground mesh
  59976. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  59977. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  59978. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59979. * @param name defines the name of the mesh
  59980. * @param options defines the options used to create the mesh
  59981. * @param scene defines the hosting scene
  59982. * @returns the ground mesh
  59983. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  59984. */
  59985. MeshBuilder.CreateGround = function (name, options, scene) {
  59986. var ground = new BABYLON.GroundMesh(name, scene);
  59987. ground._setReady(false);
  59988. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  59989. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  59990. ground._width = options.width || 1;
  59991. ground._height = options.height || 1;
  59992. ground._maxX = ground._width / 2;
  59993. ground._maxZ = ground._height / 2;
  59994. ground._minX = -ground._maxX;
  59995. ground._minZ = -ground._maxZ;
  59996. var vertexData = BABYLON.VertexData.CreateGround(options);
  59997. vertexData.applyToMesh(ground, options.updatable);
  59998. ground._setReady(true);
  59999. return ground;
  60000. };
  60001. /**
  60002. * Creates a tiled ground mesh
  60003. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  60004. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  60005. * * 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
  60006. * * 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
  60007. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60008. * @param name defines the name of the mesh
  60009. * @param options defines the options used to create the mesh
  60010. * @param scene defines the hosting scene
  60011. * @returns the tiled ground mesh
  60012. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  60013. */
  60014. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  60015. var tiledGround = new BABYLON.Mesh(name, scene);
  60016. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  60017. vertexData.applyToMesh(tiledGround, options.updatable);
  60018. return tiledGround;
  60019. };
  60020. /**
  60021. * Creates a ground mesh from a height map
  60022. * * The parameter `url` sets the URL of the height map image resource.
  60023. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  60024. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  60025. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  60026. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  60027. * * 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.
  60028. * * 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).
  60029. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60030. * @param name defines the name of the mesh
  60031. * @param url defines the url to the height map
  60032. * @param options defines the options used to create the mesh
  60033. * @param scene defines the hosting scene
  60034. * @returns the ground mesh
  60035. * @see http://doc.babylonjs.com/tutorials/14._Height_Map
  60036. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  60037. */
  60038. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  60039. var width = options.width || 10.0;
  60040. var height = options.height || 10.0;
  60041. var subdivisions = options.subdivisions || 1 | 0;
  60042. var minHeight = options.minHeight || 0.0;
  60043. var maxHeight = options.maxHeight || 1.0;
  60044. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  60045. var updatable = options.updatable;
  60046. var onReady = options.onReady;
  60047. var ground = new BABYLON.GroundMesh(name, scene);
  60048. ground._subdivisionsX = subdivisions;
  60049. ground._subdivisionsY = subdivisions;
  60050. ground._width = width;
  60051. ground._height = height;
  60052. ground._maxX = ground._width / 2.0;
  60053. ground._maxZ = ground._height / 2.0;
  60054. ground._minX = -ground._maxX;
  60055. ground._minZ = -ground._maxZ;
  60056. ground._setReady(false);
  60057. var onload = function (img) {
  60058. // Getting height map data
  60059. var canvas = document.createElement("canvas");
  60060. var context = canvas.getContext("2d");
  60061. if (!context) {
  60062. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  60063. }
  60064. if (scene.isDisposed) {
  60065. return;
  60066. }
  60067. var bufferWidth = img.width;
  60068. var bufferHeight = img.height;
  60069. canvas.width = bufferWidth;
  60070. canvas.height = bufferHeight;
  60071. context.drawImage(img, 0, 0);
  60072. // Create VertexData from map data
  60073. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  60074. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  60075. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  60076. width: width, height: height,
  60077. subdivisions: subdivisions,
  60078. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  60079. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  60080. });
  60081. vertexData.applyToMesh(ground, updatable);
  60082. //execute ready callback, if set
  60083. if (onReady) {
  60084. onReady(ground);
  60085. }
  60086. ground._setReady(true);
  60087. };
  60088. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  60089. return ground;
  60090. };
  60091. /**
  60092. * Creates a polygon mesh
  60093. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  60094. * * 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
  60095. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60096. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60097. * * 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)
  60098. * * Remember you can only change the shape positions, not their number when updating a polygon
  60099. * @param name defines the name of the mesh
  60100. * @param options defines the options used to create the mesh
  60101. * @param scene defines the hosting scene
  60102. * @returns the polygon mesh
  60103. */
  60104. MeshBuilder.CreatePolygon = function (name, options, scene) {
  60105. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60106. var shape = options.shape;
  60107. var holes = options.holes || [];
  60108. var depth = options.depth || 0;
  60109. var contours = [];
  60110. var hole = [];
  60111. for (var i = 0; i < shape.length; i++) {
  60112. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  60113. }
  60114. var epsilon = 0.00000001;
  60115. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  60116. contours.pop();
  60117. }
  60118. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  60119. for (var hNb = 0; hNb < holes.length; hNb++) {
  60120. hole = [];
  60121. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  60122. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  60123. }
  60124. polygonTriangulation.addHole(hole);
  60125. }
  60126. var polygon = polygonTriangulation.build(options.updatable, depth);
  60127. polygon._originalBuilderSideOrientation = options.sideOrientation;
  60128. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  60129. vertexData.applyToMesh(polygon, options.updatable);
  60130. return polygon;
  60131. };
  60132. ;
  60133. /**
  60134. * Creates an extruded polygon mesh, with depth in the Y direction.
  60135. * * 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)
  60136. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60137. * @param name defines the name of the mesh
  60138. * @param options defines the options used to create the mesh
  60139. * @param scene defines the hosting scene
  60140. * @returns the polygon mesh
  60141. */
  60142. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  60143. return MeshBuilder.CreatePolygon(name, options, scene);
  60144. };
  60145. ;
  60146. /**
  60147. * Creates a tube mesh.
  60148. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60149. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  60150. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  60151. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  60152. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  60153. * * 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)
  60154. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  60155. * * 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
  60156. * * 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
  60157. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60158. * * 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
  60159. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60160. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60161. * @param name defines the name of the mesh
  60162. * @param options defines the options used to create the mesh
  60163. * @param scene defines the hosting scene
  60164. * @returns the tube mesh
  60165. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60166. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  60167. */
  60168. MeshBuilder.CreateTube = function (name, options, scene) {
  60169. var path = options.path;
  60170. var instance = options.instance;
  60171. var radius = 1.0;
  60172. if (instance) {
  60173. radius = instance.radius;
  60174. }
  60175. if (options.radius !== undefined) {
  60176. radius = options.radius;
  60177. }
  60178. ;
  60179. var tessellation = options.tessellation || 64 | 0;
  60180. var radiusFunction = options.radiusFunction || null;
  60181. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60182. var invertUV = options.invertUV || false;
  60183. var updatable = options.updatable;
  60184. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60185. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  60186. // tube geometry
  60187. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  60188. var tangents = path3D.getTangents();
  60189. var normals = path3D.getNormals();
  60190. var distances = path3D.getDistances();
  60191. var pi2 = Math.PI * 2;
  60192. var step = pi2 / tessellation * arc;
  60193. var returnRadius = function () { return radius; };
  60194. var radiusFunctionFinal = radiusFunction || returnRadius;
  60195. var circlePath;
  60196. var rad;
  60197. var normal;
  60198. var rotated;
  60199. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60200. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60201. for (var i = 0; i < path.length; i++) {
  60202. rad = radiusFunctionFinal(i, distances[i]); // current radius
  60203. circlePath = Array(); // current circle array
  60204. normal = normals[i]; // current normal
  60205. for (var t = 0; t < tessellation; t++) {
  60206. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  60207. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  60208. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  60209. rotated.scaleInPlace(rad).addInPlace(path[i]);
  60210. circlePath[t] = rotated;
  60211. }
  60212. circlePaths[index] = circlePath;
  60213. index++;
  60214. }
  60215. // cap
  60216. var capPath = function (nbPoints, pathIndex) {
  60217. var pointCap = Array();
  60218. for (var i = 0; i < nbPoints; i++) {
  60219. pointCap.push(path[pathIndex]);
  60220. }
  60221. return pointCap;
  60222. };
  60223. switch (cap) {
  60224. case BABYLON.Mesh.NO_CAP:
  60225. break;
  60226. case BABYLON.Mesh.CAP_START:
  60227. circlePaths[0] = capPath(tessellation, 0);
  60228. circlePaths[1] = circlePaths[2].slice(0);
  60229. break;
  60230. case BABYLON.Mesh.CAP_END:
  60231. circlePaths[index] = circlePaths[index - 1].slice(0);
  60232. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60233. break;
  60234. case BABYLON.Mesh.CAP_ALL:
  60235. circlePaths[0] = capPath(tessellation, 0);
  60236. circlePaths[1] = circlePaths[2].slice(0);
  60237. circlePaths[index] = circlePaths[index - 1].slice(0);
  60238. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60239. break;
  60240. default:
  60241. break;
  60242. }
  60243. return circlePaths;
  60244. };
  60245. var path3D;
  60246. var pathArray;
  60247. if (instance) {
  60248. var arc = options.arc || instance.arc;
  60249. path3D = (instance.path3D).update(path);
  60250. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  60251. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  60252. instance.path3D = path3D;
  60253. instance.pathArray = pathArray;
  60254. instance.arc = arc;
  60255. instance.radius = radius;
  60256. return instance;
  60257. }
  60258. // tube creation
  60259. path3D = new BABYLON.Path3D(path);
  60260. var newPathArray = new Array();
  60261. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60262. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  60263. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60264. tube.pathArray = pathArray;
  60265. tube.path3D = path3D;
  60266. tube.tessellation = tessellation;
  60267. tube.cap = cap;
  60268. tube.arc = options.arc;
  60269. tube.radius = radius;
  60270. return tube;
  60271. };
  60272. /**
  60273. * Creates a polyhedron mesh
  60274. * * 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
  60275. * * The parameter `size` (positive float, default 1) sets the polygon size
  60276. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  60277. * * 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`
  60278. * * 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
  60279. * * 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)`)
  60280. * * 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
  60281. * * 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
  60282. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60283. * * 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
  60284. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60285. * @param name defines the name of the mesh
  60286. * @param options defines the options used to create the mesh
  60287. * @param scene defines the hosting scene
  60288. * @returns the polyhedron mesh
  60289. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  60290. */
  60291. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  60292. var polyhedron = new BABYLON.Mesh(name, scene);
  60293. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60294. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  60295. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  60296. vertexData.applyToMesh(polyhedron, options.updatable);
  60297. return polyhedron;
  60298. };
  60299. /**
  60300. * Creates a decal mesh.
  60301. * 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
  60302. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  60303. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  60304. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  60305. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  60306. * @param name defines the name of the mesh
  60307. * @param sourceMesh defines the mesh where the decal must be applied
  60308. * @param options defines the options used to create the mesh
  60309. * @param scene defines the hosting scene
  60310. * @returns the decal mesh
  60311. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  60312. */
  60313. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  60314. var indices = sourceMesh.getIndices();
  60315. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60316. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60317. var position = options.position || BABYLON.Vector3.Zero();
  60318. var normal = options.normal || BABYLON.Vector3.Up();
  60319. var size = options.size || BABYLON.Vector3.One();
  60320. var angle = options.angle || 0;
  60321. // Getting correct rotation
  60322. if (!normal) {
  60323. var target = new BABYLON.Vector3(0, 0, 1);
  60324. var camera = sourceMesh.getScene().activeCamera;
  60325. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  60326. normal = camera.globalPosition.subtract(cameraWorldTarget);
  60327. }
  60328. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  60329. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  60330. var pitch = Math.atan2(normal.y, len);
  60331. // Matrix
  60332. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  60333. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  60334. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  60335. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  60336. var vertexData = new BABYLON.VertexData();
  60337. vertexData.indices = [];
  60338. vertexData.positions = [];
  60339. vertexData.normals = [];
  60340. vertexData.uvs = [];
  60341. var currentVertexDataIndex = 0;
  60342. var extractDecalVector3 = function (indexId) {
  60343. var result = new BABYLON.PositionNormalVertex();
  60344. if (!indices || !positions || !normals) {
  60345. return result;
  60346. }
  60347. var vertexId = indices[indexId];
  60348. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  60349. // Send vector to decal local world
  60350. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  60351. // Get normal
  60352. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  60353. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  60354. return result;
  60355. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  60356. var clip = function (vertices, axis) {
  60357. if (vertices.length === 0) {
  60358. return vertices;
  60359. }
  60360. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  60361. var clipVertices = function (v0, v1) {
  60362. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  60363. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  60364. };
  60365. var result = new Array();
  60366. for (var index = 0; index < vertices.length; index += 3) {
  60367. var v1Out;
  60368. var v2Out;
  60369. var v3Out;
  60370. var total = 0;
  60371. var nV1 = null;
  60372. var nV2 = null;
  60373. var nV3 = null;
  60374. var nV4 = null;
  60375. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  60376. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  60377. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  60378. v1Out = d1 > 0;
  60379. v2Out = d2 > 0;
  60380. v3Out = d3 > 0;
  60381. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  60382. switch (total) {
  60383. case 0:
  60384. result.push(vertices[index]);
  60385. result.push(vertices[index + 1]);
  60386. result.push(vertices[index + 2]);
  60387. break;
  60388. case 1:
  60389. if (v1Out) {
  60390. nV1 = vertices[index + 1];
  60391. nV2 = vertices[index + 2];
  60392. nV3 = clipVertices(vertices[index], nV1);
  60393. nV4 = clipVertices(vertices[index], nV2);
  60394. }
  60395. if (v2Out) {
  60396. nV1 = vertices[index];
  60397. nV2 = vertices[index + 2];
  60398. nV3 = clipVertices(vertices[index + 1], nV1);
  60399. nV4 = clipVertices(vertices[index + 1], nV2);
  60400. result.push(nV3);
  60401. result.push(nV2.clone());
  60402. result.push(nV1.clone());
  60403. result.push(nV2.clone());
  60404. result.push(nV3.clone());
  60405. result.push(nV4);
  60406. break;
  60407. }
  60408. if (v3Out) {
  60409. nV1 = vertices[index];
  60410. nV2 = vertices[index + 1];
  60411. nV3 = clipVertices(vertices[index + 2], nV1);
  60412. nV4 = clipVertices(vertices[index + 2], nV2);
  60413. }
  60414. if (nV1 && nV2 && nV3 && nV4) {
  60415. result.push(nV1.clone());
  60416. result.push(nV2.clone());
  60417. result.push(nV3);
  60418. result.push(nV4);
  60419. result.push(nV3.clone());
  60420. result.push(nV2.clone());
  60421. }
  60422. break;
  60423. case 2:
  60424. if (!v1Out) {
  60425. nV1 = vertices[index].clone();
  60426. nV2 = clipVertices(nV1, vertices[index + 1]);
  60427. nV3 = clipVertices(nV1, vertices[index + 2]);
  60428. result.push(nV1);
  60429. result.push(nV2);
  60430. result.push(nV3);
  60431. }
  60432. if (!v2Out) {
  60433. nV1 = vertices[index + 1].clone();
  60434. nV2 = clipVertices(nV1, vertices[index + 2]);
  60435. nV3 = clipVertices(nV1, vertices[index]);
  60436. result.push(nV1);
  60437. result.push(nV2);
  60438. result.push(nV3);
  60439. }
  60440. if (!v3Out) {
  60441. nV1 = vertices[index + 2].clone();
  60442. nV2 = clipVertices(nV1, vertices[index]);
  60443. nV3 = clipVertices(nV1, vertices[index + 1]);
  60444. result.push(nV1);
  60445. result.push(nV2);
  60446. result.push(nV3);
  60447. }
  60448. break;
  60449. case 3:
  60450. break;
  60451. }
  60452. }
  60453. return result;
  60454. };
  60455. for (var index = 0; index < indices.length; index += 3) {
  60456. var faceVertices = new Array();
  60457. faceVertices.push(extractDecalVector3(index));
  60458. faceVertices.push(extractDecalVector3(index + 1));
  60459. faceVertices.push(extractDecalVector3(index + 2));
  60460. // Clip
  60461. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  60462. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  60463. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  60464. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  60465. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  60466. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  60467. if (faceVertices.length === 0) {
  60468. continue;
  60469. }
  60470. // Add UVs and get back to world
  60471. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  60472. var vertex = faceVertices[vIndex];
  60473. //TODO check for Int32Array | Uint32Array | Uint16Array
  60474. vertexData.indices.push(currentVertexDataIndex);
  60475. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  60476. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  60477. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  60478. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  60479. currentVertexDataIndex++;
  60480. }
  60481. }
  60482. // Return mesh
  60483. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  60484. vertexData.applyToMesh(decal);
  60485. decal.position = position.clone();
  60486. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  60487. return decal;
  60488. };
  60489. // Privates
  60490. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  60491. // extrusion geometry
  60492. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  60493. var tangents = path3D.getTangents();
  60494. var normals = path3D.getNormals();
  60495. var binormals = path3D.getBinormals();
  60496. var distances = path3D.getDistances();
  60497. var angle = 0;
  60498. var returnScale = function () { return scale !== null ? scale : 1; };
  60499. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  60500. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  60501. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  60502. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60503. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60504. for (var i = 0; i < curve.length; i++) {
  60505. var shapePath = new Array();
  60506. var angleStep = rotate(i, distances[i]);
  60507. var scaleRatio = scl(i, distances[i]);
  60508. for (var p = 0; p < shape.length; p++) {
  60509. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  60510. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  60511. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  60512. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  60513. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  60514. shapePath[p] = rotated;
  60515. }
  60516. shapePaths[index] = shapePath;
  60517. angle += angleStep;
  60518. index++;
  60519. }
  60520. // cap
  60521. var capPath = function (shapePath) {
  60522. var pointCap = Array();
  60523. var barycenter = BABYLON.Vector3.Zero();
  60524. var i;
  60525. for (i = 0; i < shapePath.length; i++) {
  60526. barycenter.addInPlace(shapePath[i]);
  60527. }
  60528. barycenter.scaleInPlace(1.0 / shapePath.length);
  60529. for (i = 0; i < shapePath.length; i++) {
  60530. pointCap.push(barycenter);
  60531. }
  60532. return pointCap;
  60533. };
  60534. switch (cap) {
  60535. case BABYLON.Mesh.NO_CAP:
  60536. break;
  60537. case BABYLON.Mesh.CAP_START:
  60538. shapePaths[0] = capPath(shapePaths[2]);
  60539. shapePaths[1] = shapePaths[2];
  60540. break;
  60541. case BABYLON.Mesh.CAP_END:
  60542. shapePaths[index] = shapePaths[index - 1];
  60543. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  60544. break;
  60545. case BABYLON.Mesh.CAP_ALL:
  60546. shapePaths[0] = capPath(shapePaths[2]);
  60547. shapePaths[1] = shapePaths[2];
  60548. shapePaths[index] = shapePaths[index - 1];
  60549. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  60550. break;
  60551. default:
  60552. break;
  60553. }
  60554. return shapePaths;
  60555. };
  60556. var path3D;
  60557. var pathArray;
  60558. if (instance) {
  60559. path3D = (instance.path3D).update(curve);
  60560. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  60561. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  60562. return instance;
  60563. }
  60564. // extruded shape creation
  60565. path3D = new BABYLON.Path3D(curve);
  60566. var newShapePaths = new Array();
  60567. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60568. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  60569. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  60570. extrudedGeneric.pathArray = pathArray;
  60571. extrudedGeneric.path3D = path3D;
  60572. extrudedGeneric.cap = cap;
  60573. return extrudedGeneric;
  60574. };
  60575. return MeshBuilder;
  60576. }());
  60577. BABYLON.MeshBuilder = MeshBuilder;
  60578. })(BABYLON || (BABYLON = {}));
  60579. //# sourceMappingURL=babylon.meshBuilder.js.map
  60580. "use strict";
  60581. var BABYLON;
  60582. (function (BABYLON) {
  60583. /**
  60584. * Draco compression (https://google.github.io/draco/)
  60585. */
  60586. var DracoCompression = /** @class */ (function () {
  60587. /**
  60588. * Constructor
  60589. */
  60590. function DracoCompression() {
  60591. }
  60592. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  60593. /**
  60594. * Returns true if the decoder is available.
  60595. */
  60596. get: function () {
  60597. return (typeof DracoDecoderModule !== "undefined" ||
  60598. (typeof WebAssembly === "object" && !!DracoCompression.Configuration.decoderWasm) ||
  60599. !!DracoCompression.Configuration.decoder);
  60600. },
  60601. enumerable: true,
  60602. configurable: true
  60603. });
  60604. /**
  60605. * Stop all async operations and release resources.
  60606. */
  60607. DracoCompression.prototype.dispose = function () {
  60608. };
  60609. /**
  60610. * Decode Draco compressed mesh data to vertex data.
  60611. * @param data The array buffer view for the Draco compression data
  60612. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  60613. * @returns A promise that resolves with the decoded vertex data
  60614. */
  60615. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  60616. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  60617. var module = wrappedModule.module;
  60618. var vertexData = new BABYLON.VertexData();
  60619. var buffer = new module.DecoderBuffer();
  60620. buffer.Init(data, data.byteLength);
  60621. var decoder = new module.Decoder();
  60622. var geometry;
  60623. var status;
  60624. try {
  60625. var type = decoder.GetEncodedGeometryType(buffer);
  60626. switch (type) {
  60627. case module.TRIANGULAR_MESH:
  60628. geometry = new module.Mesh();
  60629. status = decoder.DecodeBufferToMesh(buffer, geometry);
  60630. break;
  60631. case module.POINT_CLOUD:
  60632. geometry = new module.PointCloud();
  60633. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  60634. break;
  60635. default:
  60636. throw new Error("Invalid geometry type " + type);
  60637. }
  60638. if (!status.ok() || !geometry.ptr) {
  60639. throw new Error(status.error_msg());
  60640. }
  60641. var numPoints = geometry.num_points();
  60642. if (type === module.TRIANGULAR_MESH) {
  60643. var numFaces = geometry.num_faces();
  60644. var faceIndices = new module.DracoInt32Array();
  60645. try {
  60646. var indices = new Uint32Array(numFaces * 3);
  60647. for (var i = 0; i < numFaces; i++) {
  60648. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  60649. var offset = i * 3;
  60650. indices[offset + 0] = faceIndices.GetValue(0);
  60651. indices[offset + 1] = faceIndices.GetValue(1);
  60652. indices[offset + 2] = faceIndices.GetValue(2);
  60653. }
  60654. vertexData.indices = indices;
  60655. }
  60656. finally {
  60657. module.destroy(faceIndices);
  60658. }
  60659. }
  60660. for (var kind in attributes) {
  60661. var uniqueId = attributes[kind];
  60662. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  60663. var dracoData = new module.DracoFloat32Array();
  60664. try {
  60665. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  60666. var babylonData = new Float32Array(numPoints * attribute.num_components());
  60667. for (var i = 0; i < babylonData.length; i++) {
  60668. babylonData[i] = dracoData.GetValue(i);
  60669. }
  60670. vertexData.set(babylonData, kind);
  60671. }
  60672. finally {
  60673. module.destroy(dracoData);
  60674. }
  60675. }
  60676. }
  60677. finally {
  60678. if (geometry) {
  60679. module.destroy(geometry);
  60680. }
  60681. module.destroy(decoder);
  60682. module.destroy(buffer);
  60683. }
  60684. return vertexData;
  60685. });
  60686. };
  60687. DracoCompression._GetDecoderModule = function () {
  60688. if (!DracoCompression._DecoderModulePromise) {
  60689. var promise = void 0;
  60690. var config_1 = {};
  60691. if (typeof DracoDecoderModule !== "undefined") {
  60692. promise = Promise.resolve();
  60693. }
  60694. else if (typeof WebAssembly === "object" && DracoCompression.Configuration.decoderWasm) {
  60695. promise = Promise.all([
  60696. DracoCompression._LoadScriptAsync(DracoCompression.Configuration.decoderWasm.wrapperUrl),
  60697. DracoCompression._LoadFileAsync(DracoCompression.Configuration.decoderWasm.binaryUrl).then(function (data) {
  60698. config_1.wasmBinary = data;
  60699. })
  60700. ]);
  60701. }
  60702. else if (DracoCompression.Configuration.decoder) {
  60703. promise = DracoCompression._LoadScriptAsync(DracoCompression.Configuration.decoder.url);
  60704. }
  60705. else {
  60706. throw new Error("Invalid decoder configuration");
  60707. }
  60708. DracoCompression._DecoderModulePromise = promise.then(function () {
  60709. return new Promise(function (resolve) {
  60710. config_1.onModuleLoaded = function (decoderModule) {
  60711. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  60712. resolve({ module: decoderModule });
  60713. };
  60714. DracoDecoderModule(config_1);
  60715. });
  60716. });
  60717. }
  60718. return DracoCompression._DecoderModulePromise;
  60719. };
  60720. DracoCompression._LoadScriptAsync = function (url) {
  60721. return new Promise(function (resolve, reject) {
  60722. BABYLON.Tools.LoadScript(url, function () {
  60723. resolve();
  60724. }, function (message) {
  60725. reject(new Error(message));
  60726. });
  60727. });
  60728. };
  60729. DracoCompression._LoadFileAsync = function (url) {
  60730. return new Promise(function (resolve, reject) {
  60731. BABYLON.Tools.LoadFile(url, function (data) {
  60732. resolve(data);
  60733. }, undefined, undefined, true, function (request, exception) {
  60734. reject(exception);
  60735. });
  60736. });
  60737. };
  60738. DracoCompression._GetDefaultConfig = function () {
  60739. var configuration = {
  60740. decoder: null,
  60741. decoderWasm: null
  60742. };
  60743. if (BABYLON.Tools.IsWindowObjectExist()) {
  60744. var decoderUrl = null;
  60745. var decoderWasmBinaryUrl = null;
  60746. var decoderWasmWrapperUrl = null;
  60747. for (var i = 0; i < document.scripts.length; i++) {
  60748. var type = document.scripts[i].type;
  60749. var src = document.scripts[i].src;
  60750. switch (type) {
  60751. case "text/x-draco-decoder": {
  60752. decoderUrl = src;
  60753. break;
  60754. }
  60755. case "text/x-draco-decoder-wasm-binary": {
  60756. decoderWasmBinaryUrl = src;
  60757. break;
  60758. }
  60759. case "text/x-draco-decoder-wasm-wrapper": {
  60760. decoderWasmWrapperUrl = src;
  60761. break;
  60762. }
  60763. }
  60764. }
  60765. if (decoderUrl) {
  60766. configuration.decoder = {
  60767. url: decoderUrl
  60768. };
  60769. }
  60770. if (decoderWasmWrapperUrl && decoderWasmBinaryUrl) {
  60771. configuration.decoderWasm = {
  60772. binaryUrl: decoderWasmBinaryUrl,
  60773. wrapperUrl: decoderWasmWrapperUrl
  60774. };
  60775. }
  60776. }
  60777. return configuration;
  60778. };
  60779. /**
  60780. * Gets the configuration.
  60781. */
  60782. DracoCompression.Configuration = DracoCompression._GetDefaultConfig();
  60783. return DracoCompression;
  60784. }());
  60785. BABYLON.DracoCompression = DracoCompression;
  60786. })(BABYLON || (BABYLON = {}));
  60787. //# sourceMappingURL=babylon.dracoCompression.js.map
  60788. "use strict";
  60789. var BABYLON;
  60790. (function (BABYLON) {
  60791. var AudioEngine = /** @class */ (function () {
  60792. function AudioEngine() {
  60793. this._audioContext = null;
  60794. this._audioContextInitialized = false;
  60795. this.canUseWebAudio = false;
  60796. this.WarnedWebAudioUnsupported = false;
  60797. this.unlocked = false;
  60798. this.isMP3supported = false;
  60799. this.isOGGsupported = false;
  60800. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  60801. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  60802. this.canUseWebAudio = true;
  60803. }
  60804. var audioElem = document.createElement('audio');
  60805. try {
  60806. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  60807. this.isMP3supported = true;
  60808. }
  60809. }
  60810. catch (e) {
  60811. // protect error during capability check.
  60812. }
  60813. try {
  60814. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  60815. this.isOGGsupported = true;
  60816. }
  60817. }
  60818. catch (e) {
  60819. // protect error during capability check.
  60820. }
  60821. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  60822. this._unlockiOSaudio();
  60823. }
  60824. else {
  60825. this.unlocked = true;
  60826. }
  60827. }
  60828. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  60829. get: function () {
  60830. if (!this._audioContextInitialized) {
  60831. this._initializeAudioContext();
  60832. }
  60833. return this._audioContext;
  60834. },
  60835. enumerable: true,
  60836. configurable: true
  60837. });
  60838. AudioEngine.prototype._unlockiOSaudio = function () {
  60839. var _this = this;
  60840. var unlockaudio = function () {
  60841. if (!_this.audioContext) {
  60842. return;
  60843. }
  60844. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  60845. var source = _this.audioContext.createBufferSource();
  60846. source.buffer = buffer;
  60847. source.connect(_this.audioContext.destination);
  60848. source.start(0);
  60849. setTimeout(function () {
  60850. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  60851. _this.unlocked = true;
  60852. window.removeEventListener('touchend', unlockaudio, false);
  60853. if (_this.onAudioUnlocked) {
  60854. _this.onAudioUnlocked();
  60855. }
  60856. }
  60857. }, 0);
  60858. };
  60859. window.addEventListener('touchend', unlockaudio, false);
  60860. };
  60861. AudioEngine.prototype._initializeAudioContext = function () {
  60862. try {
  60863. if (this.canUseWebAudio) {
  60864. this._audioContext = new AudioContext();
  60865. // create a global volume gain node
  60866. this.masterGain = this._audioContext.createGain();
  60867. this.masterGain.gain.value = 1;
  60868. this.masterGain.connect(this._audioContext.destination);
  60869. this._audioContextInitialized = true;
  60870. }
  60871. }
  60872. catch (e) {
  60873. this.canUseWebAudio = false;
  60874. BABYLON.Tools.Error("Web Audio: " + e.message);
  60875. }
  60876. };
  60877. AudioEngine.prototype.dispose = function () {
  60878. if (this.canUseWebAudio && this._audioContextInitialized) {
  60879. if (this._connectedAnalyser && this._audioContext) {
  60880. this._connectedAnalyser.stopDebugCanvas();
  60881. this._connectedAnalyser.dispose();
  60882. this.masterGain.disconnect();
  60883. this.masterGain.connect(this._audioContext.destination);
  60884. this._connectedAnalyser = null;
  60885. }
  60886. this.masterGain.gain.value = 1;
  60887. }
  60888. this.WarnedWebAudioUnsupported = false;
  60889. };
  60890. AudioEngine.prototype.getGlobalVolume = function () {
  60891. if (this.canUseWebAudio && this._audioContextInitialized) {
  60892. return this.masterGain.gain.value;
  60893. }
  60894. else {
  60895. return -1;
  60896. }
  60897. };
  60898. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  60899. if (this.canUseWebAudio && this._audioContextInitialized) {
  60900. this.masterGain.gain.value = newVolume;
  60901. }
  60902. };
  60903. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  60904. if (this._connectedAnalyser) {
  60905. this._connectedAnalyser.stopDebugCanvas();
  60906. }
  60907. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  60908. this._connectedAnalyser = analyser;
  60909. this.masterGain.disconnect();
  60910. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  60911. }
  60912. };
  60913. return AudioEngine;
  60914. }());
  60915. BABYLON.AudioEngine = AudioEngine;
  60916. })(BABYLON || (BABYLON = {}));
  60917. //# sourceMappingURL=babylon.audioEngine.js.map
  60918. "use strict";
  60919. var BABYLON;
  60920. (function (BABYLON) {
  60921. var Sound = /** @class */ (function () {
  60922. /**
  60923. * Create a sound and attach it to a scene
  60924. * @param name Name of your sound
  60925. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  60926. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  60927. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  60928. */
  60929. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  60930. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  60931. var _this = this;
  60932. this.autoplay = false;
  60933. this.loop = false;
  60934. this.useCustomAttenuation = false;
  60935. this.spatialSound = false;
  60936. this.refDistance = 1;
  60937. this.rolloffFactor = 1;
  60938. this.maxDistance = 100;
  60939. this.distanceModel = "linear";
  60940. this._panningModel = "equalpower";
  60941. this._playbackRate = 1;
  60942. this._streaming = false;
  60943. this._startTime = 0;
  60944. this._startOffset = 0;
  60945. this._position = BABYLON.Vector3.Zero();
  60946. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  60947. this._volume = 1;
  60948. this._isReadyToPlay = false;
  60949. this.isPlaying = false;
  60950. this.isPaused = false;
  60951. this._isDirectional = false;
  60952. // Used if you'd like to create a directional sound.
  60953. // If not set, the sound will be omnidirectional
  60954. this._coneInnerAngle = 360;
  60955. this._coneOuterAngle = 360;
  60956. this._coneOuterGain = 0;
  60957. this._isOutputConnected = false;
  60958. this._urlType = "Unknown";
  60959. this.name = name;
  60960. this._scene = scene;
  60961. this._readyToPlayCallback = readyToPlayCallback;
  60962. // Default custom attenuation function is a linear attenuation
  60963. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  60964. if (currentDistance < maxDistance) {
  60965. return currentVolume * (1 - currentDistance / maxDistance);
  60966. }
  60967. else {
  60968. return 0;
  60969. }
  60970. };
  60971. if (options) {
  60972. this.autoplay = options.autoplay || false;
  60973. this.loop = options.loop || false;
  60974. // if volume === 0, we need another way to check this option
  60975. if (options.volume !== undefined) {
  60976. this._volume = options.volume;
  60977. }
  60978. this.spatialSound = options.spatialSound || false;
  60979. this.maxDistance = options.maxDistance || 100;
  60980. this.useCustomAttenuation = options.useCustomAttenuation || false;
  60981. this.rolloffFactor = options.rolloffFactor || 1;
  60982. this.refDistance = options.refDistance || 1;
  60983. this.distanceModel = options.distanceModel || "linear";
  60984. this._playbackRate = options.playbackRate || 1;
  60985. this._streaming = options.streaming || false;
  60986. }
  60987. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  60988. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  60989. this._soundGain.gain.value = this._volume;
  60990. this._inputAudioNode = this._soundGain;
  60991. this._ouputAudioNode = this._soundGain;
  60992. if (this.spatialSound) {
  60993. this._createSpatialParameters();
  60994. }
  60995. this._scene.mainSoundTrack.AddSound(this);
  60996. var validParameter = true;
  60997. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  60998. if (urlOrArrayBuffer) {
  60999. try {
  61000. if (typeof (urlOrArrayBuffer) === "string")
  61001. this._urlType = "String";
  61002. if (Array.isArray(urlOrArrayBuffer))
  61003. this._urlType = "Array";
  61004. if (urlOrArrayBuffer instanceof ArrayBuffer)
  61005. this._urlType = "ArrayBuffer";
  61006. var urls = [];
  61007. var codecSupportedFound = false;
  61008. switch (this._urlType) {
  61009. case "ArrayBuffer":
  61010. if (urlOrArrayBuffer.byteLength > 0) {
  61011. codecSupportedFound = true;
  61012. this._soundLoaded(urlOrArrayBuffer);
  61013. }
  61014. break;
  61015. case "String":
  61016. urls.push(urlOrArrayBuffer);
  61017. case "Array":
  61018. if (urls.length === 0)
  61019. urls = urlOrArrayBuffer;
  61020. // If we found a supported format, we load it immediately and stop the loop
  61021. for (var i = 0; i < urls.length; i++) {
  61022. var url = urls[i];
  61023. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  61024. codecSupportedFound = true;
  61025. }
  61026. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  61027. codecSupportedFound = true;
  61028. }
  61029. if (url.indexOf(".wav", url.length - 4) !== -1) {
  61030. codecSupportedFound = true;
  61031. }
  61032. if (url.indexOf("blob:") !== -1) {
  61033. codecSupportedFound = true;
  61034. }
  61035. if (codecSupportedFound) {
  61036. // Loading sound using XHR2
  61037. if (!this._streaming) {
  61038. this._scene._loadFile(url, function (data) {
  61039. _this._soundLoaded(data);
  61040. }, undefined, true, true, function (exception) {
  61041. if (exception) {
  61042. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  61043. }
  61044. BABYLON.Tools.Error("Sound creation aborted.");
  61045. _this._scene.mainSoundTrack.RemoveSound(_this);
  61046. });
  61047. }
  61048. else {
  61049. this._htmlAudioElement = new Audio(url);
  61050. this._htmlAudioElement.controls = false;
  61051. this._htmlAudioElement.loop = this.loop;
  61052. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  61053. this._htmlAudioElement.preload = "auto";
  61054. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  61055. _this._isReadyToPlay = true;
  61056. if (_this.autoplay) {
  61057. _this.play();
  61058. }
  61059. if (_this._readyToPlayCallback) {
  61060. _this._readyToPlayCallback();
  61061. }
  61062. });
  61063. document.body.appendChild(this._htmlAudioElement);
  61064. }
  61065. break;
  61066. }
  61067. }
  61068. break;
  61069. default:
  61070. validParameter = false;
  61071. break;
  61072. }
  61073. if (!validParameter) {
  61074. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  61075. }
  61076. else {
  61077. if (!codecSupportedFound) {
  61078. this._isReadyToPlay = true;
  61079. // Simulating a ready to play event to avoid breaking code path
  61080. if (this._readyToPlayCallback) {
  61081. window.setTimeout(function () {
  61082. if (_this._readyToPlayCallback) {
  61083. _this._readyToPlayCallback();
  61084. }
  61085. }, 1000);
  61086. }
  61087. }
  61088. }
  61089. }
  61090. catch (ex) {
  61091. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  61092. this._scene.mainSoundTrack.RemoveSound(this);
  61093. }
  61094. }
  61095. }
  61096. else {
  61097. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  61098. this._scene.mainSoundTrack.AddSound(this);
  61099. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  61100. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  61101. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  61102. }
  61103. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  61104. if (this._readyToPlayCallback) {
  61105. window.setTimeout(function () {
  61106. if (_this._readyToPlayCallback) {
  61107. _this._readyToPlayCallback();
  61108. }
  61109. }, 1000);
  61110. }
  61111. }
  61112. }
  61113. Sound.prototype.dispose = function () {
  61114. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61115. if (this.isPlaying) {
  61116. this.stop();
  61117. }
  61118. this._isReadyToPlay = false;
  61119. if (this.soundTrackId === -1) {
  61120. this._scene.mainSoundTrack.RemoveSound(this);
  61121. }
  61122. else {
  61123. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  61124. }
  61125. if (this._soundGain) {
  61126. this._soundGain.disconnect();
  61127. this._soundGain = null;
  61128. }
  61129. if (this._soundPanner) {
  61130. this._soundPanner.disconnect();
  61131. this._soundPanner = null;
  61132. }
  61133. if (this._soundSource) {
  61134. this._soundSource.disconnect();
  61135. this._soundSource = null;
  61136. }
  61137. this._audioBuffer = null;
  61138. if (this._htmlAudioElement) {
  61139. this._htmlAudioElement.pause();
  61140. this._htmlAudioElement.src = "";
  61141. document.body.removeChild(this._htmlAudioElement);
  61142. }
  61143. if (this._connectedMesh && this._registerFunc) {
  61144. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61145. this._connectedMesh = null;
  61146. }
  61147. }
  61148. };
  61149. Sound.prototype.isReady = function () {
  61150. return this._isReadyToPlay;
  61151. };
  61152. Sound.prototype._soundLoaded = function (audioData) {
  61153. var _this = this;
  61154. if (!BABYLON.Engine.audioEngine.audioContext) {
  61155. return;
  61156. }
  61157. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  61158. _this._audioBuffer = buffer;
  61159. _this._isReadyToPlay = true;
  61160. if (_this.autoplay) {
  61161. _this.play();
  61162. }
  61163. if (_this._readyToPlayCallback) {
  61164. _this._readyToPlayCallback();
  61165. }
  61166. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  61167. };
  61168. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  61169. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61170. this._audioBuffer = audioBuffer;
  61171. this._isReadyToPlay = true;
  61172. }
  61173. };
  61174. Sound.prototype.updateOptions = function (options) {
  61175. if (options) {
  61176. this.loop = options.loop || this.loop;
  61177. this.maxDistance = options.maxDistance || this.maxDistance;
  61178. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  61179. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  61180. this.refDistance = options.refDistance || this.refDistance;
  61181. this.distanceModel = options.distanceModel || this.distanceModel;
  61182. this._playbackRate = options.playbackRate || this._playbackRate;
  61183. this._updateSpatialParameters();
  61184. if (this.isPlaying) {
  61185. if (this._streaming) {
  61186. this._htmlAudioElement.playbackRate = this._playbackRate;
  61187. }
  61188. else {
  61189. if (this._soundSource) {
  61190. this._soundSource.playbackRate.value = this._playbackRate;
  61191. }
  61192. }
  61193. }
  61194. }
  61195. };
  61196. Sound.prototype._createSpatialParameters = function () {
  61197. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61198. if (this._scene.headphone) {
  61199. this._panningModel = "HRTF";
  61200. }
  61201. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  61202. this._updateSpatialParameters();
  61203. this._soundPanner.connect(this._ouputAudioNode);
  61204. this._inputAudioNode = this._soundPanner;
  61205. }
  61206. };
  61207. Sound.prototype._updateSpatialParameters = function () {
  61208. if (this.spatialSound && this._soundPanner) {
  61209. if (this.useCustomAttenuation) {
  61210. // Tricks to disable in a way embedded Web Audio attenuation
  61211. this._soundPanner.distanceModel = "linear";
  61212. this._soundPanner.maxDistance = Number.MAX_VALUE;
  61213. this._soundPanner.refDistance = 1;
  61214. this._soundPanner.rolloffFactor = 1;
  61215. this._soundPanner.panningModel = this._panningModel;
  61216. }
  61217. else {
  61218. this._soundPanner.distanceModel = this.distanceModel;
  61219. this._soundPanner.maxDistance = this.maxDistance;
  61220. this._soundPanner.refDistance = this.refDistance;
  61221. this._soundPanner.rolloffFactor = this.rolloffFactor;
  61222. this._soundPanner.panningModel = this._panningModel;
  61223. }
  61224. }
  61225. };
  61226. Sound.prototype.switchPanningModelToHRTF = function () {
  61227. this._panningModel = "HRTF";
  61228. this._switchPanningModel();
  61229. };
  61230. Sound.prototype.switchPanningModelToEqualPower = function () {
  61231. this._panningModel = "equalpower";
  61232. this._switchPanningModel();
  61233. };
  61234. Sound.prototype._switchPanningModel = function () {
  61235. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61236. this._soundPanner.panningModel = this._panningModel;
  61237. }
  61238. };
  61239. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  61240. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61241. if (this._isOutputConnected) {
  61242. this._ouputAudioNode.disconnect();
  61243. }
  61244. this._ouputAudioNode.connect(soundTrackAudioNode);
  61245. this._isOutputConnected = true;
  61246. }
  61247. };
  61248. /**
  61249. * Transform this sound into a directional source
  61250. * @param coneInnerAngle Size of the inner cone in degree
  61251. * @param coneOuterAngle Size of the outer cone in degree
  61252. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  61253. */
  61254. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  61255. if (coneOuterAngle < coneInnerAngle) {
  61256. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  61257. return;
  61258. }
  61259. this._coneInnerAngle = coneInnerAngle;
  61260. this._coneOuterAngle = coneOuterAngle;
  61261. this._coneOuterGain = coneOuterGain;
  61262. this._isDirectional = true;
  61263. if (this.isPlaying && this.loop) {
  61264. this.stop();
  61265. this.play();
  61266. }
  61267. };
  61268. Sound.prototype.setPosition = function (newPosition) {
  61269. this._position = newPosition;
  61270. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61271. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61272. }
  61273. };
  61274. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  61275. this._localDirection = newLocalDirection;
  61276. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  61277. this._updateDirection();
  61278. }
  61279. };
  61280. Sound.prototype._updateDirection = function () {
  61281. if (!this._connectedMesh || !this._soundPanner) {
  61282. return;
  61283. }
  61284. var mat = this._connectedMesh.getWorldMatrix();
  61285. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  61286. direction.normalize();
  61287. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  61288. };
  61289. Sound.prototype.updateDistanceFromListener = function () {
  61290. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  61291. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  61292. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  61293. }
  61294. };
  61295. Sound.prototype.setAttenuationFunction = function (callback) {
  61296. this._customAttenuationFunction = callback;
  61297. };
  61298. /**
  61299. * Play the sound
  61300. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  61301. * @param offset (optional) Start the sound setting it at a specific time
  61302. */
  61303. Sound.prototype.play = function (time, offset) {
  61304. var _this = this;
  61305. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  61306. try {
  61307. if (this._startOffset < 0) {
  61308. time = -this._startOffset;
  61309. this._startOffset = 0;
  61310. }
  61311. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61312. if (!this._soundSource || !this._streamingSource) {
  61313. if (this.spatialSound && this._soundPanner) {
  61314. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61315. if (this._isDirectional) {
  61316. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  61317. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  61318. this._soundPanner.coneOuterGain = this._coneOuterGain;
  61319. if (this._connectedMesh) {
  61320. this._updateDirection();
  61321. }
  61322. else {
  61323. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  61324. }
  61325. }
  61326. }
  61327. }
  61328. if (this._streaming) {
  61329. if (!this._streamingSource) {
  61330. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  61331. this._htmlAudioElement.onended = function () { _this._onended(); };
  61332. this._htmlAudioElement.playbackRate = this._playbackRate;
  61333. }
  61334. this._streamingSource.disconnect();
  61335. this._streamingSource.connect(this._inputAudioNode);
  61336. this._htmlAudioElement.play();
  61337. }
  61338. else {
  61339. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  61340. this._soundSource.buffer = this._audioBuffer;
  61341. this._soundSource.connect(this._inputAudioNode);
  61342. this._soundSource.loop = this.loop;
  61343. this._soundSource.playbackRate.value = this._playbackRate;
  61344. this._soundSource.onended = function () { _this._onended(); };
  61345. if (this._soundSource.buffer) {
  61346. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  61347. }
  61348. }
  61349. this._startTime = startTime;
  61350. this.isPlaying = true;
  61351. this.isPaused = false;
  61352. }
  61353. catch (ex) {
  61354. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  61355. }
  61356. }
  61357. };
  61358. Sound.prototype._onended = function () {
  61359. this.isPlaying = false;
  61360. if (this.onended) {
  61361. this.onended();
  61362. }
  61363. };
  61364. /**
  61365. * Stop the sound
  61366. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  61367. */
  61368. Sound.prototype.stop = function (time) {
  61369. if (this.isPlaying) {
  61370. if (this._streaming) {
  61371. this._htmlAudioElement.pause();
  61372. // Test needed for Firefox or it will generate an Invalid State Error
  61373. if (this._htmlAudioElement.currentTime > 0) {
  61374. this._htmlAudioElement.currentTime = 0;
  61375. }
  61376. }
  61377. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  61378. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61379. this._soundSource.stop(stopTime);
  61380. this._soundSource.onended = function () { };
  61381. if (!this.isPaused) {
  61382. this._startOffset = 0;
  61383. }
  61384. }
  61385. this.isPlaying = false;
  61386. }
  61387. };
  61388. Sound.prototype.pause = function () {
  61389. if (this.isPlaying) {
  61390. this.isPaused = true;
  61391. if (this._streaming) {
  61392. this._htmlAudioElement.pause();
  61393. }
  61394. else if (BABYLON.Engine.audioEngine.audioContext) {
  61395. this.stop(0);
  61396. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  61397. }
  61398. }
  61399. };
  61400. Sound.prototype.setVolume = function (newVolume, time) {
  61401. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  61402. if (time && BABYLON.Engine.audioEngine.audioContext) {
  61403. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  61404. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  61405. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  61406. }
  61407. else {
  61408. this._soundGain.gain.value = newVolume;
  61409. }
  61410. }
  61411. this._volume = newVolume;
  61412. };
  61413. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  61414. this._playbackRate = newPlaybackRate;
  61415. if (this.isPlaying) {
  61416. if (this._streaming) {
  61417. this._htmlAudioElement.playbackRate = this._playbackRate;
  61418. }
  61419. else if (this._soundSource) {
  61420. this._soundSource.playbackRate.value = this._playbackRate;
  61421. }
  61422. }
  61423. };
  61424. Sound.prototype.getVolume = function () {
  61425. return this._volume;
  61426. };
  61427. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  61428. var _this = this;
  61429. if (this._connectedMesh && this._registerFunc) {
  61430. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61431. this._registerFunc = null;
  61432. }
  61433. this._connectedMesh = meshToConnectTo;
  61434. if (!this.spatialSound) {
  61435. this.spatialSound = true;
  61436. this._createSpatialParameters();
  61437. if (this.isPlaying && this.loop) {
  61438. this.stop();
  61439. this.play();
  61440. }
  61441. }
  61442. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  61443. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  61444. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  61445. };
  61446. Sound.prototype.detachFromMesh = function () {
  61447. if (this._connectedMesh && this._registerFunc) {
  61448. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61449. this._registerFunc = null;
  61450. this._connectedMesh = null;
  61451. }
  61452. };
  61453. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  61454. if (!node.getBoundingInfo) {
  61455. return;
  61456. }
  61457. var mesh = node;
  61458. var boundingInfo = mesh.getBoundingInfo();
  61459. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  61460. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  61461. this._updateDirection();
  61462. }
  61463. };
  61464. Sound.prototype.clone = function () {
  61465. var _this = this;
  61466. if (!this._streaming) {
  61467. var setBufferAndRun = function () {
  61468. if (_this._isReadyToPlay) {
  61469. clonedSound._audioBuffer = _this.getAudioBuffer();
  61470. clonedSound._isReadyToPlay = true;
  61471. if (clonedSound.autoplay) {
  61472. clonedSound.play();
  61473. }
  61474. }
  61475. else {
  61476. window.setTimeout(setBufferAndRun, 300);
  61477. }
  61478. };
  61479. var currentOptions = {
  61480. autoplay: this.autoplay, loop: this.loop,
  61481. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  61482. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  61483. refDistance: this.refDistance, distanceModel: this.distanceModel
  61484. };
  61485. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  61486. if (this.useCustomAttenuation) {
  61487. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  61488. }
  61489. clonedSound.setPosition(this._position);
  61490. clonedSound.setPlaybackRate(this._playbackRate);
  61491. setBufferAndRun();
  61492. return clonedSound;
  61493. }
  61494. else {
  61495. return null;
  61496. }
  61497. };
  61498. Sound.prototype.getAudioBuffer = function () {
  61499. return this._audioBuffer;
  61500. };
  61501. Sound.prototype.serialize = function () {
  61502. var serializationObject = {
  61503. name: this.name,
  61504. url: this.name,
  61505. autoplay: this.autoplay,
  61506. loop: this.loop,
  61507. volume: this._volume,
  61508. spatialSound: this.spatialSound,
  61509. maxDistance: this.maxDistance,
  61510. rolloffFactor: this.rolloffFactor,
  61511. refDistance: this.refDistance,
  61512. distanceModel: this.distanceModel,
  61513. playbackRate: this._playbackRate,
  61514. panningModel: this._panningModel,
  61515. soundTrackId: this.soundTrackId
  61516. };
  61517. if (this.spatialSound) {
  61518. if (this._connectedMesh)
  61519. serializationObject.connectedMeshId = this._connectedMesh.id;
  61520. serializationObject.position = this._position.asArray();
  61521. serializationObject.refDistance = this.refDistance;
  61522. serializationObject.distanceModel = this.distanceModel;
  61523. serializationObject.isDirectional = this._isDirectional;
  61524. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  61525. serializationObject.coneInnerAngle = this._coneInnerAngle;
  61526. serializationObject.coneOuterAngle = this._coneOuterAngle;
  61527. serializationObject.coneOuterGain = this._coneOuterGain;
  61528. }
  61529. return serializationObject;
  61530. };
  61531. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  61532. var soundName = parsedSound.name;
  61533. var soundUrl;
  61534. if (parsedSound.url) {
  61535. soundUrl = rootUrl + parsedSound.url;
  61536. }
  61537. else {
  61538. soundUrl = rootUrl + soundName;
  61539. }
  61540. var options = {
  61541. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  61542. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  61543. rolloffFactor: parsedSound.rolloffFactor,
  61544. refDistance: parsedSound.refDistance,
  61545. distanceModel: parsedSound.distanceModel,
  61546. playbackRate: parsedSound.playbackRate
  61547. };
  61548. var newSound;
  61549. if (!sourceSound) {
  61550. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  61551. scene._addPendingData(newSound);
  61552. }
  61553. else {
  61554. var setBufferAndRun = function () {
  61555. if (sourceSound._isReadyToPlay) {
  61556. newSound._audioBuffer = sourceSound.getAudioBuffer();
  61557. newSound._isReadyToPlay = true;
  61558. if (newSound.autoplay) {
  61559. newSound.play();
  61560. }
  61561. }
  61562. else {
  61563. window.setTimeout(setBufferAndRun, 300);
  61564. }
  61565. };
  61566. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  61567. setBufferAndRun();
  61568. }
  61569. if (parsedSound.position) {
  61570. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  61571. newSound.setPosition(soundPosition);
  61572. }
  61573. if (parsedSound.isDirectional) {
  61574. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  61575. if (parsedSound.localDirectionToMesh) {
  61576. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  61577. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  61578. }
  61579. }
  61580. if (parsedSound.connectedMeshId) {
  61581. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  61582. if (connectedMesh) {
  61583. newSound.attachToMesh(connectedMesh);
  61584. }
  61585. }
  61586. return newSound;
  61587. };
  61588. return Sound;
  61589. }());
  61590. BABYLON.Sound = Sound;
  61591. })(BABYLON || (BABYLON = {}));
  61592. //# sourceMappingURL=babylon.sound.js.map
  61593. "use strict";
  61594. var BABYLON;
  61595. (function (BABYLON) {
  61596. var SoundTrack = /** @class */ (function () {
  61597. function SoundTrack(scene, options) {
  61598. this.id = -1;
  61599. this._isMainTrack = false;
  61600. this._isInitialized = false;
  61601. this._scene = scene;
  61602. this.soundCollection = new Array();
  61603. this._options = options;
  61604. if (!this._isMainTrack) {
  61605. this._scene.soundTracks.push(this);
  61606. this.id = this._scene.soundTracks.length - 1;
  61607. }
  61608. }
  61609. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  61610. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61611. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  61612. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  61613. if (this._options) {
  61614. if (this._options.volume) {
  61615. this._outputAudioNode.gain.value = this._options.volume;
  61616. }
  61617. if (this._options.mainTrack) {
  61618. this._isMainTrack = this._options.mainTrack;
  61619. }
  61620. }
  61621. this._isInitialized = true;
  61622. }
  61623. };
  61624. SoundTrack.prototype.dispose = function () {
  61625. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  61626. if (this._connectedAnalyser) {
  61627. this._connectedAnalyser.stopDebugCanvas();
  61628. }
  61629. while (this.soundCollection.length) {
  61630. this.soundCollection[0].dispose();
  61631. }
  61632. if (this._outputAudioNode) {
  61633. this._outputAudioNode.disconnect();
  61634. }
  61635. this._outputAudioNode = null;
  61636. }
  61637. };
  61638. SoundTrack.prototype.AddSound = function (sound) {
  61639. if (!this._isInitialized) {
  61640. this._initializeSoundTrackAudioGraph();
  61641. }
  61642. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  61643. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  61644. }
  61645. if (sound.soundTrackId) {
  61646. if (sound.soundTrackId === -1) {
  61647. this._scene.mainSoundTrack.RemoveSound(sound);
  61648. }
  61649. else {
  61650. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  61651. }
  61652. }
  61653. this.soundCollection.push(sound);
  61654. sound.soundTrackId = this.id;
  61655. };
  61656. SoundTrack.prototype.RemoveSound = function (sound) {
  61657. var index = this.soundCollection.indexOf(sound);
  61658. if (index !== -1) {
  61659. this.soundCollection.splice(index, 1);
  61660. }
  61661. };
  61662. SoundTrack.prototype.setVolume = function (newVolume) {
  61663. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  61664. this._outputAudioNode.gain.value = newVolume;
  61665. }
  61666. };
  61667. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  61668. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61669. for (var i = 0; i < this.soundCollection.length; i++) {
  61670. this.soundCollection[i].switchPanningModelToHRTF();
  61671. }
  61672. }
  61673. };
  61674. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  61675. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61676. for (var i = 0; i < this.soundCollection.length; i++) {
  61677. this.soundCollection[i].switchPanningModelToEqualPower();
  61678. }
  61679. }
  61680. };
  61681. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  61682. if (this._connectedAnalyser) {
  61683. this._connectedAnalyser.stopDebugCanvas();
  61684. }
  61685. this._connectedAnalyser = analyser;
  61686. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  61687. this._outputAudioNode.disconnect();
  61688. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  61689. }
  61690. };
  61691. return SoundTrack;
  61692. }());
  61693. BABYLON.SoundTrack = SoundTrack;
  61694. })(BABYLON || (BABYLON = {}));
  61695. //# sourceMappingURL=babylon.soundtrack.js.map
  61696. "use strict";
  61697. var BABYLON;
  61698. (function (BABYLON) {
  61699. var Analyser = /** @class */ (function () {
  61700. function Analyser(scene) {
  61701. this.SMOOTHING = 0.75;
  61702. this.FFT_SIZE = 512;
  61703. this.BARGRAPHAMPLITUDE = 256;
  61704. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  61705. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  61706. this._scene = scene;
  61707. this._audioEngine = BABYLON.Engine.audioEngine;
  61708. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  61709. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  61710. this._webAudioAnalyser.minDecibels = -140;
  61711. this._webAudioAnalyser.maxDecibels = 0;
  61712. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  61713. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  61714. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  61715. }
  61716. }
  61717. Analyser.prototype.getFrequencyBinCount = function () {
  61718. if (this._audioEngine.canUseWebAudio) {
  61719. return this._webAudioAnalyser.frequencyBinCount;
  61720. }
  61721. else {
  61722. return 0;
  61723. }
  61724. };
  61725. Analyser.prototype.getByteFrequencyData = function () {
  61726. if (this._audioEngine.canUseWebAudio) {
  61727. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61728. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61729. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  61730. }
  61731. return this._byteFreqs;
  61732. };
  61733. Analyser.prototype.getByteTimeDomainData = function () {
  61734. if (this._audioEngine.canUseWebAudio) {
  61735. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61736. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61737. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  61738. }
  61739. return this._byteTime;
  61740. };
  61741. Analyser.prototype.getFloatFrequencyData = function () {
  61742. if (this._audioEngine.canUseWebAudio) {
  61743. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61744. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61745. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  61746. }
  61747. return this._floatFreqs;
  61748. };
  61749. Analyser.prototype.drawDebugCanvas = function () {
  61750. var _this = this;
  61751. if (this._audioEngine.canUseWebAudio) {
  61752. if (!this._debugCanvas) {
  61753. this._debugCanvas = document.createElement("canvas");
  61754. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  61755. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  61756. this._debugCanvas.style.position = "absolute";
  61757. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  61758. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  61759. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  61760. document.body.appendChild(this._debugCanvas);
  61761. this._registerFunc = function () {
  61762. _this.drawDebugCanvas();
  61763. };
  61764. this._scene.registerBeforeRender(this._registerFunc);
  61765. }
  61766. if (this._registerFunc && this._debugCanvasContext) {
  61767. var workingArray = this.getByteFrequencyData();
  61768. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  61769. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  61770. // Draw the frequency domain chart.
  61771. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  61772. var value = workingArray[i];
  61773. var percent = value / this.BARGRAPHAMPLITUDE;
  61774. var height = this.DEBUGCANVASSIZE.height * percent;
  61775. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  61776. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  61777. var hue = i / this.getFrequencyBinCount() * 360;
  61778. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  61779. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  61780. }
  61781. }
  61782. }
  61783. };
  61784. Analyser.prototype.stopDebugCanvas = function () {
  61785. if (this._debugCanvas) {
  61786. if (this._registerFunc) {
  61787. this._scene.unregisterBeforeRender(this._registerFunc);
  61788. this._registerFunc = null;
  61789. }
  61790. document.body.removeChild(this._debugCanvas);
  61791. this._debugCanvas = null;
  61792. this._debugCanvasContext = null;
  61793. }
  61794. };
  61795. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  61796. if (this._audioEngine.canUseWebAudio) {
  61797. inputAudioNode.connect(this._webAudioAnalyser);
  61798. this._webAudioAnalyser.connect(outputAudioNode);
  61799. }
  61800. };
  61801. Analyser.prototype.dispose = function () {
  61802. if (this._audioEngine.canUseWebAudio) {
  61803. this._webAudioAnalyser.disconnect();
  61804. }
  61805. };
  61806. return Analyser;
  61807. }());
  61808. BABYLON.Analyser = Analyser;
  61809. })(BABYLON || (BABYLON = {}));
  61810. //# sourceMappingURL=babylon.analyser.js.map
  61811. "use strict";
  61812. var BABYLON;
  61813. (function (BABYLON) {
  61814. var CubeTexture = /** @class */ (function (_super) {
  61815. __extends(CubeTexture, _super);
  61816. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  61817. if (extensions === void 0) { extensions = null; }
  61818. if (noMipmap === void 0) { noMipmap = false; }
  61819. if (files === void 0) { files = null; }
  61820. if (onLoad === void 0) { onLoad = null; }
  61821. if (onError === void 0) { onError = null; }
  61822. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  61823. if (prefiltered === void 0) { prefiltered = false; }
  61824. if (forcedExtension === void 0) { forcedExtension = null; }
  61825. var _this = _super.call(this, scene) || this;
  61826. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  61827. /**
  61828. * Gets or sets the center of the bounding box associated with the cube texture
  61829. * It must define where the camera used to render the texture was set
  61830. */
  61831. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  61832. _this._rotationY = 0;
  61833. _this.name = rootUrl;
  61834. _this.url = rootUrl;
  61835. _this._noMipmap = noMipmap;
  61836. _this.hasAlpha = false;
  61837. _this._format = format;
  61838. _this._prefiltered = prefiltered;
  61839. _this.isCube = true;
  61840. _this._textureMatrix = BABYLON.Matrix.Identity();
  61841. if (prefiltered) {
  61842. _this.gammaSpace = false;
  61843. }
  61844. if (!rootUrl && !files) {
  61845. return _this;
  61846. }
  61847. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  61848. var lastDot = rootUrl.lastIndexOf(".");
  61849. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  61850. var isDDS = (extension === ".dds");
  61851. if (!files) {
  61852. if (!isDDS && !extensions) {
  61853. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  61854. }
  61855. files = [];
  61856. if (extensions) {
  61857. for (var index = 0; index < extensions.length; index++) {
  61858. files.push(rootUrl + extensions[index]);
  61859. }
  61860. }
  61861. }
  61862. _this._files = files;
  61863. if (!_this._texture) {
  61864. if (!scene.useDelayedTextureLoading) {
  61865. if (prefiltered) {
  61866. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  61867. }
  61868. else {
  61869. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  61870. }
  61871. }
  61872. else {
  61873. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  61874. }
  61875. }
  61876. else if (onLoad) {
  61877. if (_this._texture.isReady) {
  61878. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  61879. }
  61880. else {
  61881. _this._texture.onLoadedObservable.add(onLoad);
  61882. }
  61883. }
  61884. return _this;
  61885. }
  61886. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  61887. get: function () {
  61888. return this._boundingBoxSize;
  61889. },
  61890. /**
  61891. * Gets or sets the size of the bounding box associated with the cube texture
  61892. * When defined, the cubemap will switch to local mode
  61893. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  61894. * @example https://www.babylonjs-playground.com/#RNASML
  61895. */
  61896. set: function (value) {
  61897. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  61898. return;
  61899. }
  61900. this._boundingBoxSize = value;
  61901. var scene = this.getScene();
  61902. if (scene) {
  61903. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  61904. }
  61905. },
  61906. enumerable: true,
  61907. configurable: true
  61908. });
  61909. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  61910. /**
  61911. * Gets texture matrix rotation angle around Y axis radians.
  61912. */
  61913. get: function () {
  61914. return this._rotationY;
  61915. },
  61916. /**
  61917. * Sets texture matrix rotation angle around Y axis in radians.
  61918. */
  61919. set: function (value) {
  61920. this._rotationY = value;
  61921. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  61922. },
  61923. enumerable: true,
  61924. configurable: true
  61925. });
  61926. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  61927. var rootUrlKey = "";
  61928. files.forEach(function (url) { return rootUrlKey += url; });
  61929. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  61930. };
  61931. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  61932. if (forcedExtension === void 0) { forcedExtension = null; }
  61933. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  61934. };
  61935. // Methods
  61936. CubeTexture.prototype.delayLoad = function () {
  61937. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  61938. return;
  61939. }
  61940. var scene = this.getScene();
  61941. if (!scene) {
  61942. return;
  61943. }
  61944. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  61945. this._texture = this._getFromCache(this.url, this._noMipmap);
  61946. if (!this._texture) {
  61947. if (this._prefiltered) {
  61948. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  61949. }
  61950. else {
  61951. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  61952. }
  61953. }
  61954. };
  61955. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  61956. return this._textureMatrix;
  61957. };
  61958. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  61959. this._textureMatrix = value;
  61960. };
  61961. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  61962. var texture = BABYLON.SerializationHelper.Parse(function () {
  61963. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  61964. }, parsedTexture, scene);
  61965. // Local Cubemaps
  61966. if (parsedTexture.boundingBoxPosition) {
  61967. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  61968. }
  61969. if (parsedTexture.boundingBoxSize) {
  61970. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  61971. }
  61972. // Animations
  61973. if (parsedTexture.animations) {
  61974. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  61975. var parsedAnimation = parsedTexture.animations[animationIndex];
  61976. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  61977. }
  61978. }
  61979. return texture;
  61980. };
  61981. CubeTexture.prototype.clone = function () {
  61982. var _this = this;
  61983. return BABYLON.SerializationHelper.Clone(function () {
  61984. var scene = _this.getScene();
  61985. if (!scene) {
  61986. return _this;
  61987. }
  61988. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  61989. }, this);
  61990. };
  61991. __decorate([
  61992. BABYLON.serialize("rotationY")
  61993. ], CubeTexture.prototype, "_rotationY", void 0);
  61994. return CubeTexture;
  61995. }(BABYLON.BaseTexture));
  61996. BABYLON.CubeTexture = CubeTexture;
  61997. })(BABYLON || (BABYLON = {}));
  61998. //# sourceMappingURL=babylon.cubeTexture.js.map
  61999. "use strict";
  62000. var BABYLON;
  62001. (function (BABYLON) {
  62002. var RenderTargetTexture = /** @class */ (function (_super) {
  62003. __extends(RenderTargetTexture, _super);
  62004. /**
  62005. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  62006. * or used a shadow, depth texture...
  62007. * @param name The friendly name of the texture
  62008. * @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)
  62009. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  62010. * @param generateMipMaps True if mip maps need to be generated after render.
  62011. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  62012. * @param type The type of the buffer in the RTT (int, half float, float...)
  62013. * @param isCube True if a cube texture needs to be created
  62014. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  62015. * @param generateDepthBuffer True to generate a depth buffer
  62016. * @param generateStencilBuffer True to generate a stencil buffer
  62017. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  62018. */
  62019. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  62020. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  62021. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62022. if (isCube === void 0) { isCube = false; }
  62023. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62024. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62025. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  62026. if (isMulti === void 0) { isMulti = false; }
  62027. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62028. _this.isCube = isCube;
  62029. /**
  62030. * Use this list to define the list of mesh you want to render.
  62031. */
  62032. _this.renderList = new Array();
  62033. _this.renderParticles = true;
  62034. _this.renderSprites = false;
  62035. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  62036. _this.ignoreCameraViewport = false;
  62037. // Events
  62038. /**
  62039. * An event triggered when the texture is unbind.
  62040. */
  62041. _this.onBeforeBindObservable = new BABYLON.Observable();
  62042. /**
  62043. * An event triggered when the texture is unbind.
  62044. */
  62045. _this.onAfterUnbindObservable = new BABYLON.Observable();
  62046. /**
  62047. * An event triggered before rendering the texture
  62048. */
  62049. _this.onBeforeRenderObservable = new BABYLON.Observable();
  62050. /**
  62051. * An event triggered after rendering the texture
  62052. */
  62053. _this.onAfterRenderObservable = new BABYLON.Observable();
  62054. /**
  62055. * An event triggered after the texture clear
  62056. */
  62057. _this.onClearObservable = new BABYLON.Observable();
  62058. _this._currentRefreshId = -1;
  62059. _this._refreshRate = 1;
  62060. _this._samples = 1;
  62061. /**
  62062. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  62063. * It must define where the camera used to render the texture is set
  62064. */
  62065. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62066. scene = _this.getScene();
  62067. if (!scene) {
  62068. return _this;
  62069. }
  62070. _this._engine = scene.getEngine();
  62071. _this.name = name;
  62072. _this.isRenderTarget = true;
  62073. _this._initialSizeParameter = size;
  62074. _this._processSizeParameter(size);
  62075. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  62076. });
  62077. _this._generateMipMaps = generateMipMaps ? true : false;
  62078. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  62079. // Rendering groups
  62080. _this._renderingManager = new BABYLON.RenderingManager(scene);
  62081. if (isMulti) {
  62082. return _this;
  62083. }
  62084. _this._renderTargetOptions = {
  62085. generateMipMaps: generateMipMaps,
  62086. type: type,
  62087. samplingMode: samplingMode,
  62088. generateDepthBuffer: generateDepthBuffer,
  62089. generateStencilBuffer: generateStencilBuffer
  62090. };
  62091. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  62092. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62093. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62094. }
  62095. if (isCube) {
  62096. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  62097. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  62098. _this._textureMatrix = BABYLON.Matrix.Identity();
  62099. }
  62100. else {
  62101. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  62102. }
  62103. return _this;
  62104. }
  62105. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  62106. get: function () {
  62107. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  62108. },
  62109. enumerable: true,
  62110. configurable: true
  62111. });
  62112. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  62113. get: function () {
  62114. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  62115. },
  62116. enumerable: true,
  62117. configurable: true
  62118. });
  62119. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  62120. get: function () {
  62121. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  62122. },
  62123. enumerable: true,
  62124. configurable: true
  62125. });
  62126. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  62127. set: function (callback) {
  62128. if (this._onAfterUnbindObserver) {
  62129. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  62130. }
  62131. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  62132. },
  62133. enumerable: true,
  62134. configurable: true
  62135. });
  62136. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  62137. set: function (callback) {
  62138. if (this._onBeforeRenderObserver) {
  62139. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62140. }
  62141. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62142. },
  62143. enumerable: true,
  62144. configurable: true
  62145. });
  62146. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  62147. set: function (callback) {
  62148. if (this._onAfterRenderObserver) {
  62149. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  62150. }
  62151. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  62152. },
  62153. enumerable: true,
  62154. configurable: true
  62155. });
  62156. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  62157. set: function (callback) {
  62158. if (this._onClearObserver) {
  62159. this.onClearObservable.remove(this._onClearObserver);
  62160. }
  62161. this._onClearObserver = this.onClearObservable.add(callback);
  62162. },
  62163. enumerable: true,
  62164. configurable: true
  62165. });
  62166. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  62167. get: function () {
  62168. return this._renderTargetOptions;
  62169. },
  62170. enumerable: true,
  62171. configurable: true
  62172. });
  62173. RenderTargetTexture.prototype._onRatioRescale = function () {
  62174. if (this._sizeRatio) {
  62175. this.resize(this._initialSizeParameter);
  62176. }
  62177. };
  62178. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  62179. get: function () {
  62180. return this._boundingBoxSize;
  62181. },
  62182. /**
  62183. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  62184. * When defined, the cubemap will switch to local mode
  62185. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62186. * @example https://www.babylonjs-playground.com/#RNASML
  62187. */
  62188. set: function (value) {
  62189. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62190. return;
  62191. }
  62192. this._boundingBoxSize = value;
  62193. var scene = this.getScene();
  62194. if (scene) {
  62195. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62196. }
  62197. },
  62198. enumerable: true,
  62199. configurable: true
  62200. });
  62201. /**
  62202. * Creates a depth stencil texture.
  62203. * This is only available in WebGL 2 or with the depth texture extension available.
  62204. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  62205. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  62206. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  62207. */
  62208. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  62209. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  62210. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  62211. if (generateStencil === void 0) { generateStencil = false; }
  62212. if (!this.getScene()) {
  62213. return;
  62214. }
  62215. var engine = this.getScene().getEngine();
  62216. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  62217. bilinearFiltering: bilinearFiltering,
  62218. comparisonFunction: comparisonFunction,
  62219. generateStencil: generateStencil,
  62220. isCube: this.isCube
  62221. });
  62222. engine.setFrameBufferDepthStencilTexture(this);
  62223. };
  62224. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  62225. if (size.ratio) {
  62226. this._sizeRatio = size.ratio;
  62227. this._size = {
  62228. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  62229. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  62230. };
  62231. }
  62232. else {
  62233. this._size = size;
  62234. }
  62235. };
  62236. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  62237. get: function () {
  62238. return this._samples;
  62239. },
  62240. set: function (value) {
  62241. if (this._samples === value) {
  62242. return;
  62243. }
  62244. var scene = this.getScene();
  62245. if (!scene) {
  62246. return;
  62247. }
  62248. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  62249. },
  62250. enumerable: true,
  62251. configurable: true
  62252. });
  62253. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  62254. this._currentRefreshId = -1;
  62255. };
  62256. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  62257. get: function () {
  62258. return this._refreshRate;
  62259. },
  62260. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62261. set: function (value) {
  62262. this._refreshRate = value;
  62263. this.resetRefreshCounter();
  62264. },
  62265. enumerable: true,
  62266. configurable: true
  62267. });
  62268. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  62269. if (!this._postProcessManager) {
  62270. var scene = this.getScene();
  62271. if (!scene) {
  62272. return;
  62273. }
  62274. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  62275. this._postProcesses = new Array();
  62276. }
  62277. this._postProcesses.push(postProcess);
  62278. this._postProcesses[0].autoClear = false;
  62279. };
  62280. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  62281. if (!this._postProcesses) {
  62282. return;
  62283. }
  62284. if (dispose) {
  62285. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  62286. var postProcess = _a[_i];
  62287. postProcess.dispose();
  62288. }
  62289. }
  62290. this._postProcesses = [];
  62291. };
  62292. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  62293. if (!this._postProcesses) {
  62294. return;
  62295. }
  62296. var index = this._postProcesses.indexOf(postProcess);
  62297. if (index === -1) {
  62298. return;
  62299. }
  62300. this._postProcesses.splice(index, 1);
  62301. if (this._postProcesses.length > 0) {
  62302. this._postProcesses[0].autoClear = false;
  62303. }
  62304. };
  62305. RenderTargetTexture.prototype._shouldRender = function () {
  62306. if (this._currentRefreshId === -1) {
  62307. this._currentRefreshId = 1;
  62308. return true;
  62309. }
  62310. if (this.refreshRate === this._currentRefreshId) {
  62311. this._currentRefreshId = 1;
  62312. return true;
  62313. }
  62314. this._currentRefreshId++;
  62315. return false;
  62316. };
  62317. RenderTargetTexture.prototype.getRenderSize = function () {
  62318. if (this._size.width) {
  62319. return this._size.width;
  62320. }
  62321. return this._size;
  62322. };
  62323. RenderTargetTexture.prototype.getRenderWidth = function () {
  62324. if (this._size.width) {
  62325. return this._size.width;
  62326. }
  62327. return this._size;
  62328. };
  62329. RenderTargetTexture.prototype.getRenderHeight = function () {
  62330. if (this._size.width) {
  62331. return this._size.height;
  62332. }
  62333. return this._size;
  62334. };
  62335. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  62336. get: function () {
  62337. return true;
  62338. },
  62339. enumerable: true,
  62340. configurable: true
  62341. });
  62342. RenderTargetTexture.prototype.scale = function (ratio) {
  62343. var newSize = this.getRenderSize() * ratio;
  62344. this.resize(newSize);
  62345. };
  62346. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  62347. if (this.isCube) {
  62348. return this._textureMatrix;
  62349. }
  62350. return _super.prototype.getReflectionTextureMatrix.call(this);
  62351. };
  62352. RenderTargetTexture.prototype.resize = function (size) {
  62353. this.releaseInternalTexture();
  62354. var scene = this.getScene();
  62355. if (!scene) {
  62356. return;
  62357. }
  62358. this._processSizeParameter(size);
  62359. if (this.isCube) {
  62360. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  62361. }
  62362. else {
  62363. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  62364. }
  62365. };
  62366. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  62367. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  62368. if (dumpForDebug === void 0) { dumpForDebug = false; }
  62369. var scene = this.getScene();
  62370. if (!scene) {
  62371. return;
  62372. }
  62373. var engine = scene.getEngine();
  62374. if (this.useCameraPostProcesses !== undefined) {
  62375. useCameraPostProcess = this.useCameraPostProcesses;
  62376. }
  62377. if (this._waitingRenderList) {
  62378. this.renderList = [];
  62379. for (var index = 0; index < this._waitingRenderList.length; index++) {
  62380. var id = this._waitingRenderList[index];
  62381. var mesh_1 = scene.getMeshByID(id);
  62382. if (mesh_1) {
  62383. this.renderList.push(mesh_1);
  62384. }
  62385. }
  62386. delete this._waitingRenderList;
  62387. }
  62388. // Is predicate defined?
  62389. if (this.renderListPredicate) {
  62390. if (this.renderList) {
  62391. this.renderList.splice(0); // Clear previous renderList
  62392. }
  62393. else {
  62394. this.renderList = [];
  62395. }
  62396. var scene = this.getScene();
  62397. if (!scene) {
  62398. return;
  62399. }
  62400. var sceneMeshes = scene.meshes;
  62401. for (var index = 0; index < sceneMeshes.length; index++) {
  62402. var mesh = sceneMeshes[index];
  62403. if (this.renderListPredicate(mesh)) {
  62404. this.renderList.push(mesh);
  62405. }
  62406. }
  62407. }
  62408. this.onBeforeBindObservable.notifyObservers(this);
  62409. // Set custom projection.
  62410. // Needs to be before binding to prevent changing the aspect ratio.
  62411. var camera;
  62412. if (this.activeCamera) {
  62413. camera = this.activeCamera;
  62414. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62415. if (this.activeCamera !== scene.activeCamera) {
  62416. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  62417. }
  62418. }
  62419. else {
  62420. camera = scene.activeCamera;
  62421. if (camera) {
  62422. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62423. }
  62424. }
  62425. // Prepare renderingManager
  62426. this._renderingManager.reset();
  62427. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  62428. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  62429. var sceneRenderId = scene.getRenderId();
  62430. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  62431. var mesh = currentRenderList[meshIndex];
  62432. if (mesh) {
  62433. if (!mesh.isReady(this.refreshRate === 0)) {
  62434. this.resetRefreshCounter();
  62435. continue;
  62436. }
  62437. mesh._preActivateForIntermediateRendering(sceneRenderId);
  62438. var isMasked = void 0;
  62439. if (!this.renderList && camera) {
  62440. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  62441. }
  62442. else {
  62443. isMasked = false;
  62444. }
  62445. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  62446. mesh._activate(sceneRenderId);
  62447. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  62448. var subMesh = mesh.subMeshes[subIndex];
  62449. scene._activeIndices.addCount(subMesh.indexCount, false);
  62450. this._renderingManager.dispatch(subMesh, mesh);
  62451. }
  62452. }
  62453. }
  62454. }
  62455. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  62456. var particleSystem = scene.particleSystems[particleIndex];
  62457. var emitter = particleSystem.emitter;
  62458. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  62459. continue;
  62460. }
  62461. if (currentRenderList.indexOf(emitter) >= 0) {
  62462. this._renderingManager.dispatchParticles(particleSystem);
  62463. }
  62464. }
  62465. if (this.isCube) {
  62466. for (var face = 0; face < 6; face++) {
  62467. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  62468. scene.incrementRenderId();
  62469. scene.resetCachedMaterial();
  62470. }
  62471. }
  62472. else {
  62473. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  62474. }
  62475. this.onAfterUnbindObservable.notifyObservers(this);
  62476. if (scene.activeCamera) {
  62477. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  62478. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  62479. }
  62480. engine.setViewport(scene.activeCamera.viewport);
  62481. }
  62482. scene.resetCachedMaterial();
  62483. };
  62484. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  62485. var minimum = 128;
  62486. var x = renderDimension * scale;
  62487. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  62488. // Ensure we don't exceed the render dimension (while staying POT)
  62489. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  62490. };
  62491. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  62492. var _this = this;
  62493. if (!this._texture) {
  62494. return;
  62495. }
  62496. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  62497. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  62498. });
  62499. };
  62500. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  62501. var scene = this.getScene();
  62502. if (!scene) {
  62503. return;
  62504. }
  62505. var engine = scene.getEngine();
  62506. if (!this._texture) {
  62507. return;
  62508. }
  62509. // Bind
  62510. if (this._postProcessManager) {
  62511. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  62512. }
  62513. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  62514. if (this._texture) {
  62515. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  62516. }
  62517. }
  62518. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  62519. // Clear
  62520. if (this.onClearObservable.hasObservers()) {
  62521. this.onClearObservable.notifyObservers(engine);
  62522. }
  62523. else {
  62524. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  62525. }
  62526. if (!this._doNotChangeAspectRatio) {
  62527. scene.updateTransformMatrix(true);
  62528. }
  62529. // Render
  62530. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  62531. if (this._postProcessManager) {
  62532. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  62533. }
  62534. else if (useCameraPostProcess) {
  62535. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  62536. }
  62537. if (!this._doNotChangeAspectRatio) {
  62538. scene.updateTransformMatrix(true);
  62539. }
  62540. // Dump ?
  62541. if (dumpForDebug) {
  62542. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  62543. }
  62544. // Unbind
  62545. if (!this.isCube || faceIndex === 5) {
  62546. if (this.isCube) {
  62547. if (faceIndex === 5) {
  62548. engine.generateMipMapsForCubemap(this._texture);
  62549. }
  62550. }
  62551. this.unbindFrameBuffer(engine, faceIndex);
  62552. }
  62553. else {
  62554. this.onAfterRenderObservable.notifyObservers(faceIndex);
  62555. }
  62556. };
  62557. /**
  62558. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  62559. * This allowed control for front to back rendering or reversly depending of the special needs.
  62560. *
  62561. * @param renderingGroupId The rendering group id corresponding to its index
  62562. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  62563. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  62564. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  62565. */
  62566. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  62567. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  62568. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  62569. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  62570. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  62571. };
  62572. /**
  62573. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  62574. *
  62575. * @param renderingGroupId The rendering group id corresponding to its index
  62576. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  62577. */
  62578. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  62579. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  62580. };
  62581. RenderTargetTexture.prototype.clone = function () {
  62582. var textureSize = this.getSize();
  62583. 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);
  62584. // Base texture
  62585. newTexture.hasAlpha = this.hasAlpha;
  62586. newTexture.level = this.level;
  62587. // RenderTarget Texture
  62588. newTexture.coordinatesMode = this.coordinatesMode;
  62589. if (this.renderList) {
  62590. newTexture.renderList = this.renderList.slice(0);
  62591. }
  62592. return newTexture;
  62593. };
  62594. RenderTargetTexture.prototype.serialize = function () {
  62595. if (!this.name) {
  62596. return null;
  62597. }
  62598. var serializationObject = _super.prototype.serialize.call(this);
  62599. serializationObject.renderTargetSize = this.getRenderSize();
  62600. serializationObject.renderList = [];
  62601. if (this.renderList) {
  62602. for (var index = 0; index < this.renderList.length; index++) {
  62603. serializationObject.renderList.push(this.renderList[index].id);
  62604. }
  62605. }
  62606. return serializationObject;
  62607. };
  62608. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  62609. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  62610. var objBuffer = this.getInternalTexture();
  62611. var scene = this.getScene();
  62612. if (objBuffer && scene) {
  62613. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  62614. }
  62615. };
  62616. RenderTargetTexture.prototype.dispose = function () {
  62617. if (this._postProcessManager) {
  62618. this._postProcessManager.dispose();
  62619. this._postProcessManager = null;
  62620. }
  62621. this.clearPostProcesses(true);
  62622. if (this._resizeObserver) {
  62623. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  62624. this._resizeObserver = null;
  62625. }
  62626. this.renderList = null;
  62627. // Remove from custom render targets
  62628. var scene = this.getScene();
  62629. if (!scene) {
  62630. return;
  62631. }
  62632. var index = scene.customRenderTargets.indexOf(this);
  62633. if (index >= 0) {
  62634. scene.customRenderTargets.splice(index, 1);
  62635. }
  62636. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  62637. var camera = _a[_i];
  62638. index = camera.customRenderTargets.indexOf(this);
  62639. if (index >= 0) {
  62640. camera.customRenderTargets.splice(index, 1);
  62641. }
  62642. }
  62643. _super.prototype.dispose.call(this);
  62644. };
  62645. RenderTargetTexture.prototype._rebuild = function () {
  62646. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  62647. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  62648. }
  62649. if (this._postProcessManager) {
  62650. this._postProcessManager._rebuild();
  62651. }
  62652. };
  62653. /**
  62654. * Clear the info related to rendering groups preventing retention point in material dispose.
  62655. */
  62656. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  62657. if (this._renderingManager) {
  62658. this._renderingManager.freeRenderingGroups();
  62659. }
  62660. };
  62661. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  62662. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  62663. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  62664. return RenderTargetTexture;
  62665. }(BABYLON.Texture));
  62666. BABYLON.RenderTargetTexture = RenderTargetTexture;
  62667. })(BABYLON || (BABYLON = {}));
  62668. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  62669. "use strict";
  62670. var BABYLON;
  62671. (function (BABYLON) {
  62672. ;
  62673. var MultiRenderTarget = /** @class */ (function (_super) {
  62674. __extends(MultiRenderTarget, _super);
  62675. function MultiRenderTarget(name, size, count, scene, options) {
  62676. var _this = this;
  62677. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  62678. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  62679. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  62680. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  62681. _this._engine = scene.getEngine();
  62682. if (!_this.isSupported) {
  62683. _this.dispose();
  62684. return;
  62685. }
  62686. var types = [];
  62687. var samplingModes = [];
  62688. for (var i = 0; i < count; i++) {
  62689. if (options && options.types && options.types[i] !== undefined) {
  62690. types.push(options.types[i]);
  62691. }
  62692. else {
  62693. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62694. }
  62695. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  62696. samplingModes.push(options.samplingModes[i]);
  62697. }
  62698. else {
  62699. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62700. }
  62701. }
  62702. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  62703. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  62704. _this._size = size;
  62705. _this._multiRenderTargetOptions = {
  62706. samplingModes: samplingModes,
  62707. generateMipMaps: generateMipMaps,
  62708. generateDepthBuffer: generateDepthBuffer,
  62709. generateStencilBuffer: generateStencilBuffer,
  62710. generateDepthTexture: generateDepthTexture,
  62711. types: types,
  62712. textureCount: count
  62713. };
  62714. _this._createInternalTextures();
  62715. _this._createTextures();
  62716. return _this;
  62717. }
  62718. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  62719. get: function () {
  62720. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  62721. },
  62722. enumerable: true,
  62723. configurable: true
  62724. });
  62725. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  62726. get: function () {
  62727. return this._textures;
  62728. },
  62729. enumerable: true,
  62730. configurable: true
  62731. });
  62732. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  62733. get: function () {
  62734. return this._textures[this._textures.length - 1];
  62735. },
  62736. enumerable: true,
  62737. configurable: true
  62738. });
  62739. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  62740. set: function (wrap) {
  62741. if (this._textures) {
  62742. for (var i = 0; i < this._textures.length; i++) {
  62743. this._textures[i].wrapU = wrap;
  62744. }
  62745. }
  62746. },
  62747. enumerable: true,
  62748. configurable: true
  62749. });
  62750. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  62751. set: function (wrap) {
  62752. if (this._textures) {
  62753. for (var i = 0; i < this._textures.length; i++) {
  62754. this._textures[i].wrapV = wrap;
  62755. }
  62756. }
  62757. },
  62758. enumerable: true,
  62759. configurable: true
  62760. });
  62761. MultiRenderTarget.prototype._rebuild = function () {
  62762. this.releaseInternalTextures();
  62763. this._createInternalTextures();
  62764. for (var i = 0; i < this._internalTextures.length; i++) {
  62765. var texture = this._textures[i];
  62766. texture._texture = this._internalTextures[i];
  62767. }
  62768. // Keeps references to frame buffer and stencil/depth buffer
  62769. this._texture = this._internalTextures[0];
  62770. };
  62771. MultiRenderTarget.prototype._createInternalTextures = function () {
  62772. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  62773. };
  62774. MultiRenderTarget.prototype._createTextures = function () {
  62775. this._textures = [];
  62776. for (var i = 0; i < this._internalTextures.length; i++) {
  62777. var texture = new BABYLON.Texture(null, this.getScene());
  62778. texture._texture = this._internalTextures[i];
  62779. this._textures.push(texture);
  62780. }
  62781. // Keeps references to frame buffer and stencil/depth buffer
  62782. this._texture = this._internalTextures[0];
  62783. };
  62784. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  62785. get: function () {
  62786. return this._samples;
  62787. },
  62788. set: function (value) {
  62789. if (this._samples === value) {
  62790. return;
  62791. }
  62792. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  62793. },
  62794. enumerable: true,
  62795. configurable: true
  62796. });
  62797. MultiRenderTarget.prototype.resize = function (size) {
  62798. this.releaseInternalTextures();
  62799. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  62800. this._createInternalTextures();
  62801. };
  62802. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  62803. var _this = this;
  62804. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  62805. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  62806. });
  62807. };
  62808. MultiRenderTarget.prototype.dispose = function () {
  62809. this.releaseInternalTextures();
  62810. _super.prototype.dispose.call(this);
  62811. };
  62812. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  62813. if (!this._internalTextures) {
  62814. return;
  62815. }
  62816. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  62817. if (this._internalTextures[i] !== undefined) {
  62818. this._internalTextures[i].dispose();
  62819. this._internalTextures.splice(i, 1);
  62820. }
  62821. }
  62822. };
  62823. return MultiRenderTarget;
  62824. }(BABYLON.RenderTargetTexture));
  62825. BABYLON.MultiRenderTarget = MultiRenderTarget;
  62826. })(BABYLON || (BABYLON = {}));
  62827. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  62828. "use strict";
  62829. var BABYLON;
  62830. (function (BABYLON) {
  62831. var MirrorTexture = /** @class */ (function (_super) {
  62832. __extends(MirrorTexture, _super);
  62833. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  62834. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62835. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62836. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62837. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  62838. _this.scene = scene;
  62839. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  62840. _this._transformMatrix = BABYLON.Matrix.Zero();
  62841. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  62842. _this._adaptiveBlurKernel = 0;
  62843. _this._blurKernelX = 0;
  62844. _this._blurKernelY = 0;
  62845. _this._blurRatio = 1.0;
  62846. _this.ignoreCameraViewport = true;
  62847. _this._updateGammaSpace();
  62848. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(_this._updateGammaSpace);
  62849. _this.onBeforeRenderObservable.add(function () {
  62850. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  62851. _this._savedViewMatrix = scene.getViewMatrix();
  62852. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  62853. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  62854. scene.clipPlane = _this.mirrorPlane;
  62855. scene.getEngine().cullBackFaces = false;
  62856. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  62857. });
  62858. _this.onAfterRenderObservable.add(function () {
  62859. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  62860. scene.getEngine().cullBackFaces = true;
  62861. scene._mirroredCameraPosition = null;
  62862. delete scene.clipPlane;
  62863. });
  62864. return _this;
  62865. }
  62866. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  62867. get: function () {
  62868. return this._blurRatio;
  62869. },
  62870. set: function (value) {
  62871. if (this._blurRatio === value) {
  62872. return;
  62873. }
  62874. this._blurRatio = value;
  62875. this._preparePostProcesses();
  62876. },
  62877. enumerable: true,
  62878. configurable: true
  62879. });
  62880. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  62881. set: function (value) {
  62882. this._adaptiveBlurKernel = value;
  62883. this._autoComputeBlurKernel();
  62884. },
  62885. enumerable: true,
  62886. configurable: true
  62887. });
  62888. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  62889. set: function (value) {
  62890. this.blurKernelX = value;
  62891. this.blurKernelY = value;
  62892. },
  62893. enumerable: true,
  62894. configurable: true
  62895. });
  62896. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  62897. get: function () {
  62898. return this._blurKernelX;
  62899. },
  62900. set: function (value) {
  62901. if (this._blurKernelX === value) {
  62902. return;
  62903. }
  62904. this._blurKernelX = value;
  62905. this._preparePostProcesses();
  62906. },
  62907. enumerable: true,
  62908. configurable: true
  62909. });
  62910. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  62911. get: function () {
  62912. return this._blurKernelY;
  62913. },
  62914. set: function (value) {
  62915. if (this._blurKernelY === value) {
  62916. return;
  62917. }
  62918. this._blurKernelY = value;
  62919. this._preparePostProcesses();
  62920. },
  62921. enumerable: true,
  62922. configurable: true
  62923. });
  62924. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  62925. var engine = this.getScene().getEngine();
  62926. var dw = this.getRenderWidth() / engine.getRenderWidth();
  62927. var dh = this.getRenderHeight() / engine.getRenderHeight();
  62928. this.blurKernelX = this._adaptiveBlurKernel * dw;
  62929. this.blurKernelY = this._adaptiveBlurKernel * dh;
  62930. };
  62931. MirrorTexture.prototype._onRatioRescale = function () {
  62932. if (this._sizeRatio) {
  62933. this.resize(this._initialSizeParameter);
  62934. if (!this._adaptiveBlurKernel) {
  62935. this._preparePostProcesses();
  62936. }
  62937. }
  62938. if (this._adaptiveBlurKernel) {
  62939. this._autoComputeBlurKernel();
  62940. }
  62941. };
  62942. MirrorTexture.prototype._updateGammaSpace = function () {
  62943. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  62944. };
  62945. MirrorTexture.prototype._preparePostProcesses = function () {
  62946. this.clearPostProcesses(true);
  62947. if (this._blurKernelX && this._blurKernelY) {
  62948. var engine = this.getScene().getEngine();
  62949. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62950. 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);
  62951. this._blurX.autoClear = false;
  62952. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  62953. this._blurX.inputTexture = this._texture;
  62954. }
  62955. else {
  62956. this._blurX.alwaysForcePOT = true;
  62957. }
  62958. 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);
  62959. this._blurY.autoClear = false;
  62960. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  62961. this.addPostProcess(this._blurX);
  62962. this.addPostProcess(this._blurY);
  62963. }
  62964. else {
  62965. if (this._blurY) {
  62966. this.removePostProcess(this._blurY);
  62967. this._blurY.dispose();
  62968. this._blurY = null;
  62969. }
  62970. if (this._blurX) {
  62971. this.removePostProcess(this._blurX);
  62972. this._blurX.dispose();
  62973. this._blurX = null;
  62974. }
  62975. }
  62976. };
  62977. MirrorTexture.prototype.clone = function () {
  62978. var scene = this.getScene();
  62979. if (!scene) {
  62980. return this;
  62981. }
  62982. var textureSize = this.getSize();
  62983. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  62984. // Base texture
  62985. newTexture.hasAlpha = this.hasAlpha;
  62986. newTexture.level = this.level;
  62987. // Mirror Texture
  62988. newTexture.mirrorPlane = this.mirrorPlane.clone();
  62989. if (this.renderList) {
  62990. newTexture.renderList = this.renderList.slice(0);
  62991. }
  62992. return newTexture;
  62993. };
  62994. MirrorTexture.prototype.serialize = function () {
  62995. if (!this.name) {
  62996. return null;
  62997. }
  62998. var serializationObject = _super.prototype.serialize.call(this);
  62999. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  63000. return serializationObject;
  63001. };
  63002. MirrorTexture.prototype.dispose = function () {
  63003. _super.prototype.dispose.call(this);
  63004. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  63005. };
  63006. return MirrorTexture;
  63007. }(BABYLON.RenderTargetTexture));
  63008. BABYLON.MirrorTexture = MirrorTexture;
  63009. })(BABYLON || (BABYLON = {}));
  63010. //# sourceMappingURL=babylon.mirrorTexture.js.map
  63011. "use strict";
  63012. var BABYLON;
  63013. (function (BABYLON) {
  63014. /**
  63015. * Creates a refraction texture used by refraction channel of the standard material.
  63016. * @param name the texture name
  63017. * @param size size of the underlying texture
  63018. * @param scene root scene
  63019. */
  63020. var RefractionTexture = /** @class */ (function (_super) {
  63021. __extends(RefractionTexture, _super);
  63022. function RefractionTexture(name, size, scene, generateMipMaps) {
  63023. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  63024. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  63025. _this.depth = 2.0;
  63026. _this.onBeforeRenderObservable.add(function () {
  63027. scene.clipPlane = _this.refractionPlane;
  63028. });
  63029. _this.onAfterRenderObservable.add(function () {
  63030. delete scene.clipPlane;
  63031. });
  63032. return _this;
  63033. }
  63034. RefractionTexture.prototype.clone = function () {
  63035. var scene = this.getScene();
  63036. if (!scene) {
  63037. return this;
  63038. }
  63039. var textureSize = this.getSize();
  63040. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  63041. // Base texture
  63042. newTexture.hasAlpha = this.hasAlpha;
  63043. newTexture.level = this.level;
  63044. // Refraction Texture
  63045. newTexture.refractionPlane = this.refractionPlane.clone();
  63046. if (this.renderList) {
  63047. newTexture.renderList = this.renderList.slice(0);
  63048. }
  63049. newTexture.depth = this.depth;
  63050. return newTexture;
  63051. };
  63052. RefractionTexture.prototype.serialize = function () {
  63053. if (!this.name) {
  63054. return null;
  63055. }
  63056. var serializationObject = _super.prototype.serialize.call(this);
  63057. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  63058. serializationObject.depth = this.depth;
  63059. return serializationObject;
  63060. };
  63061. return RefractionTexture;
  63062. }(BABYLON.RenderTargetTexture));
  63063. BABYLON.RefractionTexture = RefractionTexture;
  63064. })(BABYLON || (BABYLON = {}));
  63065. //# sourceMappingURL=babylon.refractionTexture.js.map
  63066. "use strict";
  63067. var BABYLON;
  63068. (function (BABYLON) {
  63069. /**
  63070. * A class extending {BABYLON.Texture} allowing drawing on a texture
  63071. * @see http://doc.babylonjs.com/how_to/dynamictexture
  63072. */
  63073. var DynamicTexture = /** @class */ (function (_super) {
  63074. __extends(DynamicTexture, _super);
  63075. /**
  63076. * Creates a {BABYLON.DynamicTexture}
  63077. * @param name defines the name of the texture
  63078. * @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
  63079. * @param scene defines the scene where you want the texture
  63080. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  63081. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  63082. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  63083. */
  63084. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  63085. if (scene === void 0) { scene = null; }
  63086. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63087. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63088. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  63089. _this.name = name;
  63090. _this._engine = _this.getScene().getEngine();
  63091. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63092. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63093. _this._generateMipMaps = generateMipMaps;
  63094. if (options.getContext) {
  63095. _this._canvas = options;
  63096. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63097. }
  63098. else {
  63099. _this._canvas = document.createElement("canvas");
  63100. if (options.width) {
  63101. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63102. }
  63103. else {
  63104. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  63105. }
  63106. }
  63107. var textureSize = _this.getSize();
  63108. _this._canvas.width = textureSize.width;
  63109. _this._canvas.height = textureSize.height;
  63110. _this._context = _this._canvas.getContext("2d");
  63111. return _this;
  63112. }
  63113. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  63114. /**
  63115. * Gets the current state of canRescale
  63116. */
  63117. get: function () {
  63118. return true;
  63119. },
  63120. enumerable: true,
  63121. configurable: true
  63122. });
  63123. DynamicTexture.prototype._recreate = function (textureSize) {
  63124. this._canvas.width = textureSize.width;
  63125. this._canvas.height = textureSize.height;
  63126. this.releaseInternalTexture();
  63127. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  63128. };
  63129. /**
  63130. * Scales the texture
  63131. * @param ratio the scale factor to apply to both width and height
  63132. */
  63133. DynamicTexture.prototype.scale = function (ratio) {
  63134. var textureSize = this.getSize();
  63135. textureSize.width *= ratio;
  63136. textureSize.height *= ratio;
  63137. this._recreate(textureSize);
  63138. };
  63139. /**
  63140. * Resizes the texture
  63141. * @param width the new width
  63142. * @param height the new height
  63143. */
  63144. DynamicTexture.prototype.scaleTo = function (width, height) {
  63145. var textureSize = this.getSize();
  63146. textureSize.width = width;
  63147. textureSize.height = height;
  63148. this._recreate(textureSize);
  63149. };
  63150. /**
  63151. * Gets the context of the canvas used by the texture
  63152. * @returns the canvas context of the dynamic texture
  63153. */
  63154. DynamicTexture.prototype.getContext = function () {
  63155. return this._context;
  63156. };
  63157. /**
  63158. * Clears the texture
  63159. */
  63160. DynamicTexture.prototype.clear = function () {
  63161. var size = this.getSize();
  63162. this._context.fillRect(0, 0, size.width, size.height);
  63163. };
  63164. /**
  63165. * Updates the texture
  63166. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63167. */
  63168. DynamicTexture.prototype.update = function (invertY) {
  63169. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  63170. };
  63171. /**
  63172. * Draws text onto the texture
  63173. * @param text defines the text to be drawn
  63174. * @param x defines the placement of the text from the left
  63175. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  63176. * @param font defines the font to be used with font-style, font-size, font-name
  63177. * @param color defines the color used for the text
  63178. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  63179. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63180. * @param update defines whether texture is immediately update (default is true)
  63181. */
  63182. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  63183. if (update === void 0) { update = true; }
  63184. var size = this.getSize();
  63185. if (clearColor) {
  63186. this._context.fillStyle = clearColor;
  63187. this._context.fillRect(0, 0, size.width, size.height);
  63188. }
  63189. this._context.font = font;
  63190. if (x === null || x === undefined) {
  63191. var textSize = this._context.measureText(text);
  63192. x = (size.width - textSize.width) / 2;
  63193. }
  63194. if (y === null || y === undefined) {
  63195. var fontSize = parseInt((font.replace(/\D/g, '')));
  63196. ;
  63197. y = (size.height / 2) + (fontSize / 3.65);
  63198. }
  63199. this._context.fillStyle = color;
  63200. this._context.fillText(text, x, y);
  63201. if (update) {
  63202. this.update(invertY);
  63203. }
  63204. };
  63205. /**
  63206. * Clones the texture
  63207. * @returns the clone of the texture.
  63208. */
  63209. DynamicTexture.prototype.clone = function () {
  63210. var scene = this.getScene();
  63211. if (!scene) {
  63212. return this;
  63213. }
  63214. var textureSize = this.getSize();
  63215. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  63216. // Base texture
  63217. newTexture.hasAlpha = this.hasAlpha;
  63218. newTexture.level = this.level;
  63219. // Dynamic Texture
  63220. newTexture.wrapU = this.wrapU;
  63221. newTexture.wrapV = this.wrapV;
  63222. return newTexture;
  63223. };
  63224. /** @ignore */
  63225. DynamicTexture.prototype._rebuild = function () {
  63226. this.update();
  63227. };
  63228. return DynamicTexture;
  63229. }(BABYLON.Texture));
  63230. BABYLON.DynamicTexture = DynamicTexture;
  63231. })(BABYLON || (BABYLON = {}));
  63232. //# sourceMappingURL=babylon.dynamicTexture.js.map
  63233. "use strict";
  63234. var BABYLON;
  63235. (function (BABYLON) {
  63236. var VideoTexture = /** @class */ (function (_super) {
  63237. __extends(VideoTexture, _super);
  63238. /**
  63239. * Creates a video texture.
  63240. * Sample : https://doc.babylonjs.com/how_to/video_texture
  63241. * @param {string | null} name optional name, will detect from video source, if not defined
  63242. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  63243. * @param {BABYLON.Scene} scene is obviously the current scene.
  63244. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  63245. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  63246. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  63247. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  63248. */
  63249. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  63250. if (generateMipMaps === void 0) { generateMipMaps = false; }
  63251. if (invertY === void 0) { invertY = false; }
  63252. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63253. if (settings === void 0) { settings = {
  63254. autoPlay: true,
  63255. loop: true,
  63256. autoUpdateTexture: true,
  63257. }; }
  63258. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63259. _this._createInternalTexture = function () {
  63260. if (_this._texture != null) {
  63261. return;
  63262. }
  63263. if (!_this._engine.needPOTTextures ||
  63264. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  63265. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63266. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63267. }
  63268. else {
  63269. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63270. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63271. _this._generateMipMaps = false;
  63272. }
  63273. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  63274. _this._texture.isReady = true;
  63275. _this._updateInternalTexture();
  63276. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  63277. _this.onLoadObservable.notifyObservers(_this);
  63278. }
  63279. };
  63280. _this.reset = function () {
  63281. if (_this._texture == null) {
  63282. return;
  63283. }
  63284. _this._texture.dispose();
  63285. _this._texture = null;
  63286. };
  63287. _this._updateInternalTexture = function (e) {
  63288. if (_this._texture == null || !_this._texture.isReady) {
  63289. return;
  63290. }
  63291. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  63292. return;
  63293. }
  63294. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  63295. };
  63296. _this._engine = _this.getScene().getEngine();
  63297. _this._generateMipMaps = generateMipMaps;
  63298. _this._samplingMode = samplingMode;
  63299. _this.autoUpdateTexture = settings.autoUpdateTexture;
  63300. _this.name = name || _this._getName(src);
  63301. _this.video = _this._getVideo(src);
  63302. if (settings.autoPlay !== undefined) {
  63303. _this.video.autoplay = settings.autoPlay;
  63304. }
  63305. if (settings.loop !== undefined) {
  63306. _this.video.loop = settings.loop;
  63307. }
  63308. _this.video.addEventListener("canplay", _this._createInternalTexture);
  63309. _this.video.addEventListener("paused", _this._updateInternalTexture);
  63310. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  63311. _this.video.addEventListener("emptied", _this.reset);
  63312. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  63313. _this._createInternalTexture();
  63314. }
  63315. return _this;
  63316. }
  63317. VideoTexture.prototype._getName = function (src) {
  63318. if (src instanceof HTMLVideoElement) {
  63319. return src.currentSrc;
  63320. }
  63321. if (typeof src === "object") {
  63322. return src.toString();
  63323. }
  63324. return src;
  63325. };
  63326. ;
  63327. VideoTexture.prototype._getVideo = function (src) {
  63328. if (src instanceof HTMLVideoElement) {
  63329. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  63330. return src;
  63331. }
  63332. var video = document.createElement("video");
  63333. if (typeof src === "string") {
  63334. BABYLON.Tools.SetCorsBehavior(src, video);
  63335. video.src = src;
  63336. }
  63337. else {
  63338. BABYLON.Tools.SetCorsBehavior(src[0], video);
  63339. src.forEach(function (url) {
  63340. var source = document.createElement("source");
  63341. source.src = url;
  63342. video.appendChild(source);
  63343. });
  63344. }
  63345. return video;
  63346. };
  63347. ;
  63348. /**
  63349. * Internal method to initiate `update`.
  63350. */
  63351. VideoTexture.prototype._rebuild = function () {
  63352. this.update();
  63353. };
  63354. /**
  63355. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  63356. */
  63357. VideoTexture.prototype.update = function () {
  63358. if (!this.autoUpdateTexture) {
  63359. // Expecting user to call `updateTexture` manually
  63360. return;
  63361. }
  63362. this.updateTexture(true);
  63363. };
  63364. /**
  63365. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  63366. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  63367. */
  63368. VideoTexture.prototype.updateTexture = function (isVisible) {
  63369. if (!isVisible) {
  63370. return;
  63371. }
  63372. if (this.video.paused) {
  63373. return;
  63374. }
  63375. this._updateInternalTexture();
  63376. };
  63377. /**
  63378. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  63379. * @param url New url.
  63380. */
  63381. VideoTexture.prototype.updateURL = function (url) {
  63382. this.video.src = url;
  63383. };
  63384. VideoTexture.prototype.dispose = function () {
  63385. _super.prototype.dispose.call(this);
  63386. this.video.removeEventListener("canplay", this._createInternalTexture);
  63387. this.video.removeEventListener("paused", this._updateInternalTexture);
  63388. this.video.removeEventListener("seeked", this._updateInternalTexture);
  63389. this.video.removeEventListener("emptied", this.reset);
  63390. this.video.pause();
  63391. };
  63392. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  63393. var video = document.createElement("video");
  63394. var constraintsDeviceId;
  63395. if (constraints && constraints.deviceId) {
  63396. constraintsDeviceId = {
  63397. exact: constraints.deviceId,
  63398. };
  63399. }
  63400. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  63401. if (navigator.mediaDevices) {
  63402. navigator.mediaDevices.getUserMedia({ video: constraints })
  63403. .then(function (stream) {
  63404. if (video.mozSrcObject !== undefined) {
  63405. // hack for Firefox < 19
  63406. video.mozSrcObject = stream;
  63407. }
  63408. else {
  63409. video.srcObject = stream;
  63410. }
  63411. var onPlaying = function () {
  63412. if (onReady) {
  63413. onReady(new VideoTexture("video", video, scene, true, true));
  63414. }
  63415. video.removeEventListener("playing", onPlaying);
  63416. };
  63417. video.addEventListener("playing", onPlaying);
  63418. video.play();
  63419. })
  63420. .catch(function (err) {
  63421. BABYLON.Tools.Error(err.name);
  63422. });
  63423. }
  63424. else {
  63425. navigator.getUserMedia =
  63426. navigator.getUserMedia ||
  63427. navigator.webkitGetUserMedia ||
  63428. navigator.mozGetUserMedia ||
  63429. navigator.msGetUserMedia;
  63430. if (navigator.getUserMedia) {
  63431. navigator.getUserMedia({
  63432. video: {
  63433. deviceId: constraintsDeviceId,
  63434. width: {
  63435. min: (constraints && constraints.minWidth) || 256,
  63436. max: (constraints && constraints.maxWidth) || 640,
  63437. },
  63438. height: {
  63439. min: (constraints && constraints.minHeight) || 256,
  63440. max: (constraints && constraints.maxHeight) || 480,
  63441. },
  63442. },
  63443. }, function (stream) {
  63444. if (video.mozSrcObject !== undefined) {
  63445. // hack for Firefox < 19
  63446. video.mozSrcObject = stream;
  63447. }
  63448. else {
  63449. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  63450. }
  63451. video.play();
  63452. if (onReady) {
  63453. onReady(new VideoTexture("video", video, scene, true, true));
  63454. }
  63455. }, function (e) {
  63456. BABYLON.Tools.Error(e.name);
  63457. });
  63458. }
  63459. }
  63460. };
  63461. return VideoTexture;
  63462. }(BABYLON.Texture));
  63463. BABYLON.VideoTexture = VideoTexture;
  63464. })(BABYLON || (BABYLON = {}));
  63465. //# sourceMappingURL=babylon.videoTexture.js.map
  63466. "use strict";
  63467. var BABYLON;
  63468. (function (BABYLON) {
  63469. var RawTexture = /** @class */ (function (_super) {
  63470. __extends(RawTexture, _super);
  63471. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  63472. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63473. if (invertY === void 0) { invertY = false; }
  63474. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63475. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63476. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63477. _this.format = format;
  63478. _this._engine = scene.getEngine();
  63479. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  63480. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63481. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63482. return _this;
  63483. }
  63484. RawTexture.prototype.update = function (data) {
  63485. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  63486. };
  63487. // Statics
  63488. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63489. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63490. if (invertY === void 0) { invertY = false; }
  63491. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63492. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  63493. };
  63494. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63495. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63496. if (invertY === void 0) { invertY = false; }
  63497. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63498. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  63499. };
  63500. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63501. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63502. if (invertY === void 0) { invertY = false; }
  63503. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63504. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  63505. };
  63506. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  63507. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63508. if (invertY === void 0) { invertY = false; }
  63509. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63510. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63511. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  63512. };
  63513. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  63514. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63515. if (invertY === void 0) { invertY = false; }
  63516. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63517. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63518. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  63519. };
  63520. return RawTexture;
  63521. }(BABYLON.Texture));
  63522. BABYLON.RawTexture = RawTexture;
  63523. })(BABYLON || (BABYLON = {}));
  63524. //# sourceMappingURL=babylon.rawTexture.js.map
  63525. "use strict";
  63526. var BABYLON;
  63527. (function (BABYLON) {
  63528. /**
  63529. * Class used to store 3D textures containing user data
  63530. */
  63531. var RawTexture3D = /** @class */ (function (_super) {
  63532. __extends(RawTexture3D, _super);
  63533. /**
  63534. * Create a new RawTexture3D
  63535. * @param data defines the data of the texture
  63536. * @param width defines the width of the texture
  63537. * @param height defines the height of the texture
  63538. * @param depth defines the depth of the texture
  63539. * @param format defines the texture format to use
  63540. * @param scene defines the hosting scene
  63541. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  63542. * @param invertY defines if texture must be stored with Y axis inverted
  63543. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  63544. */
  63545. function RawTexture3D(data, width, height, depth,
  63546. /** Gets or sets the texture format to use*/
  63547. format, scene, generateMipMaps, invertY, samplingMode) {
  63548. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63549. if (invertY === void 0) { invertY = false; }
  63550. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63551. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63552. _this.format = format;
  63553. _this._engine = scene.getEngine();
  63554. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  63555. _this.is3D = true;
  63556. return _this;
  63557. }
  63558. /**
  63559. * Update the texture with new data
  63560. * @param data defines the data to store in the texture
  63561. */
  63562. RawTexture3D.prototype.update = function (data) {
  63563. if (!this._texture) {
  63564. return;
  63565. }
  63566. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  63567. };
  63568. return RawTexture3D;
  63569. }(BABYLON.Texture));
  63570. BABYLON.RawTexture3D = RawTexture3D;
  63571. })(BABYLON || (BABYLON = {}));
  63572. //# sourceMappingURL=babylon.rawTexture3D.js.map
  63573. "use strict";
  63574. var BABYLON;
  63575. (function (BABYLON) {
  63576. /**
  63577. * PostProcess can be used to apply a shader to a texture after it has been rendered
  63578. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  63579. */
  63580. var PostProcess = /** @class */ (function () {
  63581. /**
  63582. * Creates a new instance PostProcess
  63583. * @param name The name of the PostProcess.
  63584. * @param fragmentUrl The url of the fragment shader to be used.
  63585. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  63586. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  63587. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  63588. * @param camera The camera to apply the render pass to.
  63589. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  63590. * @param engine The engine which the post process will be applied. (default: current engine)
  63591. * @param reusable If the post process can be reused on the same frame. (default: false)
  63592. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  63593. * @param textureType Type of textures used when performing the post process. (default: 0)
  63594. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  63595. * @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
  63596. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  63597. */
  63598. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  63599. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  63600. if (defines === void 0) { defines = null; }
  63601. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63602. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  63603. if (blockCompilation === void 0) { blockCompilation = false; }
  63604. this.name = name;
  63605. /**
  63606. * Width of the texture to apply the post process on
  63607. */
  63608. this.width = -1;
  63609. /**
  63610. * Height of the texture to apply the post process on
  63611. */
  63612. this.height = -1;
  63613. /**
  63614. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  63615. */
  63616. this._outputTexture = null;
  63617. /**
  63618. * If the buffer needs to be cleared before applying the post process. (default: true)
  63619. * Should be set to false if shader will overwrite all previous pixels.
  63620. */
  63621. this.autoClear = true;
  63622. /**
  63623. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  63624. */
  63625. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  63626. /**
  63627. * Animations to be used for the post processing
  63628. */
  63629. this.animations = new Array();
  63630. /**
  63631. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  63632. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  63633. */
  63634. this.enablePixelPerfectMode = false;
  63635. /**
  63636. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  63637. */
  63638. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  63639. /**
  63640. * Force textures to be a power of two (default: false)
  63641. */
  63642. this.alwaysForcePOT = false;
  63643. /**
  63644. * Number of sample textures (default: 1)
  63645. */
  63646. this.samples = 1;
  63647. /**
  63648. * Modify the scale of the post process to be the same as the viewport (default: false)
  63649. */
  63650. this.adaptScaleToCurrentViewport = false;
  63651. this._reusable = false;
  63652. /**
  63653. * Smart array of input and output textures for the post process.
  63654. */
  63655. this._textures = new BABYLON.SmartArray(2);
  63656. /**
  63657. * The index in _textures that corresponds to the output texture.
  63658. */
  63659. this._currentRenderTextureInd = 0;
  63660. this._scaleRatio = new BABYLON.Vector2(1, 1);
  63661. this._texelSize = BABYLON.Vector2.Zero();
  63662. // Events
  63663. /**
  63664. * An event triggered when the postprocess is activated.
  63665. */
  63666. this.onActivateObservable = new BABYLON.Observable();
  63667. /**
  63668. * An event triggered when the postprocess changes its size.
  63669. */
  63670. this.onSizeChangedObservable = new BABYLON.Observable();
  63671. /**
  63672. * An event triggered when the postprocess applies its effect.
  63673. */
  63674. this.onApplyObservable = new BABYLON.Observable();
  63675. /**
  63676. * An event triggered before rendering the postprocess
  63677. */
  63678. this.onBeforeRenderObservable = new BABYLON.Observable();
  63679. /**
  63680. * An event triggered after rendering the postprocess
  63681. */
  63682. this.onAfterRenderObservable = new BABYLON.Observable();
  63683. if (camera != null) {
  63684. this._camera = camera;
  63685. this._scene = camera.getScene();
  63686. camera.attachPostProcess(this);
  63687. this._engine = this._scene.getEngine();
  63688. this._scene.postProcesses.push(this);
  63689. }
  63690. else if (engine) {
  63691. this._engine = engine;
  63692. this._engine.postProcesses.push(this);
  63693. }
  63694. this._options = options;
  63695. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  63696. this._reusable = reusable || false;
  63697. this._textureType = textureType;
  63698. this._samplers = samplers || [];
  63699. this._samplers.push("textureSampler");
  63700. this._fragmentUrl = fragmentUrl;
  63701. this._vertexUrl = vertexUrl;
  63702. this._parameters = parameters || [];
  63703. this._parameters.push("scale");
  63704. this._indexParameters = indexParameters;
  63705. if (!blockCompilation) {
  63706. this.updateEffect(defines);
  63707. }
  63708. }
  63709. Object.defineProperty(PostProcess.prototype, "onActivate", {
  63710. /**
  63711. * A function that is added to the onActivateObservable
  63712. */
  63713. set: function (callback) {
  63714. if (this._onActivateObserver) {
  63715. this.onActivateObservable.remove(this._onActivateObserver);
  63716. }
  63717. if (callback) {
  63718. this._onActivateObserver = this.onActivateObservable.add(callback);
  63719. }
  63720. },
  63721. enumerable: true,
  63722. configurable: true
  63723. });
  63724. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  63725. /**
  63726. * A function that is added to the onSizeChangedObservable
  63727. */
  63728. set: function (callback) {
  63729. if (this._onSizeChangedObserver) {
  63730. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  63731. }
  63732. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  63733. },
  63734. enumerable: true,
  63735. configurable: true
  63736. });
  63737. Object.defineProperty(PostProcess.prototype, "onApply", {
  63738. /**
  63739. * A function that is added to the onApplyObservable
  63740. */
  63741. set: function (callback) {
  63742. if (this._onApplyObserver) {
  63743. this.onApplyObservable.remove(this._onApplyObserver);
  63744. }
  63745. this._onApplyObserver = this.onApplyObservable.add(callback);
  63746. },
  63747. enumerable: true,
  63748. configurable: true
  63749. });
  63750. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  63751. /**
  63752. * A function that is added to the onBeforeRenderObservable
  63753. */
  63754. set: function (callback) {
  63755. if (this._onBeforeRenderObserver) {
  63756. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63757. }
  63758. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63759. },
  63760. enumerable: true,
  63761. configurable: true
  63762. });
  63763. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  63764. /**
  63765. * A function that is added to the onAfterRenderObservable
  63766. */
  63767. set: function (callback) {
  63768. if (this._onAfterRenderObserver) {
  63769. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63770. }
  63771. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63772. },
  63773. enumerable: true,
  63774. configurable: true
  63775. });
  63776. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  63777. /**
  63778. * 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
  63779. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  63780. */
  63781. get: function () {
  63782. return this._textures.data[this._currentRenderTextureInd];
  63783. },
  63784. set: function (value) {
  63785. this._forcedOutputTexture = value;
  63786. },
  63787. enumerable: true,
  63788. configurable: true
  63789. });
  63790. /**
  63791. * Gets the camera which post process is applied to.
  63792. * @returns The camera the post process is applied to.
  63793. */
  63794. PostProcess.prototype.getCamera = function () {
  63795. return this._camera;
  63796. };
  63797. Object.defineProperty(PostProcess.prototype, "texelSize", {
  63798. /**
  63799. * Gets the texel size of the postprocess.
  63800. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  63801. */
  63802. get: function () {
  63803. if (this._shareOutputWithPostProcess) {
  63804. return this._shareOutputWithPostProcess.texelSize;
  63805. }
  63806. if (this._forcedOutputTexture) {
  63807. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  63808. }
  63809. return this._texelSize;
  63810. },
  63811. enumerable: true,
  63812. configurable: true
  63813. });
  63814. /**
  63815. * Gets the engine which this post process belongs to.
  63816. * @returns The engine the post process was enabled with.
  63817. */
  63818. PostProcess.prototype.getEngine = function () {
  63819. return this._engine;
  63820. };
  63821. /**
  63822. * The effect that is created when initializing the post process.
  63823. * @returns The created effect corrisponding the the postprocess.
  63824. */
  63825. PostProcess.prototype.getEffect = function () {
  63826. return this._effect;
  63827. };
  63828. /**
  63829. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  63830. * @param postProcess The post process to share the output with.
  63831. * @returns This post process.
  63832. */
  63833. PostProcess.prototype.shareOutputWith = function (postProcess) {
  63834. this._disposeTextures();
  63835. this._shareOutputWithPostProcess = postProcess;
  63836. return this;
  63837. };
  63838. /**
  63839. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  63840. * This should be called if the post process that shares output with this post process is disabled/disposed.
  63841. */
  63842. PostProcess.prototype.useOwnOutput = function () {
  63843. if (this._textures.length == 0) {
  63844. this._textures = new BABYLON.SmartArray(2);
  63845. }
  63846. this._shareOutputWithPostProcess = null;
  63847. };
  63848. /**
  63849. * Updates the effect with the current post process compile time values and recompiles the shader.
  63850. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  63851. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  63852. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  63853. * @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
  63854. * @param onCompiled Called when the shader has been compiled.
  63855. * @param onError Called if there is an error when compiling a shader.
  63856. */
  63857. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  63858. if (defines === void 0) { defines = null; }
  63859. if (uniforms === void 0) { uniforms = null; }
  63860. if (samplers === void 0) { samplers = null; }
  63861. 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);
  63862. };
  63863. /**
  63864. * The post process is reusable if it can be used multiple times within one frame.
  63865. * @returns If the post process is reusable
  63866. */
  63867. PostProcess.prototype.isReusable = function () {
  63868. return this._reusable;
  63869. };
  63870. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  63871. PostProcess.prototype.markTextureDirty = function () {
  63872. this.width = -1;
  63873. };
  63874. /**
  63875. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  63876. * 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.
  63877. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  63878. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  63879. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  63880. * @returns The target texture that was bound to be written to.
  63881. */
  63882. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  63883. var _this = this;
  63884. if (sourceTexture === void 0) { sourceTexture = null; }
  63885. camera = camera || this._camera;
  63886. var scene = camera.getScene();
  63887. var engine = scene.getEngine();
  63888. var maxSize = engine.getCaps().maxTextureSize;
  63889. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  63890. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  63891. // 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
  63892. var webVRCamera = camera.parent;
  63893. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  63894. requiredWidth /= 2;
  63895. }
  63896. var desiredWidth = (this._options.width || requiredWidth);
  63897. var desiredHeight = this._options.height || requiredHeight;
  63898. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  63899. if (this.adaptScaleToCurrentViewport) {
  63900. var currentViewport = engine.currentViewport;
  63901. if (currentViewport) {
  63902. desiredWidth *= currentViewport.width;
  63903. desiredHeight *= currentViewport.height;
  63904. }
  63905. }
  63906. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  63907. if (!this._options.width) {
  63908. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  63909. }
  63910. if (!this._options.height) {
  63911. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  63912. }
  63913. }
  63914. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  63915. if (this._textures.length > 0) {
  63916. for (var i = 0; i < this._textures.length; i++) {
  63917. this._engine._releaseTexture(this._textures.data[i]);
  63918. }
  63919. this._textures.reset();
  63920. }
  63921. this.width = desiredWidth;
  63922. this.height = desiredHeight;
  63923. var textureSize = { width: this.width, height: this.height };
  63924. var textureOptions = {
  63925. generateMipMaps: false,
  63926. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  63927. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  63928. samplingMode: this.renderTargetSamplingMode,
  63929. type: this._textureType
  63930. };
  63931. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  63932. if (this._reusable) {
  63933. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  63934. }
  63935. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  63936. this.onSizeChangedObservable.notifyObservers(this);
  63937. }
  63938. this._textures.forEach(function (texture) {
  63939. if (texture.samples !== _this.samples) {
  63940. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  63941. }
  63942. });
  63943. }
  63944. var target;
  63945. if (this._shareOutputWithPostProcess) {
  63946. target = this._shareOutputWithPostProcess.inputTexture;
  63947. }
  63948. else if (this._forcedOutputTexture) {
  63949. target = this._forcedOutputTexture;
  63950. this.width = this._forcedOutputTexture.width;
  63951. this.height = this._forcedOutputTexture.height;
  63952. }
  63953. else {
  63954. target = this.inputTexture;
  63955. }
  63956. // Bind the input of this post process to be used as the output of the previous post process.
  63957. if (this.enablePixelPerfectMode) {
  63958. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  63959. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  63960. }
  63961. else {
  63962. this._scaleRatio.copyFromFloats(1, 1);
  63963. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  63964. }
  63965. this.onActivateObservable.notifyObservers(camera);
  63966. // Clear
  63967. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  63968. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  63969. }
  63970. if (this._reusable) {
  63971. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  63972. }
  63973. return target;
  63974. };
  63975. Object.defineProperty(PostProcess.prototype, "isSupported", {
  63976. /**
  63977. * If the post process is supported.
  63978. */
  63979. get: function () {
  63980. return this._effect.isSupported;
  63981. },
  63982. enumerable: true,
  63983. configurable: true
  63984. });
  63985. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  63986. /**
  63987. * The aspect ratio of the output texture.
  63988. */
  63989. get: function () {
  63990. if (this._shareOutputWithPostProcess) {
  63991. return this._shareOutputWithPostProcess.aspectRatio;
  63992. }
  63993. if (this._forcedOutputTexture) {
  63994. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  63995. }
  63996. return this.width / this.height;
  63997. },
  63998. enumerable: true,
  63999. configurable: true
  64000. });
  64001. /**
  64002. * Get a value indicating if the post-process is ready to be used
  64003. * @returns true if the post-process is ready (shader is compiled)
  64004. */
  64005. PostProcess.prototype.isReady = function () {
  64006. return this._effect && this._effect.isReady();
  64007. };
  64008. /**
  64009. * Binds all textures and uniforms to the shader, this will be run on every pass.
  64010. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  64011. */
  64012. PostProcess.prototype.apply = function () {
  64013. // Check
  64014. if (!this._effect || !this._effect.isReady())
  64015. return null;
  64016. // States
  64017. this._engine.enableEffect(this._effect);
  64018. this._engine.setState(false);
  64019. this._engine.setDepthBuffer(false);
  64020. this._engine.setDepthWrite(false);
  64021. // Alpha
  64022. this._engine.setAlphaMode(this.alphaMode);
  64023. if (this.alphaConstants) {
  64024. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  64025. }
  64026. // Bind the output texture of the preivous post process as the input to this post process.
  64027. var source;
  64028. if (this._shareOutputWithPostProcess) {
  64029. source = this._shareOutputWithPostProcess.inputTexture;
  64030. }
  64031. else if (this._forcedOutputTexture) {
  64032. source = this._forcedOutputTexture;
  64033. }
  64034. else {
  64035. source = this.inputTexture;
  64036. }
  64037. this._effect._bindTexture("textureSampler", source);
  64038. // Parameters
  64039. this._effect.setVector2("scale", this._scaleRatio);
  64040. this.onApplyObservable.notifyObservers(this._effect);
  64041. return this._effect;
  64042. };
  64043. PostProcess.prototype._disposeTextures = function () {
  64044. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  64045. return;
  64046. }
  64047. if (this._textures.length > 0) {
  64048. for (var i = 0; i < this._textures.length; i++) {
  64049. this._engine._releaseTexture(this._textures.data[i]);
  64050. }
  64051. }
  64052. this._textures.dispose();
  64053. };
  64054. /**
  64055. * Disposes the post process.
  64056. * @param camera The camera to dispose the post process on.
  64057. */
  64058. PostProcess.prototype.dispose = function (camera) {
  64059. camera = camera || this._camera;
  64060. this._disposeTextures();
  64061. if (this._scene) {
  64062. var index_1 = this._scene.postProcesses.indexOf(this);
  64063. if (index_1 !== -1) {
  64064. this._scene.postProcesses.splice(index_1, 1);
  64065. }
  64066. }
  64067. else {
  64068. var index_2 = this._engine.postProcesses.indexOf(this);
  64069. if (index_2 !== -1) {
  64070. this._engine.postProcesses.splice(index_2, 1);
  64071. }
  64072. }
  64073. if (!camera) {
  64074. return;
  64075. }
  64076. camera.detachPostProcess(this);
  64077. var index = camera._postProcesses.indexOf(this);
  64078. if (index === 0 && camera._postProcesses.length > 0) {
  64079. var firstPostProcess = this._camera._getFirstPostProcess();
  64080. if (firstPostProcess) {
  64081. firstPostProcess.markTextureDirty();
  64082. }
  64083. }
  64084. this.onActivateObservable.clear();
  64085. this.onAfterRenderObservable.clear();
  64086. this.onApplyObservable.clear();
  64087. this.onBeforeRenderObservable.clear();
  64088. this.onSizeChangedObservable.clear();
  64089. };
  64090. return PostProcess;
  64091. }());
  64092. BABYLON.PostProcess = PostProcess;
  64093. })(BABYLON || (BABYLON = {}));
  64094. //# sourceMappingURL=babylon.postProcess.js.map
  64095. "use strict";
  64096. var BABYLON;
  64097. (function (BABYLON) {
  64098. var PassPostProcess = /** @class */ (function (_super) {
  64099. __extends(PassPostProcess, _super);
  64100. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  64101. if (camera === void 0) { camera = null; }
  64102. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64103. if (blockCompilation === void 0) { blockCompilation = false; }
  64104. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  64105. }
  64106. return PassPostProcess;
  64107. }(BABYLON.PostProcess));
  64108. BABYLON.PassPostProcess = PassPostProcess;
  64109. })(BABYLON || (BABYLON = {}));
  64110. //# sourceMappingURL=babylon.passPostProcess.js.map
  64111. "use strict";
  64112. var __assign = (this && this.__assign) || Object.assign || function(t) {
  64113. for (var s, i = 1, n = arguments.length; i < n; i++) {
  64114. s = arguments[i];
  64115. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  64116. t[p] = s[p];
  64117. }
  64118. return t;
  64119. };
  64120. var BABYLON;
  64121. (function (BABYLON) {
  64122. /**
  64123. * Default implementation IShadowGenerator.
  64124. * This is the main object responsible of generating shadows in the framework.
  64125. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  64126. */
  64127. var ShadowGenerator = /** @class */ (function () {
  64128. /**
  64129. * Creates a ShadowGenerator object.
  64130. * A ShadowGenerator is the required tool to use the shadows.
  64131. * Each light casting shadows needs to use its own ShadowGenerator.
  64132. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  64133. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  64134. * @param light The light object generating the shadows.
  64135. * @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.
  64136. */
  64137. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  64138. this._bias = 0.00005;
  64139. this._normalBias = 0;
  64140. this._blurBoxOffset = 1;
  64141. this._blurScale = 2;
  64142. this._blurKernel = 1;
  64143. this._useKernelBlur = false;
  64144. this._filter = ShadowGenerator.FILTER_NONE;
  64145. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  64146. this._contactHardeningLightSizeUVRatio = 0.1;
  64147. this._darkness = 0;
  64148. this._transparencyShadow = false;
  64149. /**
  64150. * Controls the extent to which the shadows fade out at the edge of the frustum
  64151. * Used only by directionals and spots
  64152. */
  64153. this.frustumEdgeFalloff = 0;
  64154. /**
  64155. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  64156. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  64157. * It might on the other hand introduce peter panning.
  64158. */
  64159. this.forceBackFacesOnly = false;
  64160. this._lightDirection = BABYLON.Vector3.Zero();
  64161. this._viewMatrix = BABYLON.Matrix.Zero();
  64162. this._projectionMatrix = BABYLON.Matrix.Zero();
  64163. this._transformMatrix = BABYLON.Matrix.Zero();
  64164. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64165. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64166. this._currentFaceIndex = 0;
  64167. this._currentFaceIndexCache = 0;
  64168. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  64169. this._mapSize = mapSize;
  64170. this._light = light;
  64171. this._scene = light.getScene();
  64172. light._shadowGenerator = this;
  64173. // Texture type fallback from float to int if not supported.
  64174. var caps = this._scene.getEngine().getCaps();
  64175. if (!useFullFloatFirst) {
  64176. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64177. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64178. }
  64179. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64180. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64181. }
  64182. else {
  64183. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64184. }
  64185. }
  64186. else {
  64187. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64188. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64189. }
  64190. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64191. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64192. }
  64193. else {
  64194. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64195. }
  64196. }
  64197. this._initializeGenerator();
  64198. this._applyFilterValues();
  64199. }
  64200. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  64201. /**
  64202. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  64203. */
  64204. get: function () {
  64205. return this._bias;
  64206. },
  64207. /**
  64208. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  64209. */
  64210. set: function (bias) {
  64211. this._bias = bias;
  64212. },
  64213. enumerable: true,
  64214. configurable: true
  64215. });
  64216. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  64217. /**
  64218. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64219. */
  64220. get: function () {
  64221. return this._normalBias;
  64222. },
  64223. /**
  64224. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64225. */
  64226. set: function (normalBias) {
  64227. this._normalBias = normalBias;
  64228. },
  64229. enumerable: true,
  64230. configurable: true
  64231. });
  64232. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  64233. /**
  64234. * Gets the blur box offset: offset applied during the blur pass.
  64235. * Only usefull if useKernelBlur = false
  64236. */
  64237. get: function () {
  64238. return this._blurBoxOffset;
  64239. },
  64240. /**
  64241. * Sets the blur box offset: offset applied during the blur pass.
  64242. * Only usefull if useKernelBlur = false
  64243. */
  64244. set: function (value) {
  64245. if (this._blurBoxOffset === value) {
  64246. return;
  64247. }
  64248. this._blurBoxOffset = value;
  64249. this._disposeBlurPostProcesses();
  64250. },
  64251. enumerable: true,
  64252. configurable: true
  64253. });
  64254. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  64255. /**
  64256. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  64257. * 2 means half of the size.
  64258. */
  64259. get: function () {
  64260. return this._blurScale;
  64261. },
  64262. /**
  64263. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  64264. * 2 means half of the size.
  64265. */
  64266. set: function (value) {
  64267. if (this._blurScale === value) {
  64268. return;
  64269. }
  64270. this._blurScale = value;
  64271. this._disposeBlurPostProcesses();
  64272. },
  64273. enumerable: true,
  64274. configurable: true
  64275. });
  64276. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  64277. /**
  64278. * Gets the blur kernel: kernel size of the blur pass.
  64279. * Only usefull if useKernelBlur = true
  64280. */
  64281. get: function () {
  64282. return this._blurKernel;
  64283. },
  64284. /**
  64285. * Sets the blur kernel: kernel size of the blur pass.
  64286. * Only usefull if useKernelBlur = true
  64287. */
  64288. set: function (value) {
  64289. if (this._blurKernel === value) {
  64290. return;
  64291. }
  64292. this._blurKernel = value;
  64293. this._disposeBlurPostProcesses();
  64294. },
  64295. enumerable: true,
  64296. configurable: true
  64297. });
  64298. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  64299. /**
  64300. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  64301. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  64302. */
  64303. get: function () {
  64304. return this._useKernelBlur;
  64305. },
  64306. /**
  64307. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  64308. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  64309. */
  64310. set: function (value) {
  64311. if (this._useKernelBlur === value) {
  64312. return;
  64313. }
  64314. this._useKernelBlur = value;
  64315. this._disposeBlurPostProcesses();
  64316. },
  64317. enumerable: true,
  64318. configurable: true
  64319. });
  64320. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  64321. /**
  64322. * Gets the depth scale used in ESM mode.
  64323. */
  64324. get: function () {
  64325. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  64326. },
  64327. /**
  64328. * Sets the depth scale used in ESM mode.
  64329. * This can override the scale stored on the light.
  64330. */
  64331. set: function (value) {
  64332. this._depthScale = value;
  64333. },
  64334. enumerable: true,
  64335. configurable: true
  64336. });
  64337. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  64338. /**
  64339. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  64340. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  64341. */
  64342. get: function () {
  64343. return this._filter;
  64344. },
  64345. /**
  64346. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  64347. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  64348. */
  64349. set: function (value) {
  64350. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  64351. if (this._light.needCube()) {
  64352. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  64353. this.useExponentialShadowMap = true;
  64354. return;
  64355. }
  64356. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  64357. this.useCloseExponentialShadowMap = true;
  64358. return;
  64359. }
  64360. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  64361. this.usePoissonSampling = true;
  64362. return;
  64363. }
  64364. }
  64365. // Weblg1 fallback for PCF.
  64366. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  64367. if (this._scene.getEngine().webGLVersion === 1) {
  64368. this.usePoissonSampling = true;
  64369. return;
  64370. }
  64371. }
  64372. if (this._filter === value) {
  64373. return;
  64374. }
  64375. this._filter = value;
  64376. this._disposeBlurPostProcesses();
  64377. this._applyFilterValues();
  64378. this._light._markMeshesAsLightDirty();
  64379. },
  64380. enumerable: true,
  64381. configurable: true
  64382. });
  64383. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  64384. /**
  64385. * Gets if the current filter is set to Poisson Sampling.
  64386. */
  64387. get: function () {
  64388. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  64389. },
  64390. /**
  64391. * Sets the current filter to Poisson Sampling.
  64392. */
  64393. set: function (value) {
  64394. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  64395. return;
  64396. }
  64397. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  64398. },
  64399. enumerable: true,
  64400. configurable: true
  64401. });
  64402. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  64403. /**
  64404. * Gets if the current filter is set to VSM.
  64405. * DEPRECATED. Should use useExponentialShadowMap instead.
  64406. */
  64407. get: function () {
  64408. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  64409. return this.useExponentialShadowMap;
  64410. },
  64411. /**
  64412. * Sets the current filter is to VSM.
  64413. * DEPRECATED. Should use useExponentialShadowMap instead.
  64414. */
  64415. set: function (value) {
  64416. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  64417. this.useExponentialShadowMap = value;
  64418. },
  64419. enumerable: true,
  64420. configurable: true
  64421. });
  64422. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  64423. /**
  64424. * Gets if the current filter is set to blurred VSM.
  64425. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  64426. */
  64427. get: function () {
  64428. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  64429. return this.useBlurExponentialShadowMap;
  64430. },
  64431. /**
  64432. * Sets the current filter is to blurred VSM.
  64433. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  64434. */
  64435. set: function (value) {
  64436. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  64437. this.useBlurExponentialShadowMap = value;
  64438. },
  64439. enumerable: true,
  64440. configurable: true
  64441. });
  64442. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  64443. /**
  64444. * Gets if the current filter is set to ESM.
  64445. */
  64446. get: function () {
  64447. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  64448. },
  64449. /**
  64450. * Sets the current filter is to ESM.
  64451. */
  64452. set: function (value) {
  64453. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  64454. return;
  64455. }
  64456. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64457. },
  64458. enumerable: true,
  64459. configurable: true
  64460. });
  64461. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  64462. /**
  64463. * Gets if the current filter is set to filtered ESM.
  64464. */
  64465. get: function () {
  64466. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  64467. },
  64468. /**
  64469. * Gets if the current filter is set to filtered ESM.
  64470. */
  64471. set: function (value) {
  64472. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  64473. return;
  64474. }
  64475. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64476. },
  64477. enumerable: true,
  64478. configurable: true
  64479. });
  64480. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  64481. /**
  64482. * Gets if the current filter is set to "close ESM" (using the inverse of the
  64483. * exponential to prevent steep falloff artifacts).
  64484. */
  64485. get: function () {
  64486. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  64487. },
  64488. /**
  64489. * Sets the current filter to "close ESM" (using the inverse of the
  64490. * exponential to prevent steep falloff artifacts).
  64491. */
  64492. set: function (value) {
  64493. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  64494. return;
  64495. }
  64496. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64497. },
  64498. enumerable: true,
  64499. configurable: true
  64500. });
  64501. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  64502. /**
  64503. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  64504. * exponential to prevent steep falloff artifacts).
  64505. */
  64506. get: function () {
  64507. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  64508. },
  64509. /**
  64510. * Sets the current filter to filtered "close ESM" (using the inverse of the
  64511. * exponential to prevent steep falloff artifacts).
  64512. */
  64513. set: function (value) {
  64514. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  64515. return;
  64516. }
  64517. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64518. },
  64519. enumerable: true,
  64520. configurable: true
  64521. });
  64522. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  64523. /**
  64524. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  64525. */
  64526. get: function () {
  64527. return this.filter === ShadowGenerator.FILTER_PCF;
  64528. },
  64529. /**
  64530. * Sets the current filter to "PCF" (percentage closer filtering).
  64531. */
  64532. set: function (value) {
  64533. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  64534. return;
  64535. }
  64536. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  64537. },
  64538. enumerable: true,
  64539. configurable: true
  64540. });
  64541. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  64542. /**
  64543. * Gets the PCF or PCSS Quality.
  64544. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  64545. */
  64546. get: function () {
  64547. return this._filteringQuality;
  64548. },
  64549. /**
  64550. * Sets the PCF or PCSS Quality.
  64551. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  64552. */
  64553. set: function (filteringQuality) {
  64554. this._filteringQuality = filteringQuality;
  64555. },
  64556. enumerable: true,
  64557. configurable: true
  64558. });
  64559. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  64560. /**
  64561. * Gets if the current filter is set to "PCSS" (contact hardening).
  64562. */
  64563. get: function () {
  64564. return this.filter === ShadowGenerator.FILTER_PCSS;
  64565. },
  64566. /**
  64567. * Sets the current filter to "PCSS" (contact hardening).
  64568. */
  64569. set: function (value) {
  64570. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  64571. return;
  64572. }
  64573. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  64574. },
  64575. enumerable: true,
  64576. configurable: true
  64577. });
  64578. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  64579. /**
  64580. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  64581. * Using a ratio helps keeping shape stability independently of the map size.
  64582. *
  64583. * It does not account for the light projection as it was having too much
  64584. * instability during the light setup or during light position changes.
  64585. *
  64586. * Only valid if useContactHardeningShadow is true.
  64587. */
  64588. get: function () {
  64589. return this._contactHardeningLightSizeUVRatio;
  64590. },
  64591. /**
  64592. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  64593. * Using a ratio helps keeping shape stability independently of the map size.
  64594. *
  64595. * It does not account for the light projection as it was having too much
  64596. * instability during the light setup or during light position changes.
  64597. *
  64598. * Only valid if useContactHardeningShadow is true.
  64599. */
  64600. set: function (contactHardeningLightSizeUVRatio) {
  64601. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  64602. },
  64603. enumerable: true,
  64604. configurable: true
  64605. });
  64606. /**
  64607. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  64608. * 0 means strongest and 1 would means no shadow.
  64609. * @returns the darkness.
  64610. */
  64611. ShadowGenerator.prototype.getDarkness = function () {
  64612. return this._darkness;
  64613. };
  64614. /**
  64615. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  64616. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  64617. * @returns the shadow generator allowing fluent coding.
  64618. */
  64619. ShadowGenerator.prototype.setDarkness = function (darkness) {
  64620. if (darkness >= 1.0)
  64621. this._darkness = 1.0;
  64622. else if (darkness <= 0.0)
  64623. this._darkness = 0.0;
  64624. else
  64625. this._darkness = darkness;
  64626. return this;
  64627. };
  64628. /**
  64629. * Sets the ability to have transparent shadow (boolean).
  64630. * @param transparent True if transparent else False
  64631. * @returns the shadow generator allowing fluent coding
  64632. */
  64633. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  64634. this._transparencyShadow = transparent;
  64635. return this;
  64636. };
  64637. /**
  64638. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  64639. * @returns The render target texture if present otherwise, null
  64640. */
  64641. ShadowGenerator.prototype.getShadowMap = function () {
  64642. return this._shadowMap;
  64643. };
  64644. /**
  64645. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  64646. * @returns The render target texture if the shadow map is present otherwise, null
  64647. */
  64648. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  64649. if (this._shadowMap2) {
  64650. return this._shadowMap2;
  64651. }
  64652. return this._shadowMap;
  64653. };
  64654. /**
  64655. * Helper function to add a mesh and its descendants to the list of shadow casters.
  64656. * @param mesh Mesh to add
  64657. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  64658. * @returns the Shadow Generator itself
  64659. */
  64660. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  64661. if (includeDescendants === void 0) { includeDescendants = true; }
  64662. if (!this._shadowMap) {
  64663. return this;
  64664. }
  64665. if (!this._shadowMap.renderList) {
  64666. this._shadowMap.renderList = [];
  64667. }
  64668. this._shadowMap.renderList.push(mesh);
  64669. if (includeDescendants) {
  64670. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  64671. }
  64672. return this;
  64673. var _a;
  64674. };
  64675. /**
  64676. * Helper function to remove a mesh and its descendants from the list of shadow casters
  64677. * @param mesh Mesh to remove
  64678. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  64679. * @returns the Shadow Generator itself
  64680. */
  64681. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  64682. if (includeDescendants === void 0) { includeDescendants = true; }
  64683. if (!this._shadowMap || !this._shadowMap.renderList) {
  64684. return this;
  64685. }
  64686. var index = this._shadowMap.renderList.indexOf(mesh);
  64687. if (index !== -1) {
  64688. this._shadowMap.renderList.splice(index, 1);
  64689. }
  64690. if (includeDescendants) {
  64691. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  64692. var child = _a[_i];
  64693. this.removeShadowCaster(child);
  64694. }
  64695. }
  64696. return this;
  64697. };
  64698. /**
  64699. * Returns the associated light object.
  64700. * @returns the light generating the shadow
  64701. */
  64702. ShadowGenerator.prototype.getLight = function () {
  64703. return this._light;
  64704. };
  64705. ShadowGenerator.prototype._initializeGenerator = function () {
  64706. this._light._markMeshesAsLightDirty();
  64707. this._initializeShadowMap();
  64708. };
  64709. ShadowGenerator.prototype._initializeShadowMap = function () {
  64710. var _this = this;
  64711. // Render target
  64712. var engine = this._scene.getEngine();
  64713. if (engine.webGLVersion > 1) {
  64714. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  64715. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  64716. }
  64717. else {
  64718. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  64719. }
  64720. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64721. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64722. this._shadowMap.anisotropicFilteringLevel = 1;
  64723. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64724. this._shadowMap.renderParticles = false;
  64725. this._shadowMap.ignoreCameraViewport = true;
  64726. // Record Face Index before render.
  64727. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  64728. _this._currentFaceIndex = faceIndex;
  64729. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  64730. engine.setColorWrite(false);
  64731. }
  64732. });
  64733. // Custom render function.
  64734. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  64735. // Blur if required afer render.
  64736. this._shadowMap.onAfterUnbindObservable.add(function () {
  64737. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  64738. engine.setColorWrite(true);
  64739. }
  64740. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  64741. return;
  64742. }
  64743. var shadowMap = _this.getShadowMapForRendering();
  64744. if (shadowMap) {
  64745. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  64746. }
  64747. });
  64748. // Clear according to the chosen filter.
  64749. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  64750. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  64751. this._shadowMap.onClearObservable.add(function (engine) {
  64752. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  64753. engine.clear(clearOne, false, true, false);
  64754. }
  64755. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  64756. engine.clear(clearZero, true, true, false);
  64757. }
  64758. else {
  64759. engine.clear(clearOne, true, true, false);
  64760. }
  64761. });
  64762. };
  64763. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  64764. var _this = this;
  64765. var engine = this._scene.getEngine();
  64766. var targetSize = this._mapSize / this.blurScale;
  64767. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  64768. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  64769. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64770. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64771. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64772. }
  64773. if (this.useKernelBlur) {
  64774. 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);
  64775. this._kernelBlurXPostprocess.width = targetSize;
  64776. this._kernelBlurXPostprocess.height = targetSize;
  64777. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  64778. effect.setTexture("textureSampler", _this._shadowMap);
  64779. });
  64780. 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);
  64781. this._kernelBlurXPostprocess.autoClear = false;
  64782. this._kernelBlurYPostprocess.autoClear = false;
  64783. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64784. this._kernelBlurXPostprocess.packedFloat = true;
  64785. this._kernelBlurYPostprocess.packedFloat = true;
  64786. }
  64787. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  64788. }
  64789. else {
  64790. 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);
  64791. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  64792. effect.setFloat2("screenSize", targetSize, targetSize);
  64793. effect.setTexture("textureSampler", _this._shadowMap);
  64794. });
  64795. this._boxBlurPostprocess.autoClear = false;
  64796. this._blurPostProcesses = [this._boxBlurPostprocess];
  64797. }
  64798. };
  64799. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64800. var index;
  64801. var engine = this._scene.getEngine();
  64802. if (depthOnlySubMeshes.length) {
  64803. engine.setColorWrite(false);
  64804. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64805. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  64806. }
  64807. engine.setColorWrite(true);
  64808. }
  64809. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64810. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  64811. }
  64812. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64813. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  64814. }
  64815. if (this._transparencyShadow) {
  64816. for (index = 0; index < transparentSubMeshes.length; index++) {
  64817. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  64818. }
  64819. }
  64820. };
  64821. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  64822. var _this = this;
  64823. var mesh = subMesh.getRenderingMesh();
  64824. var scene = this._scene;
  64825. var engine = scene.getEngine();
  64826. var material = subMesh.getMaterial();
  64827. if (!material) {
  64828. return;
  64829. }
  64830. // Culling
  64831. engine.setState(material.backFaceCulling);
  64832. // Managing instances
  64833. var batch = mesh._getInstancesRenderList(subMesh._id);
  64834. if (batch.mustReturn) {
  64835. return;
  64836. }
  64837. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  64838. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  64839. engine.enableEffect(this._effect);
  64840. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  64841. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  64842. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  64843. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  64844. this._effect.setVector3("lightData", this._cachedDirection);
  64845. }
  64846. else {
  64847. this._effect.setVector3("lightData", this._cachedPosition);
  64848. }
  64849. if (scene.activeCamera) {
  64850. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  64851. }
  64852. // Alpha test
  64853. if (material && material.needAlphaTesting()) {
  64854. var alphaTexture = material.getAlphaTestTexture();
  64855. if (alphaTexture) {
  64856. this._effect.setTexture("diffuseSampler", alphaTexture);
  64857. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  64858. }
  64859. }
  64860. // Bones
  64861. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64862. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  64863. }
  64864. // Morph targets
  64865. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  64866. if (this.forceBackFacesOnly) {
  64867. engine.setState(true, 0, false, true);
  64868. }
  64869. // Draw
  64870. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64871. if (this.forceBackFacesOnly) {
  64872. engine.setState(true, 0, false, false);
  64873. }
  64874. }
  64875. else {
  64876. // Need to reset refresh rate of the shadowMap
  64877. if (this._shadowMap) {
  64878. this._shadowMap.resetRefreshCounter();
  64879. }
  64880. }
  64881. };
  64882. ShadowGenerator.prototype._applyFilterValues = function () {
  64883. if (!this._shadowMap) {
  64884. return;
  64885. }
  64886. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  64887. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  64888. }
  64889. else {
  64890. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64891. }
  64892. };
  64893. /**
  64894. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  64895. * @param onCompiled Callback triggered at the and of the effects compilation
  64896. * @param options Sets of optional options forcing the compilation with different modes
  64897. */
  64898. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  64899. var _this = this;
  64900. var localOptions = __assign({ useInstances: false }, options);
  64901. var shadowMap = this.getShadowMap();
  64902. if (!shadowMap) {
  64903. if (onCompiled) {
  64904. onCompiled(this);
  64905. }
  64906. return;
  64907. }
  64908. var renderList = shadowMap.renderList;
  64909. if (!renderList) {
  64910. if (onCompiled) {
  64911. onCompiled(this);
  64912. }
  64913. return;
  64914. }
  64915. var subMeshes = new Array();
  64916. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  64917. var mesh = renderList_1[_i];
  64918. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  64919. }
  64920. if (subMeshes.length === 0) {
  64921. if (onCompiled) {
  64922. onCompiled(this);
  64923. }
  64924. return;
  64925. }
  64926. var currentIndex = 0;
  64927. var checkReady = function () {
  64928. if (!_this._scene || !_this._scene.getEngine()) {
  64929. return;
  64930. }
  64931. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  64932. currentIndex++;
  64933. if (currentIndex >= subMeshes.length) {
  64934. if (onCompiled) {
  64935. onCompiled(_this);
  64936. }
  64937. return;
  64938. }
  64939. }
  64940. setTimeout(checkReady, 16);
  64941. };
  64942. checkReady();
  64943. };
  64944. /**
  64945. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  64946. * @param options Sets of optional options forcing the compilation with different modes
  64947. * @returns A promise that resolves when the compilation completes
  64948. */
  64949. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  64950. var _this = this;
  64951. return new Promise(function (resolve) {
  64952. _this.forceCompilation(function () {
  64953. resolve();
  64954. }, options);
  64955. });
  64956. };
  64957. /**
  64958. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  64959. * @param subMesh The submesh we want to render in the shadow map
  64960. * @param useInstances Defines wether will draw in the map using instances
  64961. * @returns true if ready otherwise, false
  64962. */
  64963. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  64964. var defines = [];
  64965. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64966. defines.push("#define FLOAT");
  64967. }
  64968. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  64969. defines.push("#define ESM");
  64970. }
  64971. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  64972. defines.push("#define DEPTHTEXTURE");
  64973. }
  64974. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64975. var mesh = subMesh.getMesh();
  64976. var material = subMesh.getMaterial();
  64977. // Normal bias.
  64978. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  64979. attribs.push(BABYLON.VertexBuffer.NormalKind);
  64980. defines.push("#define NORMAL");
  64981. if (mesh.nonUniformScaling) {
  64982. defines.push("#define NONUNIFORMSCALING");
  64983. }
  64984. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  64985. defines.push("#define DIRECTIONINLIGHTDATA");
  64986. }
  64987. }
  64988. // Alpha test
  64989. if (material && material.needAlphaTesting()) {
  64990. var alphaTexture = material.getAlphaTestTexture();
  64991. if (alphaTexture) {
  64992. defines.push("#define ALPHATEST");
  64993. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64994. attribs.push(BABYLON.VertexBuffer.UVKind);
  64995. defines.push("#define UV1");
  64996. }
  64997. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64998. if (alphaTexture.coordinatesIndex === 1) {
  64999. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65000. defines.push("#define UV2");
  65001. }
  65002. }
  65003. }
  65004. }
  65005. // Bones
  65006. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65007. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65008. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65009. if (mesh.numBoneInfluencers > 4) {
  65010. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65011. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65012. }
  65013. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65014. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  65015. }
  65016. else {
  65017. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65018. }
  65019. // Morph targets
  65020. var manager = mesh.morphTargetManager;
  65021. var morphInfluencers = 0;
  65022. if (manager) {
  65023. if (manager.numInfluencers > 0) {
  65024. defines.push("#define MORPHTARGETS");
  65025. morphInfluencers = manager.numInfluencers;
  65026. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  65027. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  65028. }
  65029. }
  65030. // Instances
  65031. if (useInstances) {
  65032. defines.push("#define INSTANCES");
  65033. attribs.push("world0");
  65034. attribs.push("world1");
  65035. attribs.push("world2");
  65036. attribs.push("world3");
  65037. }
  65038. // Get correct effect
  65039. var join = defines.join("\n");
  65040. if (this._cachedDefines !== join) {
  65041. this._cachedDefines = join;
  65042. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  65043. }
  65044. if (!this._effect.isReady()) {
  65045. return false;
  65046. }
  65047. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65048. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  65049. this._initializeBlurRTTAndPostProcesses();
  65050. }
  65051. }
  65052. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  65053. return false;
  65054. }
  65055. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  65056. return false;
  65057. }
  65058. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  65059. return false;
  65060. }
  65061. return true;
  65062. };
  65063. /**
  65064. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  65065. * @param defines Defines of the material we want to update
  65066. * @param lightIndex Index of the light in the enabled light list of the material
  65067. */
  65068. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  65069. var scene = this._scene;
  65070. var light = this._light;
  65071. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65072. return;
  65073. }
  65074. defines["SHADOW" + lightIndex] = true;
  65075. if (this.useContactHardeningShadow) {
  65076. defines["SHADOWPCSS" + lightIndex] = true;
  65077. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65078. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65079. }
  65080. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65081. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65082. }
  65083. // else default to high.
  65084. }
  65085. if (this.usePercentageCloserFiltering) {
  65086. defines["SHADOWPCF" + lightIndex] = true;
  65087. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65088. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65089. }
  65090. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65091. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65092. }
  65093. // else default to high.
  65094. }
  65095. else if (this.usePoissonSampling) {
  65096. defines["SHADOWPOISSON" + lightIndex] = true;
  65097. }
  65098. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65099. defines["SHADOWESM" + lightIndex] = true;
  65100. }
  65101. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65102. defines["SHADOWCLOSEESM" + lightIndex] = true;
  65103. }
  65104. if (light.needCube()) {
  65105. defines["SHADOWCUBE" + lightIndex] = true;
  65106. }
  65107. };
  65108. /**
  65109. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  65110. * defined in the generator but impacting the effect).
  65111. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  65112. * @param effect The effect we are binfing the information for
  65113. */
  65114. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  65115. var light = this._light;
  65116. var scene = this._scene;
  65117. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65118. return;
  65119. }
  65120. var camera = scene.activeCamera;
  65121. if (!camera) {
  65122. return;
  65123. }
  65124. var shadowMap = this.getShadowMap();
  65125. if (!shadowMap) {
  65126. return;
  65127. }
  65128. if (!light.needCube()) {
  65129. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  65130. }
  65131. // Only PCF uses depth stencil texture.
  65132. if (this._filter === ShadowGenerator.FILTER_PCF) {
  65133. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65134. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65135. }
  65136. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  65137. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65138. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  65139. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65140. }
  65141. else {
  65142. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65143. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  65144. }
  65145. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  65146. };
  65147. /**
  65148. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  65149. * (eq to shadow prjection matrix * light transform matrix)
  65150. * @returns The transform matrix used to create the shadow map
  65151. */
  65152. ShadowGenerator.prototype.getTransformMatrix = function () {
  65153. var scene = this._scene;
  65154. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  65155. return this._transformMatrix;
  65156. }
  65157. this._currentRenderID = scene.getRenderId();
  65158. this._currentFaceIndexCache = this._currentFaceIndex;
  65159. var lightPosition = this._light.position;
  65160. if (this._light.computeTransformedInformation()) {
  65161. lightPosition = this._light.transformedPosition;
  65162. }
  65163. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  65164. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  65165. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  65166. }
  65167. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  65168. this._cachedPosition.copyFrom(lightPosition);
  65169. this._cachedDirection.copyFrom(this._lightDirection);
  65170. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  65171. var shadowMap = this.getShadowMap();
  65172. if (shadowMap) {
  65173. var renderList = shadowMap.renderList;
  65174. if (renderList) {
  65175. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  65176. }
  65177. }
  65178. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  65179. }
  65180. return this._transformMatrix;
  65181. };
  65182. /**
  65183. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  65184. * Cube and 2D textures for instance.
  65185. */
  65186. ShadowGenerator.prototype.recreateShadowMap = function () {
  65187. var shadowMap = this._shadowMap;
  65188. if (!shadowMap) {
  65189. return;
  65190. }
  65191. // Track render list.
  65192. var renderList = shadowMap.renderList;
  65193. // Clean up existing data.
  65194. this._disposeRTTandPostProcesses();
  65195. // Reinitializes.
  65196. this._initializeGenerator();
  65197. // Reaffect the filter to ensure a correct fallback if necessary.
  65198. this.filter = this.filter;
  65199. // Reaffect the filter.
  65200. this._applyFilterValues();
  65201. // Reaffect Render List.
  65202. this._shadowMap.renderList = renderList;
  65203. };
  65204. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  65205. if (this._shadowMap2) {
  65206. this._shadowMap2.dispose();
  65207. this._shadowMap2 = null;
  65208. }
  65209. if (this._boxBlurPostprocess) {
  65210. this._boxBlurPostprocess.dispose();
  65211. this._boxBlurPostprocess = null;
  65212. }
  65213. if (this._kernelBlurXPostprocess) {
  65214. this._kernelBlurXPostprocess.dispose();
  65215. this._kernelBlurXPostprocess = null;
  65216. }
  65217. if (this._kernelBlurYPostprocess) {
  65218. this._kernelBlurYPostprocess.dispose();
  65219. this._kernelBlurYPostprocess = null;
  65220. }
  65221. this._blurPostProcesses = [];
  65222. };
  65223. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  65224. if (this._shadowMap) {
  65225. this._shadowMap.dispose();
  65226. this._shadowMap = null;
  65227. }
  65228. this._disposeBlurPostProcesses();
  65229. };
  65230. /**
  65231. * Disposes the ShadowGenerator.
  65232. * Returns nothing.
  65233. */
  65234. ShadowGenerator.prototype.dispose = function () {
  65235. this._disposeRTTandPostProcesses();
  65236. if (this._light) {
  65237. this._light._shadowGenerator = null;
  65238. this._light._markMeshesAsLightDirty();
  65239. }
  65240. };
  65241. /**
  65242. * Serializes the shadow generator setup to a json object.
  65243. * @returns The serialized JSON object
  65244. */
  65245. ShadowGenerator.prototype.serialize = function () {
  65246. var serializationObject = {};
  65247. var shadowMap = this.getShadowMap();
  65248. if (!shadowMap) {
  65249. return serializationObject;
  65250. }
  65251. serializationObject.lightId = this._light.id;
  65252. serializationObject.mapSize = shadowMap.getRenderSize();
  65253. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  65254. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  65255. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65256. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65257. serializationObject.usePoissonSampling = this.usePoissonSampling;
  65258. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  65259. serializationObject.depthScale = this.depthScale;
  65260. serializationObject.darkness = this.getDarkness();
  65261. serializationObject.blurBoxOffset = this.blurBoxOffset;
  65262. serializationObject.blurKernel = this.blurKernel;
  65263. serializationObject.blurScale = this.blurScale;
  65264. serializationObject.useKernelBlur = this.useKernelBlur;
  65265. serializationObject.transparencyShadow = this._transparencyShadow;
  65266. serializationObject.bias = this.bias;
  65267. serializationObject.normalBias = this.normalBias;
  65268. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  65269. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  65270. serializationObject.filteringQuality = this.filteringQuality;
  65271. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  65272. serializationObject.renderList = [];
  65273. if (shadowMap.renderList) {
  65274. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  65275. var mesh = shadowMap.renderList[meshIndex];
  65276. serializationObject.renderList.push(mesh.id);
  65277. }
  65278. }
  65279. return serializationObject;
  65280. };
  65281. /**
  65282. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  65283. * @param parsedShadowGenerator The JSON object to parse
  65284. * @param scene The scene to create the shadow map for
  65285. * @returns The parsed shadow generator
  65286. */
  65287. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  65288. //casting to point light, as light is missing the position attr and typescript complains.
  65289. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  65290. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  65291. var shadowMap = shadowGenerator.getShadowMap();
  65292. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  65293. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  65294. meshes.forEach(function (mesh) {
  65295. if (!shadowMap) {
  65296. return;
  65297. }
  65298. if (!shadowMap.renderList) {
  65299. shadowMap.renderList = [];
  65300. }
  65301. shadowMap.renderList.push(mesh);
  65302. });
  65303. }
  65304. if (parsedShadowGenerator.usePoissonSampling) {
  65305. shadowGenerator.usePoissonSampling = true;
  65306. }
  65307. else if (parsedShadowGenerator.useExponentialShadowMap) {
  65308. shadowGenerator.useExponentialShadowMap = true;
  65309. }
  65310. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  65311. shadowGenerator.useBlurExponentialShadowMap = true;
  65312. }
  65313. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  65314. shadowGenerator.useCloseExponentialShadowMap = true;
  65315. }
  65316. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  65317. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  65318. }
  65319. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  65320. shadowGenerator.usePercentageCloserFiltering = true;
  65321. }
  65322. else if (parsedShadowGenerator.useContactHardeningShadow) {
  65323. shadowGenerator.useContactHardeningShadow = true;
  65324. }
  65325. if (parsedShadowGenerator.filteringQuality) {
  65326. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  65327. }
  65328. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  65329. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  65330. }
  65331. else if (parsedShadowGenerator.useVarianceShadowMap) {
  65332. shadowGenerator.useExponentialShadowMap = true;
  65333. }
  65334. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  65335. shadowGenerator.useBlurExponentialShadowMap = true;
  65336. }
  65337. if (parsedShadowGenerator.depthScale) {
  65338. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  65339. }
  65340. if (parsedShadowGenerator.blurScale) {
  65341. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  65342. }
  65343. if (parsedShadowGenerator.blurBoxOffset) {
  65344. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  65345. }
  65346. if (parsedShadowGenerator.useKernelBlur) {
  65347. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  65348. }
  65349. if (parsedShadowGenerator.blurKernel) {
  65350. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  65351. }
  65352. if (parsedShadowGenerator.bias !== undefined) {
  65353. shadowGenerator.bias = parsedShadowGenerator.bias;
  65354. }
  65355. if (parsedShadowGenerator.normalBias !== undefined) {
  65356. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  65357. }
  65358. if (parsedShadowGenerator.darkness) {
  65359. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  65360. }
  65361. if (parsedShadowGenerator.transparencyShadow) {
  65362. shadowGenerator.setTransparencyShadow(true);
  65363. }
  65364. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  65365. return shadowGenerator;
  65366. };
  65367. /**
  65368. * Shadow generator mode None: no filtering applied.
  65369. */
  65370. ShadowGenerator.FILTER_NONE = 0;
  65371. /**
  65372. * Shadow generator mode ESM: Exponential Shadow Mapping.
  65373. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65374. */
  65375. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  65376. /**
  65377. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  65378. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  65379. */
  65380. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  65381. /**
  65382. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  65383. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65384. */
  65385. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  65386. /**
  65387. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  65388. * edge artifacts on steep falloff.
  65389. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65390. */
  65391. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  65392. /**
  65393. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  65394. * edge artifacts on steep falloff.
  65395. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65396. */
  65397. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  65398. /**
  65399. * Shadow generator mode PCF: Percentage Closer Filtering
  65400. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  65401. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  65402. */
  65403. ShadowGenerator.FILTER_PCF = 6;
  65404. /**
  65405. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  65406. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  65407. * Contact Hardening
  65408. */
  65409. ShadowGenerator.FILTER_PCSS = 7;
  65410. /**
  65411. * Reserved for PCF and PCSS
  65412. * Highest Quality.
  65413. *
  65414. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  65415. *
  65416. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  65417. */
  65418. ShadowGenerator.QUALITY_HIGH = 0;
  65419. /**
  65420. * Reserved for PCF and PCSS
  65421. * Good tradeoff for quality/perf cross devices
  65422. *
  65423. * Execute PCF on a 3*3 kernel.
  65424. *
  65425. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  65426. */
  65427. ShadowGenerator.QUALITY_MEDIUM = 1;
  65428. /**
  65429. * Reserved for PCF and PCSS
  65430. * The lowest quality but the fastest.
  65431. *
  65432. * Execute PCF on a 1*1 kernel.
  65433. *
  65434. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  65435. */
  65436. ShadowGenerator.QUALITY_LOW = 2;
  65437. return ShadowGenerator;
  65438. }());
  65439. BABYLON.ShadowGenerator = ShadowGenerator;
  65440. })(BABYLON || (BABYLON = {}));
  65441. //# sourceMappingURL=babylon.shadowGenerator.js.map
  65442. "use strict";
  65443. var BABYLON;
  65444. (function (BABYLON) {
  65445. var DefaultLoadingScreen = /** @class */ (function () {
  65446. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  65447. if (_loadingText === void 0) { _loadingText = ""; }
  65448. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  65449. var _this = this;
  65450. this._renderingCanvas = _renderingCanvas;
  65451. this._loadingText = _loadingText;
  65452. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  65453. // Resize
  65454. this._resizeLoadingUI = function () {
  65455. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  65456. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  65457. if (!_this._loadingDiv) {
  65458. return;
  65459. }
  65460. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  65461. _this._loadingDiv.style.left = canvasRect.left + "px";
  65462. _this._loadingDiv.style.top = canvasRect.top + "px";
  65463. _this._loadingDiv.style.width = canvasRect.width + "px";
  65464. _this._loadingDiv.style.height = canvasRect.height + "px";
  65465. };
  65466. }
  65467. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  65468. if (this._loadingDiv) {
  65469. // Do not add a loading screen if there is already one
  65470. return;
  65471. }
  65472. this._loadingDiv = document.createElement("div");
  65473. this._loadingDiv.id = "babylonjsLoadingDiv";
  65474. this._loadingDiv.style.opacity = "0";
  65475. this._loadingDiv.style.transition = "opacity 1.5s ease";
  65476. this._loadingDiv.style.pointerEvents = "none";
  65477. // Loading text
  65478. this._loadingTextDiv = document.createElement("div");
  65479. this._loadingTextDiv.style.position = "absolute";
  65480. this._loadingTextDiv.style.left = "0";
  65481. this._loadingTextDiv.style.top = "50%";
  65482. this._loadingTextDiv.style.marginTop = "80px";
  65483. this._loadingTextDiv.style.width = "100%";
  65484. this._loadingTextDiv.style.height = "20px";
  65485. this._loadingTextDiv.style.fontFamily = "Arial";
  65486. this._loadingTextDiv.style.fontSize = "14px";
  65487. this._loadingTextDiv.style.color = "white";
  65488. this._loadingTextDiv.style.textAlign = "center";
  65489. this._loadingTextDiv.innerHTML = "Loading";
  65490. this._loadingDiv.appendChild(this._loadingTextDiv);
  65491. //set the predefined text
  65492. this._loadingTextDiv.innerHTML = this._loadingText;
  65493. // Generating keyframes
  65494. var style = document.createElement('style');
  65495. style.type = 'text/css';
  65496. 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 }";
  65497. style.innerHTML = keyFrames;
  65498. document.getElementsByTagName('head')[0].appendChild(style);
  65499. // Loading img
  65500. var imgBack = new Image();
  65501. 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";
  65502. imgBack.style.position = "absolute";
  65503. imgBack.style.left = "50%";
  65504. imgBack.style.top = "50%";
  65505. imgBack.style.marginLeft = "-60px";
  65506. imgBack.style.marginTop = "-60px";
  65507. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  65508. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  65509. imgBack.style.transformOrigin = "50% 50%";
  65510. imgBack.style.webkitTransformOrigin = "50% 50%";
  65511. this._loadingDiv.appendChild(imgBack);
  65512. this._resizeLoadingUI();
  65513. window.addEventListener("resize", this._resizeLoadingUI);
  65514. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  65515. document.body.appendChild(this._loadingDiv);
  65516. this._loadingDiv.style.opacity = "1";
  65517. };
  65518. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  65519. var _this = this;
  65520. if (!this._loadingDiv) {
  65521. return;
  65522. }
  65523. var onTransitionEnd = function () {
  65524. if (!_this._loadingDiv) {
  65525. return;
  65526. }
  65527. document.body.removeChild(_this._loadingDiv);
  65528. window.removeEventListener("resize", _this._resizeLoadingUI);
  65529. _this._loadingDiv = null;
  65530. };
  65531. this._loadingDiv.style.opacity = "0";
  65532. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  65533. };
  65534. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  65535. set: function (text) {
  65536. this._loadingText = text;
  65537. if (this._loadingTextDiv) {
  65538. this._loadingTextDiv.innerHTML = this._loadingText;
  65539. }
  65540. },
  65541. enumerable: true,
  65542. configurable: true
  65543. });
  65544. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  65545. get: function () {
  65546. return this._loadingDivBackgroundColor;
  65547. },
  65548. set: function (color) {
  65549. this._loadingDivBackgroundColor = color;
  65550. if (!this._loadingDiv) {
  65551. return;
  65552. }
  65553. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  65554. },
  65555. enumerable: true,
  65556. configurable: true
  65557. });
  65558. return DefaultLoadingScreen;
  65559. }());
  65560. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  65561. })(BABYLON || (BABYLON = {}));
  65562. //# sourceMappingURL=babylon.loadingScreen.js.map
  65563. "use strict";
  65564. var BABYLON;
  65565. (function (BABYLON) {
  65566. var SceneLoaderProgressEvent = /** @class */ (function () {
  65567. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  65568. this.lengthComputable = lengthComputable;
  65569. this.loaded = loaded;
  65570. this.total = total;
  65571. }
  65572. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  65573. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  65574. };
  65575. return SceneLoaderProgressEvent;
  65576. }());
  65577. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  65578. var SceneLoader = /** @class */ (function () {
  65579. function SceneLoader() {
  65580. }
  65581. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  65582. get: function () {
  65583. return 0;
  65584. },
  65585. enumerable: true,
  65586. configurable: true
  65587. });
  65588. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  65589. get: function () {
  65590. return 1;
  65591. },
  65592. enumerable: true,
  65593. configurable: true
  65594. });
  65595. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  65596. get: function () {
  65597. return 2;
  65598. },
  65599. enumerable: true,
  65600. configurable: true
  65601. });
  65602. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  65603. get: function () {
  65604. return 3;
  65605. },
  65606. enumerable: true,
  65607. configurable: true
  65608. });
  65609. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  65610. get: function () {
  65611. return SceneLoader._ForceFullSceneLoadingForIncremental;
  65612. },
  65613. set: function (value) {
  65614. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  65615. },
  65616. enumerable: true,
  65617. configurable: true
  65618. });
  65619. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  65620. get: function () {
  65621. return SceneLoader._ShowLoadingScreen;
  65622. },
  65623. set: function (value) {
  65624. SceneLoader._ShowLoadingScreen = value;
  65625. },
  65626. enumerable: true,
  65627. configurable: true
  65628. });
  65629. Object.defineProperty(SceneLoader, "loggingLevel", {
  65630. get: function () {
  65631. return SceneLoader._loggingLevel;
  65632. },
  65633. set: function (value) {
  65634. SceneLoader._loggingLevel = value;
  65635. },
  65636. enumerable: true,
  65637. configurable: true
  65638. });
  65639. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  65640. get: function () {
  65641. return SceneLoader._CleanBoneMatrixWeights;
  65642. },
  65643. set: function (value) {
  65644. SceneLoader._CleanBoneMatrixWeights = value;
  65645. },
  65646. enumerable: true,
  65647. configurable: true
  65648. });
  65649. SceneLoader._getDefaultPlugin = function () {
  65650. return SceneLoader._registeredPlugins[".babylon"];
  65651. };
  65652. SceneLoader._getPluginForExtension = function (extension) {
  65653. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  65654. if (registeredPlugin) {
  65655. return registeredPlugin;
  65656. }
  65657. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  65658. return SceneLoader._getDefaultPlugin();
  65659. };
  65660. SceneLoader._getPluginForDirectLoad = function (data) {
  65661. for (var extension in SceneLoader._registeredPlugins) {
  65662. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  65663. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  65664. return SceneLoader._registeredPlugins[extension];
  65665. }
  65666. }
  65667. return SceneLoader._getDefaultPlugin();
  65668. };
  65669. SceneLoader._getPluginForFilename = function (sceneFilename) {
  65670. if (sceneFilename.name) {
  65671. sceneFilename = sceneFilename.name;
  65672. }
  65673. var queryStringPosition = sceneFilename.indexOf("?");
  65674. if (queryStringPosition !== -1) {
  65675. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  65676. }
  65677. var dotPosition = sceneFilename.lastIndexOf(".");
  65678. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  65679. return SceneLoader._getPluginForExtension(extension);
  65680. };
  65681. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  65682. SceneLoader._getDirectLoad = function (sceneFilename) {
  65683. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  65684. return sceneFilename.substr(5);
  65685. }
  65686. return null;
  65687. };
  65688. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  65689. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  65690. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  65691. var plugin;
  65692. if (registeredPlugin.plugin.createPlugin) {
  65693. plugin = registeredPlugin.plugin.createPlugin();
  65694. }
  65695. else {
  65696. plugin = registeredPlugin.plugin;
  65697. }
  65698. var useArrayBuffer = registeredPlugin.isBinary;
  65699. var database;
  65700. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  65701. var dataCallback = function (data, responseURL) {
  65702. if (scene.isDisposed) {
  65703. onError("Scene has been disposed");
  65704. return;
  65705. }
  65706. scene.database = database;
  65707. onSuccess(plugin, data, responseURL);
  65708. };
  65709. var request = null;
  65710. var pluginDisposed = false;
  65711. var onDisposeObservable = plugin.onDisposeObservable;
  65712. if (onDisposeObservable) {
  65713. onDisposeObservable.add(function () {
  65714. pluginDisposed = true;
  65715. if (request) {
  65716. request.abort();
  65717. request = null;
  65718. }
  65719. onDispose();
  65720. });
  65721. }
  65722. var manifestChecked = function () {
  65723. if (pluginDisposed) {
  65724. return;
  65725. }
  65726. var url = rootUrl + sceneFilename;
  65727. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  65728. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  65729. } : undefined, database, useArrayBuffer, function (request, exception) {
  65730. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  65731. });
  65732. };
  65733. if (directLoad) {
  65734. dataCallback(directLoad);
  65735. return plugin;
  65736. }
  65737. if (rootUrl.indexOf("file:") === -1) {
  65738. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  65739. if (canUseOfflineSupport) {
  65740. // Also check for exceptions
  65741. var exceptionFound = false;
  65742. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  65743. var regex = _a[_i];
  65744. if (regex.test(rootUrl + sceneFilename)) {
  65745. exceptionFound = true;
  65746. break;
  65747. }
  65748. }
  65749. canUseOfflineSupport = !exceptionFound;
  65750. }
  65751. if (canUseOfflineSupport) {
  65752. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  65753. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  65754. }
  65755. else {
  65756. manifestChecked();
  65757. }
  65758. }
  65759. else {
  65760. var fileOrString = sceneFilename;
  65761. if (fileOrString.name) {
  65762. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  65763. }
  65764. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  65765. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  65766. }
  65767. else {
  65768. onError("Unable to find file named " + sceneFilename);
  65769. }
  65770. }
  65771. return plugin;
  65772. };
  65773. // Public functions
  65774. SceneLoader.GetPluginForExtension = function (extension) {
  65775. return SceneLoader._getPluginForExtension(extension).plugin;
  65776. };
  65777. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  65778. return !!SceneLoader._registeredPlugins[extension];
  65779. };
  65780. SceneLoader.RegisterPlugin = function (plugin) {
  65781. if (typeof plugin.extensions === "string") {
  65782. var extension = plugin.extensions;
  65783. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  65784. plugin: plugin,
  65785. isBinary: false
  65786. };
  65787. }
  65788. else {
  65789. var extensions = plugin.extensions;
  65790. Object.keys(extensions).forEach(function (extension) {
  65791. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  65792. plugin: plugin,
  65793. isBinary: extensions[extension].isBinary
  65794. };
  65795. });
  65796. }
  65797. };
  65798. /**
  65799. * Import meshes into a scene
  65800. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  65801. * @param rootUrl a string that defines the root url for scene and resources
  65802. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65803. * @param scene the instance of BABYLON.Scene to append to
  65804. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  65805. * @param onProgress a callback with a progress event for each file being loaded
  65806. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65807. * @param pluginExtension the extension used to determine the plugin
  65808. * @returns The loaded plugin
  65809. */
  65810. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  65811. if (onSuccess === void 0) { onSuccess = null; }
  65812. if (onProgress === void 0) { onProgress = null; }
  65813. if (onError === void 0) { onError = null; }
  65814. if (pluginExtension === void 0) { pluginExtension = null; }
  65815. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  65816. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  65817. return null;
  65818. }
  65819. var loadingToken = {};
  65820. scene._addPendingData(loadingToken);
  65821. var disposeHandler = function () {
  65822. scene._removePendingData(loadingToken);
  65823. };
  65824. var errorHandler = function (message, exception) {
  65825. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  65826. if (onError) {
  65827. onError(scene, errorMessage, exception);
  65828. }
  65829. else {
  65830. BABYLON.Tools.Error(errorMessage);
  65831. // should the exception be thrown?
  65832. }
  65833. disposeHandler();
  65834. };
  65835. var progressHandler = onProgress ? function (event) {
  65836. try {
  65837. onProgress(event);
  65838. }
  65839. catch (e) {
  65840. errorHandler("Error in onProgress callback", e);
  65841. }
  65842. } : undefined;
  65843. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  65844. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  65845. if (onSuccess) {
  65846. try {
  65847. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  65848. }
  65849. catch (e) {
  65850. errorHandler("Error in onSuccess callback", e);
  65851. }
  65852. }
  65853. scene._removePendingData(loadingToken);
  65854. };
  65855. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  65856. if (plugin.rewriteRootURL) {
  65857. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  65858. }
  65859. if (sceneFilename === "") {
  65860. if (sceneFilename === "") {
  65861. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  65862. }
  65863. }
  65864. if (plugin.importMesh) {
  65865. var syncedPlugin = plugin;
  65866. var meshes = new Array();
  65867. var particleSystems = new Array();
  65868. var skeletons = new Array();
  65869. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  65870. return;
  65871. }
  65872. scene.loadingPluginName = plugin.name;
  65873. successHandler(meshes, particleSystems, skeletons, []);
  65874. }
  65875. else {
  65876. var asyncedPlugin = plugin;
  65877. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  65878. scene.loadingPluginName = plugin.name;
  65879. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  65880. }).catch(function (error) {
  65881. errorHandler(error.message, error);
  65882. });
  65883. }
  65884. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  65885. };
  65886. /**
  65887. * Import meshes into a scene
  65888. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  65889. * @param rootUrl a string that defines the root url for scene and resources
  65890. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65891. * @param scene the instance of BABYLON.Scene to append to
  65892. * @param onProgress a callback with a progress event for each file being loaded
  65893. * @param pluginExtension the extension used to determine the plugin
  65894. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  65895. */
  65896. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  65897. if (onProgress === void 0) { onProgress = null; }
  65898. if (pluginExtension === void 0) { pluginExtension = null; }
  65899. return new Promise(function (resolve, reject) {
  65900. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  65901. resolve({
  65902. meshes: meshes,
  65903. particleSystems: particleSystems,
  65904. skeletons: skeletons,
  65905. animationGroups: animationGroups
  65906. });
  65907. }, onProgress, function (scene, message, exception) {
  65908. reject(exception || new Error(message));
  65909. });
  65910. });
  65911. };
  65912. /**
  65913. * Load a scene
  65914. * @param rootUrl a string that defines the root url for scene and resources
  65915. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65916. * @param engine is the instance of BABYLON.Engine to use to create the scene
  65917. * @param onSuccess a callback with the scene when import succeeds
  65918. * @param onProgress a callback with a progress event for each file being loaded
  65919. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65920. * @param pluginExtension the extension used to determine the plugin
  65921. * @returns The loaded plugin
  65922. */
  65923. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  65924. if (onSuccess === void 0) { onSuccess = null; }
  65925. if (onProgress === void 0) { onProgress = null; }
  65926. if (onError === void 0) { onError = null; }
  65927. if (pluginExtension === void 0) { pluginExtension = null; }
  65928. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  65929. };
  65930. /**
  65931. * Load a scene
  65932. * @param rootUrl a string that defines the root url for scene and resources
  65933. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65934. * @param engine is the instance of BABYLON.Engine to use to create the scene
  65935. * @param onProgress a callback with a progress event for each file being loaded
  65936. * @param pluginExtension the extension used to determine the plugin
  65937. * @returns The loaded scene
  65938. */
  65939. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  65940. if (onProgress === void 0) { onProgress = null; }
  65941. if (pluginExtension === void 0) { pluginExtension = null; }
  65942. return new Promise(function (resolve, reject) {
  65943. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  65944. resolve(scene);
  65945. }, onProgress, function (scene, message, exception) {
  65946. reject(exception || new Error(message));
  65947. }, pluginExtension);
  65948. });
  65949. };
  65950. /**
  65951. * Append a scene
  65952. * @param rootUrl a string that defines the root url for scene and resources
  65953. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65954. * @param scene is the instance of BABYLON.Scene to append to
  65955. * @param onSuccess a callback with the scene when import succeeds
  65956. * @param onProgress a callback with a progress event for each file being loaded
  65957. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65958. * @param pluginExtension the extension used to determine the plugin
  65959. * @returns The loaded plugin
  65960. */
  65961. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  65962. if (onSuccess === void 0) { onSuccess = null; }
  65963. if (onProgress === void 0) { onProgress = null; }
  65964. if (onError === void 0) { onError = null; }
  65965. if (pluginExtension === void 0) { pluginExtension = null; }
  65966. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  65967. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  65968. return null;
  65969. }
  65970. if (SceneLoader.ShowLoadingScreen) {
  65971. scene.getEngine().displayLoadingUI();
  65972. }
  65973. var loadingToken = {};
  65974. scene._addPendingData(loadingToken);
  65975. var disposeHandler = function () {
  65976. scene._removePendingData(loadingToken);
  65977. scene.getEngine().hideLoadingUI();
  65978. };
  65979. var errorHandler = function (message, exception) {
  65980. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  65981. if (onError) {
  65982. onError(scene, errorMessage, exception);
  65983. }
  65984. else {
  65985. BABYLON.Tools.Error(errorMessage);
  65986. // should the exception be thrown?
  65987. }
  65988. disposeHandler();
  65989. };
  65990. var progressHandler = onProgress ? function (event) {
  65991. try {
  65992. onProgress(event);
  65993. }
  65994. catch (e) {
  65995. errorHandler("Error in onProgress callback", e);
  65996. }
  65997. } : undefined;
  65998. var successHandler = function () {
  65999. if (onSuccess) {
  66000. try {
  66001. onSuccess(scene);
  66002. }
  66003. catch (e) {
  66004. errorHandler("Error in onSuccess callback", e);
  66005. }
  66006. }
  66007. scene._removePendingData(loadingToken);
  66008. };
  66009. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66010. if (sceneFilename === "") {
  66011. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66012. }
  66013. if (plugin.load) {
  66014. var syncedPlugin = plugin;
  66015. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  66016. return;
  66017. }
  66018. scene.loadingPluginName = plugin.name;
  66019. successHandler();
  66020. }
  66021. else {
  66022. var asyncedPlugin = plugin;
  66023. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  66024. scene.loadingPluginName = plugin.name;
  66025. successHandler();
  66026. }).catch(function (error) {
  66027. errorHandler(error.message, error);
  66028. });
  66029. }
  66030. if (SceneLoader.ShowLoadingScreen) {
  66031. scene.executeWhenReady(function () {
  66032. scene.getEngine().hideLoadingUI();
  66033. });
  66034. }
  66035. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66036. };
  66037. /**
  66038. * Append a scene
  66039. * @param rootUrl a string that defines the root url for scene and resources
  66040. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66041. * @param scene is the instance of BABYLON.Scene to append to
  66042. * @param onProgress a callback with a progress event for each file being loaded
  66043. * @param pluginExtension the extension used to determine the plugin
  66044. * @returns The given scene
  66045. */
  66046. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66047. if (onProgress === void 0) { onProgress = null; }
  66048. if (pluginExtension === void 0) { pluginExtension = null; }
  66049. return new Promise(function (resolve, reject) {
  66050. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  66051. resolve(scene);
  66052. }, onProgress, function (scene, message, exception) {
  66053. reject(exception || new Error(message));
  66054. }, pluginExtension);
  66055. });
  66056. };
  66057. /**
  66058. * Load a scene into an asset container
  66059. * @param rootUrl a string that defines the root url for scene and resources
  66060. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66061. * @param scene is the instance of BABYLON.Scene to append to
  66062. * @param onSuccess a callback with the scene when import succeeds
  66063. * @param onProgress a callback with a progress event for each file being loaded
  66064. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66065. * @param pluginExtension the extension used to determine the plugin
  66066. * @returns The loaded plugin
  66067. */
  66068. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66069. if (onSuccess === void 0) { onSuccess = null; }
  66070. if (onProgress === void 0) { onProgress = null; }
  66071. if (onError === void 0) { onError = null; }
  66072. if (pluginExtension === void 0) { pluginExtension = null; }
  66073. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66074. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66075. return null;
  66076. }
  66077. var loadingToken = {};
  66078. scene._addPendingData(loadingToken);
  66079. var disposeHandler = function () {
  66080. scene._removePendingData(loadingToken);
  66081. };
  66082. var errorHandler = function (message, exception) {
  66083. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66084. if (onError) {
  66085. onError(scene, errorMessage, exception);
  66086. }
  66087. else {
  66088. BABYLON.Tools.Error(errorMessage);
  66089. // should the exception be thrown?
  66090. }
  66091. disposeHandler();
  66092. };
  66093. var progressHandler = onProgress ? function (event) {
  66094. try {
  66095. onProgress(event);
  66096. }
  66097. catch (e) {
  66098. errorHandler("Error in onProgress callback", e);
  66099. }
  66100. } : undefined;
  66101. var successHandler = function (assets) {
  66102. if (onSuccess) {
  66103. try {
  66104. onSuccess(assets);
  66105. }
  66106. catch (e) {
  66107. errorHandler("Error in onSuccess callback", e);
  66108. }
  66109. }
  66110. scene._removePendingData(loadingToken);
  66111. };
  66112. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66113. if (plugin.loadAssetContainer) {
  66114. var syncedPlugin = plugin;
  66115. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  66116. if (!assetContainer) {
  66117. return;
  66118. }
  66119. scene.loadingPluginName = plugin.name;
  66120. successHandler(assetContainer);
  66121. }
  66122. else if (plugin.loadAssetContainerAsync) {
  66123. var asyncedPlugin = plugin;
  66124. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  66125. scene.loadingPluginName = plugin.name;
  66126. successHandler(assetContainer);
  66127. }).catch(function (error) {
  66128. errorHandler(error.message, error);
  66129. });
  66130. }
  66131. else {
  66132. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  66133. }
  66134. if (SceneLoader.ShowLoadingScreen) {
  66135. scene.executeWhenReady(function () {
  66136. scene.getEngine().hideLoadingUI();
  66137. });
  66138. }
  66139. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66140. };
  66141. /**
  66142. * Load a scene into an asset container
  66143. * @param rootUrl a string that defines the root url for scene and resources
  66144. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66145. * @param scene is the instance of BABYLON.Scene to append to
  66146. * @param onProgress a callback with a progress event for each file being loaded
  66147. * @param pluginExtension the extension used to determine the plugin
  66148. * @returns The loaded asset container
  66149. */
  66150. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66151. if (onProgress === void 0) { onProgress = null; }
  66152. if (pluginExtension === void 0) { pluginExtension = null; }
  66153. return new Promise(function (resolve, reject) {
  66154. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  66155. resolve(assetContainer);
  66156. }, onProgress, function (scene, message, exception) {
  66157. reject(exception || new Error(message));
  66158. }, pluginExtension);
  66159. });
  66160. };
  66161. // Flags
  66162. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  66163. SceneLoader._ShowLoadingScreen = true;
  66164. SceneLoader._CleanBoneMatrixWeights = false;
  66165. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  66166. // Members
  66167. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  66168. SceneLoader._registeredPlugins = {};
  66169. return SceneLoader;
  66170. }());
  66171. BABYLON.SceneLoader = SceneLoader;
  66172. ;
  66173. })(BABYLON || (BABYLON = {}));
  66174. //# sourceMappingURL=babylon.sceneLoader.js.map
  66175. "use strict";
  66176. var BABYLON;
  66177. (function (BABYLON) {
  66178. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  66179. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66180. var parsedMaterial = parsedData.materials[index];
  66181. if (parsedMaterial.id === id) {
  66182. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66183. }
  66184. }
  66185. return null;
  66186. };
  66187. var isDescendantOf = function (mesh, names, hierarchyIds) {
  66188. for (var i in names) {
  66189. if (mesh.name === names[i]) {
  66190. hierarchyIds.push(mesh.id);
  66191. return true;
  66192. }
  66193. }
  66194. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  66195. hierarchyIds.push(mesh.id);
  66196. return true;
  66197. }
  66198. return false;
  66199. };
  66200. var logOperation = function (operation, producer) {
  66201. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  66202. };
  66203. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  66204. if (addToScene === void 0) { addToScene = false; }
  66205. var container = new BABYLON.AssetContainer(scene);
  66206. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66207. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66208. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66209. // and avoid problems with multiple concurrent .babylon loads.
  66210. var log = "importScene has failed JSON parse";
  66211. try {
  66212. var parsedData = JSON.parse(data);
  66213. log = "";
  66214. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  66215. var index;
  66216. var cache;
  66217. // Lights
  66218. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  66219. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  66220. var parsedLight = parsedData.lights[index];
  66221. var light = BABYLON.Light.Parse(parsedLight, scene);
  66222. if (light) {
  66223. container.lights.push(light);
  66224. log += (index === 0 ? "\n\tLights:" : "");
  66225. log += "\n\t\t" + light.toString(fullDetails);
  66226. }
  66227. }
  66228. }
  66229. // Animations
  66230. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  66231. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  66232. var parsedAnimation = parsedData.animations[index];
  66233. var animation = BABYLON.Animation.Parse(parsedAnimation);
  66234. scene.animations.push(animation);
  66235. container.animations.push(animation);
  66236. log += (index === 0 ? "\n\tAnimations:" : "");
  66237. log += "\n\t\t" + animation.toString(fullDetails);
  66238. }
  66239. }
  66240. // Materials
  66241. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  66242. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66243. var parsedMaterial = parsedData.materials[index];
  66244. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66245. container.materials.push(mat);
  66246. log += (index === 0 ? "\n\tMaterials:" : "");
  66247. log += "\n\t\t" + mat.toString(fullDetails);
  66248. }
  66249. }
  66250. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  66251. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  66252. var parsedMultiMaterial = parsedData.multiMaterials[index];
  66253. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  66254. container.multiMaterials.push(mmat);
  66255. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  66256. log += "\n\t\t" + mmat.toString(fullDetails);
  66257. }
  66258. }
  66259. // Morph targets
  66260. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  66261. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  66262. var managerData = _a[_i];
  66263. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  66264. }
  66265. }
  66266. // Skeletons
  66267. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  66268. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  66269. var parsedSkeleton = parsedData.skeletons[index];
  66270. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  66271. container.skeletons.push(skeleton);
  66272. log += (index === 0 ? "\n\tSkeletons:" : "");
  66273. log += "\n\t\t" + skeleton.toString(fullDetails);
  66274. }
  66275. }
  66276. // Geometries
  66277. var geometries = parsedData.geometries;
  66278. if (geometries !== undefined && geometries !== null) {
  66279. var addedGeometry = new Array();
  66280. // Boxes
  66281. var boxes = geometries.boxes;
  66282. if (boxes !== undefined && boxes !== null) {
  66283. for (index = 0, cache = boxes.length; index < cache; index++) {
  66284. var parsedBox = boxes[index];
  66285. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  66286. }
  66287. }
  66288. // Spheres
  66289. var spheres = geometries.spheres;
  66290. if (spheres !== undefined && spheres !== null) {
  66291. for (index = 0, cache = spheres.length; index < cache; index++) {
  66292. var parsedSphere = spheres[index];
  66293. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  66294. }
  66295. }
  66296. // Cylinders
  66297. var cylinders = geometries.cylinders;
  66298. if (cylinders !== undefined && cylinders !== null) {
  66299. for (index = 0, cache = cylinders.length; index < cache; index++) {
  66300. var parsedCylinder = cylinders[index];
  66301. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  66302. }
  66303. }
  66304. // Toruses
  66305. var toruses = geometries.toruses;
  66306. if (toruses !== undefined && toruses !== null) {
  66307. for (index = 0, cache = toruses.length; index < cache; index++) {
  66308. var parsedTorus = toruses[index];
  66309. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  66310. }
  66311. }
  66312. // Grounds
  66313. var grounds = geometries.grounds;
  66314. if (grounds !== undefined && grounds !== null) {
  66315. for (index = 0, cache = grounds.length; index < cache; index++) {
  66316. var parsedGround = grounds[index];
  66317. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  66318. }
  66319. }
  66320. // Planes
  66321. var planes = geometries.planes;
  66322. if (planes !== undefined && planes !== null) {
  66323. for (index = 0, cache = planes.length; index < cache; index++) {
  66324. var parsedPlane = planes[index];
  66325. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  66326. }
  66327. }
  66328. // TorusKnots
  66329. var torusKnots = geometries.torusKnots;
  66330. if (torusKnots !== undefined && torusKnots !== null) {
  66331. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  66332. var parsedTorusKnot = torusKnots[index];
  66333. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  66334. }
  66335. }
  66336. // VertexData
  66337. var vertexData = geometries.vertexData;
  66338. if (vertexData !== undefined && vertexData !== null) {
  66339. for (index = 0, cache = vertexData.length; index < cache; index++) {
  66340. var parsedVertexData = vertexData[index];
  66341. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  66342. }
  66343. }
  66344. addedGeometry.forEach(function (g) {
  66345. if (g) {
  66346. container.geometries.push(g);
  66347. }
  66348. });
  66349. }
  66350. // Transform nodes
  66351. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  66352. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  66353. var parsedTransformNode = parsedData.transformNodes[index];
  66354. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  66355. container.transformNodes.push(node);
  66356. }
  66357. }
  66358. // Meshes
  66359. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  66360. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  66361. var parsedMesh = parsedData.meshes[index];
  66362. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  66363. container.meshes.push(mesh);
  66364. log += (index === 0 ? "\n\tMeshes:" : "");
  66365. log += "\n\t\t" + mesh.toString(fullDetails);
  66366. }
  66367. }
  66368. // Cameras
  66369. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  66370. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  66371. var parsedCamera = parsedData.cameras[index];
  66372. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  66373. container.cameras.push(camera);
  66374. log += (index === 0 ? "\n\tCameras:" : "");
  66375. log += "\n\t\t" + camera.toString(fullDetails);
  66376. }
  66377. }
  66378. // Browsing all the graph to connect the dots
  66379. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  66380. var camera = scene.cameras[index];
  66381. if (camera._waitingParentId) {
  66382. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  66383. camera._waitingParentId = null;
  66384. }
  66385. }
  66386. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  66387. var light_1 = scene.lights[index];
  66388. if (light_1 && light_1._waitingParentId) {
  66389. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  66390. light_1._waitingParentId = null;
  66391. }
  66392. }
  66393. // Sounds
  66394. // TODO: add sound
  66395. var loadedSounds = [];
  66396. var loadedSound;
  66397. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  66398. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  66399. var parsedSound = parsedData.sounds[index];
  66400. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66401. if (!parsedSound.url)
  66402. parsedSound.url = parsedSound.name;
  66403. if (!loadedSounds[parsedSound.url]) {
  66404. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  66405. loadedSounds[parsedSound.url] = loadedSound;
  66406. container.sounds.push(loadedSound);
  66407. }
  66408. else {
  66409. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  66410. }
  66411. }
  66412. else {
  66413. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  66414. }
  66415. }
  66416. }
  66417. loadedSounds = [];
  66418. // Connect parents & children and parse actions
  66419. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  66420. var transformNode = scene.transformNodes[index];
  66421. if (transformNode._waitingParentId) {
  66422. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  66423. transformNode._waitingParentId = null;
  66424. }
  66425. }
  66426. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66427. var mesh = scene.meshes[index];
  66428. if (mesh._waitingParentId) {
  66429. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  66430. mesh._waitingParentId = null;
  66431. }
  66432. if (mesh._waitingActions) {
  66433. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  66434. mesh._waitingActions = null;
  66435. }
  66436. }
  66437. // freeze world matrix application
  66438. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66439. var currentMesh = scene.meshes[index];
  66440. if (currentMesh._waitingFreezeWorldMatrix) {
  66441. currentMesh.freezeWorldMatrix();
  66442. currentMesh._waitingFreezeWorldMatrix = null;
  66443. }
  66444. else {
  66445. currentMesh.computeWorldMatrix(true);
  66446. }
  66447. }
  66448. // Particles Systems
  66449. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  66450. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  66451. var parsedParticleSystem = parsedData.particleSystems[index];
  66452. if (parsedParticleSystem.activeParticleCount) {
  66453. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  66454. container.particleSystems.push(ps);
  66455. }
  66456. else {
  66457. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  66458. container.particleSystems.push(ps);
  66459. }
  66460. }
  66461. }
  66462. // Lens flares
  66463. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  66464. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  66465. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  66466. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  66467. container.lensFlareSystems.push(lf);
  66468. }
  66469. }
  66470. // Shadows
  66471. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  66472. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  66473. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  66474. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  66475. container.shadowGenerators.push(sg);
  66476. }
  66477. }
  66478. // Lights exclusions / inclusions
  66479. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  66480. var light_2 = scene.lights[index];
  66481. // Excluded check
  66482. if (light_2._excludedMeshesIds.length > 0) {
  66483. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  66484. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  66485. if (excludedMesh) {
  66486. light_2.excludedMeshes.push(excludedMesh);
  66487. }
  66488. }
  66489. light_2._excludedMeshesIds = [];
  66490. }
  66491. // Included check
  66492. if (light_2._includedOnlyMeshesIds.length > 0) {
  66493. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  66494. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  66495. if (includedOnlyMesh) {
  66496. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  66497. }
  66498. }
  66499. light_2._includedOnlyMeshesIds = [];
  66500. }
  66501. }
  66502. // Effect layers
  66503. if (parsedData.effectLayers) {
  66504. for (index = 0; index < parsedData.effectLayers.length; index++) {
  66505. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  66506. container.effectLayers.push(effectLayer);
  66507. }
  66508. }
  66509. // Actions (scene)
  66510. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  66511. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  66512. }
  66513. if (!addToScene) {
  66514. container.removeAllFromScene();
  66515. }
  66516. }
  66517. catch (err) {
  66518. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  66519. if (onError) {
  66520. onError(msg, err);
  66521. }
  66522. else {
  66523. BABYLON.Tools.Log(msg);
  66524. throw err;
  66525. }
  66526. }
  66527. finally {
  66528. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  66529. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  66530. }
  66531. }
  66532. return container;
  66533. };
  66534. BABYLON.SceneLoader.RegisterPlugin({
  66535. name: "babylon.js",
  66536. extensions: ".babylon",
  66537. canDirectLoad: function (data) {
  66538. if (data.indexOf("babylon") !== -1) {
  66539. return true;
  66540. }
  66541. return false;
  66542. },
  66543. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  66544. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66545. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66546. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66547. // and avoid problems with multiple concurrent .babylon loads.
  66548. var log = "importMesh has failed JSON parse";
  66549. try {
  66550. var parsedData = JSON.parse(data);
  66551. log = "";
  66552. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  66553. if (!meshesNames) {
  66554. meshesNames = null;
  66555. }
  66556. else if (!Array.isArray(meshesNames)) {
  66557. meshesNames = [meshesNames];
  66558. }
  66559. var hierarchyIds = new Array();
  66560. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  66561. var loadedSkeletonsIds = [];
  66562. var loadedMaterialsIds = [];
  66563. var index;
  66564. var cache;
  66565. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  66566. var parsedMesh = parsedData.meshes[index];
  66567. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  66568. if (meshesNames !== null) {
  66569. // Remove found mesh name from list.
  66570. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  66571. }
  66572. //Geometry?
  66573. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  66574. //does the file contain geometries?
  66575. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  66576. //find the correct geometry and add it to the scene
  66577. var found = false;
  66578. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  66579. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  66580. return;
  66581. }
  66582. else {
  66583. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  66584. if (parsedGeometryData.id === parsedMesh.geometryId) {
  66585. switch (geometryType) {
  66586. case "boxes":
  66587. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  66588. break;
  66589. case "spheres":
  66590. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  66591. break;
  66592. case "cylinders":
  66593. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  66594. break;
  66595. case "toruses":
  66596. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  66597. break;
  66598. case "grounds":
  66599. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  66600. break;
  66601. case "planes":
  66602. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  66603. break;
  66604. case "torusKnots":
  66605. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  66606. break;
  66607. case "vertexData":
  66608. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  66609. break;
  66610. }
  66611. found = true;
  66612. }
  66613. });
  66614. }
  66615. });
  66616. if (found === false) {
  66617. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  66618. }
  66619. }
  66620. }
  66621. // Material ?
  66622. if (parsedMesh.materialId) {
  66623. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  66624. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  66625. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  66626. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  66627. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  66628. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  66629. var subMatId = parsedMultiMaterial.materials[matIndex];
  66630. loadedMaterialsIds.push(subMatId);
  66631. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  66632. if (mat) {
  66633. log += "\n\tMaterial " + mat.toString(fullDetails);
  66634. }
  66635. }
  66636. loadedMaterialsIds.push(parsedMultiMaterial.id);
  66637. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  66638. if (mmat) {
  66639. materialFound = true;
  66640. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  66641. }
  66642. break;
  66643. }
  66644. }
  66645. }
  66646. if (materialFound === false) {
  66647. loadedMaterialsIds.push(parsedMesh.materialId);
  66648. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  66649. if (!mat) {
  66650. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  66651. }
  66652. else {
  66653. log += "\n\tMaterial " + mat.toString(fullDetails);
  66654. }
  66655. }
  66656. }
  66657. // Skeleton ?
  66658. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  66659. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  66660. if (skeletonAlreadyLoaded === false) {
  66661. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  66662. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  66663. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  66664. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  66665. skeletons.push(skeleton);
  66666. loadedSkeletonsIds.push(parsedSkeleton.id);
  66667. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  66668. }
  66669. }
  66670. }
  66671. }
  66672. // Morph targets ?
  66673. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  66674. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  66675. var managerData = _a[_i];
  66676. BABYLON.MorphTargetManager.Parse(managerData, scene);
  66677. }
  66678. }
  66679. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  66680. meshes.push(mesh);
  66681. log += "\n\tMesh " + mesh.toString(fullDetails);
  66682. }
  66683. }
  66684. // Connecting parents
  66685. var currentMesh;
  66686. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66687. currentMesh = scene.meshes[index];
  66688. if (currentMesh._waitingParentId) {
  66689. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  66690. currentMesh._waitingParentId = null;
  66691. }
  66692. }
  66693. // freeze and compute world matrix application
  66694. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66695. currentMesh = scene.meshes[index];
  66696. if (currentMesh._waitingFreezeWorldMatrix) {
  66697. currentMesh.freezeWorldMatrix();
  66698. currentMesh._waitingFreezeWorldMatrix = null;
  66699. }
  66700. else {
  66701. currentMesh.computeWorldMatrix(true);
  66702. }
  66703. }
  66704. }
  66705. // Particles
  66706. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  66707. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  66708. var parsedParticleSystem = parsedData.particleSystems[index];
  66709. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  66710. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  66711. }
  66712. }
  66713. }
  66714. return true;
  66715. }
  66716. catch (err) {
  66717. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  66718. if (onError) {
  66719. onError(msg, err);
  66720. }
  66721. else {
  66722. BABYLON.Tools.Log(msg);
  66723. throw err;
  66724. }
  66725. }
  66726. finally {
  66727. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  66728. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  66729. }
  66730. }
  66731. return false;
  66732. },
  66733. load: function (scene, data, rootUrl, onError) {
  66734. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66735. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66736. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66737. // and avoid problems with multiple concurrent .babylon loads.
  66738. var log = "importScene has failed JSON parse";
  66739. try {
  66740. var parsedData = JSON.parse(data);
  66741. log = "";
  66742. // Scene
  66743. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  66744. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  66745. }
  66746. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  66747. scene.autoClear = parsedData.autoClear;
  66748. }
  66749. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  66750. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  66751. }
  66752. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  66753. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  66754. }
  66755. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  66756. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  66757. }
  66758. // Fog
  66759. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  66760. scene.fogMode = parsedData.fogMode;
  66761. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  66762. scene.fogStart = parsedData.fogStart;
  66763. scene.fogEnd = parsedData.fogEnd;
  66764. scene.fogDensity = parsedData.fogDensity;
  66765. log += "\tFog mode for scene: ";
  66766. switch (scene.fogMode) {
  66767. // getters not compiling, so using hardcoded
  66768. case 1:
  66769. log += "exp\n";
  66770. break;
  66771. case 2:
  66772. log += "exp2\n";
  66773. break;
  66774. case 3:
  66775. log += "linear\n";
  66776. break;
  66777. }
  66778. }
  66779. //Physics
  66780. if (parsedData.physicsEnabled) {
  66781. var physicsPlugin;
  66782. if (parsedData.physicsEngine === "cannon") {
  66783. physicsPlugin = new BABYLON.CannonJSPlugin();
  66784. }
  66785. else if (parsedData.physicsEngine === "oimo") {
  66786. physicsPlugin = new BABYLON.OimoJSPlugin();
  66787. }
  66788. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  66789. //else - default engine, which is currently oimo
  66790. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  66791. scene.enablePhysics(physicsGravity, physicsPlugin);
  66792. }
  66793. // Metadata
  66794. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  66795. scene.metadata = parsedData.metadata;
  66796. }
  66797. //collisions, if defined. otherwise, default is true
  66798. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  66799. scene.collisionsEnabled = parsedData.collisionsEnabled;
  66800. }
  66801. scene.workerCollisions = !!parsedData.workerCollisions;
  66802. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  66803. if (!container) {
  66804. return false;
  66805. }
  66806. if (parsedData.autoAnimate) {
  66807. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  66808. }
  66809. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  66810. scene.setActiveCameraByID(parsedData.activeCameraID);
  66811. }
  66812. // Environment texture
  66813. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  66814. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  66815. if (parsedData.createDefaultSkybox === true) {
  66816. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  66817. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  66818. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  66819. }
  66820. }
  66821. // Finish
  66822. return true;
  66823. }
  66824. catch (err) {
  66825. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  66826. if (onError) {
  66827. onError(msg, err);
  66828. }
  66829. else {
  66830. BABYLON.Tools.Log(msg);
  66831. throw err;
  66832. }
  66833. }
  66834. finally {
  66835. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  66836. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  66837. }
  66838. }
  66839. return false;
  66840. },
  66841. loadAssetContainer: function (scene, data, rootUrl, onError) {
  66842. var container = loadAssetContainer(scene, data, rootUrl, onError);
  66843. return container;
  66844. }
  66845. });
  66846. })(BABYLON || (BABYLON = {}));
  66847. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  66848. "use strict";
  66849. var BABYLON;
  66850. (function (BABYLON) {
  66851. var FilesInput = /** @class */ (function () {
  66852. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  66853. this.onProcessFileCallback = function () { return true; };
  66854. this._engine = engine;
  66855. this._currentScene = scene;
  66856. this._sceneLoadedCallback = sceneLoadedCallback;
  66857. this._progressCallback = progressCallback;
  66858. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  66859. this._textureLoadingCallback = textureLoadingCallback;
  66860. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  66861. this._onReloadCallback = onReloadCallback;
  66862. this._errorCallback = errorCallback;
  66863. }
  66864. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  66865. var _this = this;
  66866. if (elementToMonitor) {
  66867. this._elementToMonitor = elementToMonitor;
  66868. this._dragEnterHandler = function (e) { _this.drag(e); };
  66869. this._dragOverHandler = function (e) { _this.drag(e); };
  66870. this._dropHandler = function (e) { _this.drop(e); };
  66871. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  66872. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  66873. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  66874. }
  66875. };
  66876. FilesInput.prototype.dispose = function () {
  66877. if (!this._elementToMonitor) {
  66878. return;
  66879. }
  66880. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  66881. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  66882. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  66883. };
  66884. FilesInput.prototype.renderFunction = function () {
  66885. if (this._additionalRenderLoopLogicCallback) {
  66886. this._additionalRenderLoopLogicCallback();
  66887. }
  66888. if (this._currentScene) {
  66889. if (this._textureLoadingCallback) {
  66890. var remaining = this._currentScene.getWaitingItemsCount();
  66891. if (remaining > 0) {
  66892. this._textureLoadingCallback(remaining);
  66893. }
  66894. }
  66895. this._currentScene.render();
  66896. }
  66897. };
  66898. FilesInput.prototype.drag = function (e) {
  66899. e.stopPropagation();
  66900. e.preventDefault();
  66901. };
  66902. FilesInput.prototype.drop = function (eventDrop) {
  66903. eventDrop.stopPropagation();
  66904. eventDrop.preventDefault();
  66905. this.loadFiles(eventDrop);
  66906. };
  66907. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  66908. var _this = this;
  66909. var reader = folder.createReader();
  66910. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  66911. reader.readEntries(function (entries) {
  66912. remaining.count += entries.length;
  66913. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  66914. var entry = entries_1[_i];
  66915. if (entry.isFile) {
  66916. entry.file(function (file) {
  66917. file.correctName = relativePath + file.name;
  66918. files.push(file);
  66919. if (--remaining.count === 0) {
  66920. callback();
  66921. }
  66922. });
  66923. }
  66924. else if (entry.isDirectory) {
  66925. _this._traverseFolder(entry, files, remaining, callback);
  66926. }
  66927. }
  66928. if (--remaining.count) {
  66929. callback();
  66930. }
  66931. });
  66932. };
  66933. FilesInput.prototype._processFiles = function (files) {
  66934. for (var i = 0; i < files.length; i++) {
  66935. var name = files[i].correctName.toLowerCase();
  66936. var extension = name.split('.').pop();
  66937. if (!this.onProcessFileCallback(files[i], name, extension)) {
  66938. continue;
  66939. }
  66940. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  66941. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  66942. this._sceneFileToLoad = files[i];
  66943. }
  66944. else {
  66945. FilesInput.FilesToLoad[name] = files[i];
  66946. }
  66947. }
  66948. };
  66949. FilesInput.prototype.loadFiles = function (event) {
  66950. var _this = this;
  66951. if (this._startingProcessingFilesCallback)
  66952. this._startingProcessingFilesCallback();
  66953. // Handling data transfer via drag'n'drop
  66954. if (event && event.dataTransfer && event.dataTransfer.files) {
  66955. this._filesToLoad = event.dataTransfer.files;
  66956. }
  66957. // Handling files from input files
  66958. if (event && event.target && event.target.files) {
  66959. this._filesToLoad = event.target.files;
  66960. }
  66961. if (this._filesToLoad && this._filesToLoad.length > 0) {
  66962. var files_1 = new Array();
  66963. var folders = [];
  66964. var items = event.dataTransfer ? event.dataTransfer.items : null;
  66965. for (var i = 0; i < this._filesToLoad.length; i++) {
  66966. var fileToLoad = this._filesToLoad[i];
  66967. var name_1 = fileToLoad.name.toLowerCase();
  66968. var entry = void 0;
  66969. fileToLoad.correctName = name_1;
  66970. if (items) {
  66971. var item = items[i];
  66972. if (item.getAsEntry) {
  66973. entry = item.getAsEntry();
  66974. }
  66975. else if (item.webkitGetAsEntry) {
  66976. entry = item.webkitGetAsEntry();
  66977. }
  66978. }
  66979. if (!entry) {
  66980. files_1.push(fileToLoad);
  66981. }
  66982. else {
  66983. if (entry.isDirectory) {
  66984. folders.push(entry);
  66985. }
  66986. else {
  66987. files_1.push(fileToLoad);
  66988. }
  66989. }
  66990. }
  66991. if (folders.length === 0) {
  66992. this._processFiles(files_1);
  66993. this._processReload();
  66994. }
  66995. else {
  66996. var remaining = { count: folders.length };
  66997. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  66998. var folder = folders_1[_i];
  66999. this._traverseFolder(folder, files_1, remaining, function () {
  67000. _this._processFiles(files_1);
  67001. if (remaining.count === 0) {
  67002. _this._processReload();
  67003. }
  67004. });
  67005. }
  67006. }
  67007. }
  67008. };
  67009. FilesInput.prototype._processReload = function () {
  67010. if (this._onReloadCallback) {
  67011. this._onReloadCallback(this._sceneFileToLoad);
  67012. }
  67013. else {
  67014. this.reload();
  67015. }
  67016. };
  67017. FilesInput.prototype.reload = function () {
  67018. var _this = this;
  67019. // If a scene file has been provided
  67020. if (this._sceneFileToLoad) {
  67021. if (this._currentScene) {
  67022. if (BABYLON.Tools.errorsCount > 0) {
  67023. BABYLON.Tools.ClearLogCache();
  67024. }
  67025. this._engine.stopRenderLoop();
  67026. this._currentScene.dispose();
  67027. }
  67028. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  67029. if (_this._progressCallback) {
  67030. _this._progressCallback(progress);
  67031. }
  67032. }).then(function (scene) {
  67033. _this._currentScene = scene;
  67034. if (_this._sceneLoadedCallback) {
  67035. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  67036. }
  67037. // Wait for textures and shaders to be ready
  67038. _this._currentScene.executeWhenReady(function () {
  67039. _this._engine.runRenderLoop(function () {
  67040. _this.renderFunction();
  67041. });
  67042. });
  67043. }).catch(function (error) {
  67044. if (_this._errorCallback) {
  67045. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  67046. }
  67047. });
  67048. }
  67049. else {
  67050. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  67051. }
  67052. };
  67053. FilesInput.FilesToLoad = {};
  67054. return FilesInput;
  67055. }());
  67056. BABYLON.FilesInput = FilesInput;
  67057. })(BABYLON || (BABYLON = {}));
  67058. //# sourceMappingURL=babylon.filesInput.js.map
  67059. "use strict";
  67060. var BABYLON;
  67061. (function (BABYLON) {
  67062. /**
  67063. * This class implement a typical dictionary using a string as key and the generic type T as value.
  67064. * The underlying implementation relies on an associative array to ensure the best performances.
  67065. * The value can be anything including 'null' but except 'undefined'
  67066. */
  67067. var StringDictionary = /** @class */ (function () {
  67068. function StringDictionary() {
  67069. this._count = 0;
  67070. this._data = {};
  67071. }
  67072. /**
  67073. * This will clear this dictionary and copy the content from the 'source' one.
  67074. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  67075. * @param source the dictionary to take the content from and copy to this dictionary
  67076. */
  67077. StringDictionary.prototype.copyFrom = function (source) {
  67078. var _this = this;
  67079. this.clear();
  67080. source.forEach(function (t, v) { return _this.add(t, v); });
  67081. };
  67082. /**
  67083. * Get a value based from its key
  67084. * @param key the given key to get the matching value from
  67085. * @return the value if found, otherwise undefined is returned
  67086. */
  67087. StringDictionary.prototype.get = function (key) {
  67088. var val = this._data[key];
  67089. if (val !== undefined) {
  67090. return val;
  67091. }
  67092. return undefined;
  67093. };
  67094. /**
  67095. * Get a value from its key or add it if it doesn't exist.
  67096. * This method will ensure you that a given key/data will be present in the dictionary.
  67097. * @param key the given key to get the matching value from
  67098. * @param factory the factory that will create the value if the key is not present in the dictionary.
  67099. * The factory will only be invoked if there's no data for the given key.
  67100. * @return the value corresponding to the key.
  67101. */
  67102. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  67103. var val = this.get(key);
  67104. if (val !== undefined) {
  67105. return val;
  67106. }
  67107. val = factory(key);
  67108. if (val) {
  67109. this.add(key, val);
  67110. }
  67111. return val;
  67112. };
  67113. /**
  67114. * Get a value from its key if present in the dictionary otherwise add it
  67115. * @param key the key to get the value from
  67116. * @param val if there's no such key/value pair in the dictionary add it with this value
  67117. * @return the value corresponding to the key
  67118. */
  67119. StringDictionary.prototype.getOrAdd = function (key, val) {
  67120. var curVal = this.get(key);
  67121. if (curVal !== undefined) {
  67122. return curVal;
  67123. }
  67124. this.add(key, val);
  67125. return val;
  67126. };
  67127. /**
  67128. * Check if there's a given key in the dictionary
  67129. * @param key the key to check for
  67130. * @return true if the key is present, false otherwise
  67131. */
  67132. StringDictionary.prototype.contains = function (key) {
  67133. return this._data[key] !== undefined;
  67134. };
  67135. /**
  67136. * Add a new key and its corresponding value
  67137. * @param key the key to add
  67138. * @param value the value corresponding to the key
  67139. * @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
  67140. */
  67141. StringDictionary.prototype.add = function (key, value) {
  67142. if (this._data[key] !== undefined) {
  67143. return false;
  67144. }
  67145. this._data[key] = value;
  67146. ++this._count;
  67147. return true;
  67148. };
  67149. StringDictionary.prototype.set = function (key, value) {
  67150. if (this._data[key] === undefined) {
  67151. return false;
  67152. }
  67153. this._data[key] = value;
  67154. return true;
  67155. };
  67156. /**
  67157. * Get the element of the given key and remove it from the dictionary
  67158. * @param key
  67159. */
  67160. StringDictionary.prototype.getAndRemove = function (key) {
  67161. var val = this.get(key);
  67162. if (val !== undefined) {
  67163. delete this._data[key];
  67164. --this._count;
  67165. return val;
  67166. }
  67167. return null;
  67168. };
  67169. /**
  67170. * Remove a key/value from the dictionary.
  67171. * @param key the key to remove
  67172. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  67173. */
  67174. StringDictionary.prototype.remove = function (key) {
  67175. if (this.contains(key)) {
  67176. delete this._data[key];
  67177. --this._count;
  67178. return true;
  67179. }
  67180. return false;
  67181. };
  67182. /**
  67183. * Clear the whole content of the dictionary
  67184. */
  67185. StringDictionary.prototype.clear = function () {
  67186. this._data = {};
  67187. this._count = 0;
  67188. };
  67189. Object.defineProperty(StringDictionary.prototype, "count", {
  67190. get: function () {
  67191. return this._count;
  67192. },
  67193. enumerable: true,
  67194. configurable: true
  67195. });
  67196. /**
  67197. * Execute a callback on each key/val of the dictionary.
  67198. * Note that you can remove any element in this dictionary in the callback implementation
  67199. * @param callback the callback to execute on a given key/value pair
  67200. */
  67201. StringDictionary.prototype.forEach = function (callback) {
  67202. for (var cur in this._data) {
  67203. var val = this._data[cur];
  67204. callback(cur, val);
  67205. }
  67206. };
  67207. /**
  67208. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  67209. * If the callback returns null or undefined the method will iterate to the next key/value pair
  67210. * Note that you can remove any element in this dictionary in the callback implementation
  67211. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  67212. */
  67213. StringDictionary.prototype.first = function (callback) {
  67214. for (var cur in this._data) {
  67215. var val = this._data[cur];
  67216. var res = callback(cur, val);
  67217. if (res) {
  67218. return res;
  67219. }
  67220. }
  67221. return null;
  67222. };
  67223. return StringDictionary;
  67224. }());
  67225. BABYLON.StringDictionary = StringDictionary;
  67226. })(BABYLON || (BABYLON = {}));
  67227. //# sourceMappingURL=babylon.stringDictionary.js.map
  67228. "use strict";
  67229. var BABYLON;
  67230. (function (BABYLON) {
  67231. var Tags = /** @class */ (function () {
  67232. function Tags() {
  67233. }
  67234. Tags.EnableFor = function (obj) {
  67235. obj._tags = obj._tags || {};
  67236. obj.hasTags = function () {
  67237. return Tags.HasTags(obj);
  67238. };
  67239. obj.addTags = function (tagsString) {
  67240. return Tags.AddTagsTo(obj, tagsString);
  67241. };
  67242. obj.removeTags = function (tagsString) {
  67243. return Tags.RemoveTagsFrom(obj, tagsString);
  67244. };
  67245. obj.matchesTagsQuery = function (tagsQuery) {
  67246. return Tags.MatchesQuery(obj, tagsQuery);
  67247. };
  67248. };
  67249. Tags.DisableFor = function (obj) {
  67250. delete obj._tags;
  67251. delete obj.hasTags;
  67252. delete obj.addTags;
  67253. delete obj.removeTags;
  67254. delete obj.matchesTagsQuery;
  67255. };
  67256. Tags.HasTags = function (obj) {
  67257. if (!obj._tags) {
  67258. return false;
  67259. }
  67260. return !BABYLON.Tools.IsEmpty(obj._tags);
  67261. };
  67262. Tags.GetTags = function (obj, asString) {
  67263. if (asString === void 0) { asString = true; }
  67264. if (!obj._tags) {
  67265. return null;
  67266. }
  67267. if (asString) {
  67268. var tagsArray = [];
  67269. for (var tag in obj._tags) {
  67270. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  67271. tagsArray.push(tag);
  67272. }
  67273. }
  67274. return tagsArray.join(" ");
  67275. }
  67276. else {
  67277. return obj._tags;
  67278. }
  67279. };
  67280. // the tags 'true' and 'false' are reserved and cannot be used as tags
  67281. // a tag cannot start with '||', '&&', and '!'
  67282. // it cannot contain whitespaces
  67283. Tags.AddTagsTo = function (obj, tagsString) {
  67284. if (!tagsString) {
  67285. return;
  67286. }
  67287. if (typeof tagsString !== "string") {
  67288. return;
  67289. }
  67290. var tags = tagsString.split(" ");
  67291. tags.forEach(function (tag, index, array) {
  67292. Tags._AddTagTo(obj, tag);
  67293. });
  67294. };
  67295. Tags._AddTagTo = function (obj, tag) {
  67296. tag = tag.trim();
  67297. if (tag === "" || tag === "true" || tag === "false") {
  67298. return;
  67299. }
  67300. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  67301. return;
  67302. }
  67303. Tags.EnableFor(obj);
  67304. obj._tags[tag] = true;
  67305. };
  67306. Tags.RemoveTagsFrom = function (obj, tagsString) {
  67307. if (!Tags.HasTags(obj)) {
  67308. return;
  67309. }
  67310. var tags = tagsString.split(" ");
  67311. for (var t in tags) {
  67312. Tags._RemoveTagFrom(obj, tags[t]);
  67313. }
  67314. };
  67315. Tags._RemoveTagFrom = function (obj, tag) {
  67316. delete obj._tags[tag];
  67317. };
  67318. Tags.MatchesQuery = function (obj, tagsQuery) {
  67319. if (tagsQuery === undefined) {
  67320. return true;
  67321. }
  67322. if (tagsQuery === "") {
  67323. return Tags.HasTags(obj);
  67324. }
  67325. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  67326. };
  67327. return Tags;
  67328. }());
  67329. BABYLON.Tags = Tags;
  67330. })(BABYLON || (BABYLON = {}));
  67331. //# sourceMappingURL=babylon.tags.js.map
  67332. "use strict";
  67333. var BABYLON;
  67334. (function (BABYLON) {
  67335. var AndOrNotEvaluator = /** @class */ (function () {
  67336. function AndOrNotEvaluator() {
  67337. }
  67338. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  67339. if (!query.match(/\([^\(\)]*\)/g)) {
  67340. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  67341. }
  67342. else {
  67343. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  67344. // remove parenthesis
  67345. r = r.slice(1, r.length - 1);
  67346. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  67347. });
  67348. }
  67349. if (query === "true") {
  67350. return true;
  67351. }
  67352. if (query === "false") {
  67353. return false;
  67354. }
  67355. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  67356. };
  67357. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  67358. evaluateCallback = evaluateCallback || (function (r) {
  67359. return r === "true" ? true : false;
  67360. });
  67361. var result;
  67362. var or = parenthesisContent.split("||");
  67363. for (var i in or) {
  67364. if (or.hasOwnProperty(i)) {
  67365. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  67366. var and = ori.split("&&");
  67367. if (and.length > 1) {
  67368. for (var j = 0; j < and.length; ++j) {
  67369. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  67370. if (andj !== "true" && andj !== "false") {
  67371. if (andj[0] === "!") {
  67372. result = !evaluateCallback(andj.substring(1));
  67373. }
  67374. else {
  67375. result = evaluateCallback(andj);
  67376. }
  67377. }
  67378. else {
  67379. result = andj === "true" ? true : false;
  67380. }
  67381. if (!result) {
  67382. ori = "false";
  67383. break;
  67384. }
  67385. }
  67386. }
  67387. if (result || ori === "true") {
  67388. result = true;
  67389. break;
  67390. }
  67391. // result equals false (or undefined)
  67392. if (ori !== "true" && ori !== "false") {
  67393. if (ori[0] === "!") {
  67394. result = !evaluateCallback(ori.substring(1));
  67395. }
  67396. else {
  67397. result = evaluateCallback(ori);
  67398. }
  67399. }
  67400. else {
  67401. result = ori === "true" ? true : false;
  67402. }
  67403. }
  67404. }
  67405. // the whole parenthesis scope is replaced by 'true' or 'false'
  67406. return result ? "true" : "false";
  67407. };
  67408. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  67409. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  67410. // remove whitespaces
  67411. r = r.replace(/[\s]/g, function () { return ""; });
  67412. return r.length % 2 ? "!" : "";
  67413. });
  67414. booleanString = booleanString.trim();
  67415. if (booleanString === "!true") {
  67416. booleanString = "false";
  67417. }
  67418. else if (booleanString === "!false") {
  67419. booleanString = "true";
  67420. }
  67421. return booleanString;
  67422. };
  67423. return AndOrNotEvaluator;
  67424. }());
  67425. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  67426. })(BABYLON || (BABYLON = {}));
  67427. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  67428. "use strict";
  67429. var BABYLON;
  67430. (function (BABYLON) {
  67431. var Database = /** @class */ (function () {
  67432. function Database(urlToScene, callbackManifestChecked) {
  67433. // Handling various flavors of prefixed version of IndexedDB
  67434. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  67435. this.callbackManifestChecked = callbackManifestChecked;
  67436. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  67437. this.db = null;
  67438. this._enableSceneOffline = false;
  67439. this._enableTexturesOffline = false;
  67440. this.manifestVersionFound = 0;
  67441. this.mustUpdateRessources = false;
  67442. this.hasReachedQuota = false;
  67443. if (!Database.IDBStorageEnabled) {
  67444. this.callbackManifestChecked(true);
  67445. }
  67446. else {
  67447. this.checkManifestFile();
  67448. }
  67449. }
  67450. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  67451. get: function () {
  67452. return this._enableSceneOffline;
  67453. },
  67454. enumerable: true,
  67455. configurable: true
  67456. });
  67457. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  67458. get: function () {
  67459. return this._enableTexturesOffline;
  67460. },
  67461. enumerable: true,
  67462. configurable: true
  67463. });
  67464. Database.prototype.checkManifestFile = function () {
  67465. var _this = this;
  67466. var noManifestFile = function () {
  67467. _this._enableSceneOffline = false;
  67468. _this._enableTexturesOffline = false;
  67469. _this.callbackManifestChecked(false);
  67470. };
  67471. var timeStampUsed = false;
  67472. var manifestURL = this.currentSceneUrl + ".manifest";
  67473. var xhr = new XMLHttpRequest();
  67474. if (navigator.onLine) {
  67475. // Adding a timestamp to by-pass browsers' cache
  67476. timeStampUsed = true;
  67477. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  67478. }
  67479. xhr.open("GET", manifestURL, true);
  67480. xhr.addEventListener("load", function () {
  67481. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  67482. try {
  67483. var manifestFile = JSON.parse(xhr.response);
  67484. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  67485. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  67486. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  67487. _this.manifestVersionFound = manifestFile.version;
  67488. }
  67489. if (_this.callbackManifestChecked) {
  67490. _this.callbackManifestChecked(true);
  67491. }
  67492. }
  67493. catch (ex) {
  67494. noManifestFile();
  67495. }
  67496. }
  67497. else {
  67498. noManifestFile();
  67499. }
  67500. }, false);
  67501. xhr.addEventListener("error", function (event) {
  67502. if (timeStampUsed) {
  67503. timeStampUsed = false;
  67504. // Let's retry without the timeStamp
  67505. // It could fail when coupled with HTML5 Offline API
  67506. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  67507. xhr.open("GET", retryManifestURL, true);
  67508. xhr.send();
  67509. }
  67510. else {
  67511. noManifestFile();
  67512. }
  67513. }, false);
  67514. try {
  67515. xhr.send();
  67516. }
  67517. catch (ex) {
  67518. BABYLON.Tools.Error("Error on XHR send request.");
  67519. this.callbackManifestChecked(false);
  67520. }
  67521. };
  67522. Database.prototype.openAsync = function (successCallback, errorCallback) {
  67523. var _this = this;
  67524. var handleError = function () {
  67525. _this.isSupported = false;
  67526. if (errorCallback)
  67527. errorCallback();
  67528. };
  67529. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  67530. // Your browser doesn't support IndexedDB
  67531. this.isSupported = false;
  67532. if (errorCallback)
  67533. errorCallback();
  67534. }
  67535. else {
  67536. // If the DB hasn't been opened or created yet
  67537. if (!this.db) {
  67538. this.hasReachedQuota = false;
  67539. this.isSupported = true;
  67540. var request = this.idbFactory.open("babylonjs", 1);
  67541. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  67542. request.onerror = function (event) {
  67543. handleError();
  67544. };
  67545. // executes when a version change transaction cannot complete due to other active transactions
  67546. request.onblocked = function (event) {
  67547. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  67548. handleError();
  67549. };
  67550. // DB has been opened successfully
  67551. request.onsuccess = function (event) {
  67552. _this.db = request.result;
  67553. successCallback();
  67554. };
  67555. // Initialization of the DB. Creating Scenes & Textures stores
  67556. request.onupgradeneeded = function (event) {
  67557. _this.db = (event.target).result;
  67558. if (_this.db) {
  67559. try {
  67560. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  67561. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  67562. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  67563. }
  67564. catch (ex) {
  67565. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  67566. handleError();
  67567. }
  67568. }
  67569. };
  67570. }
  67571. else {
  67572. if (successCallback)
  67573. successCallback();
  67574. }
  67575. }
  67576. };
  67577. Database.prototype.loadImageFromDB = function (url, image) {
  67578. var _this = this;
  67579. var completeURL = Database.ReturnFullUrlLocation(url);
  67580. var saveAndLoadImage = function () {
  67581. if (!_this.hasReachedQuota && _this.db !== null) {
  67582. // the texture is not yet in the DB, let's try to save it
  67583. _this._saveImageIntoDBAsync(completeURL, image);
  67584. }
  67585. else {
  67586. image.src = url;
  67587. }
  67588. };
  67589. if (!this.mustUpdateRessources) {
  67590. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  67591. }
  67592. else {
  67593. saveAndLoadImage();
  67594. }
  67595. };
  67596. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  67597. if (this.isSupported && this.db !== null) {
  67598. var texture;
  67599. var transaction = this.db.transaction(["textures"]);
  67600. transaction.onabort = function (event) {
  67601. image.src = url;
  67602. };
  67603. transaction.oncomplete = function (event) {
  67604. var blobTextureURL;
  67605. if (texture) {
  67606. var URL = window.URL || window.webkitURL;
  67607. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  67608. image.onerror = function () {
  67609. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  67610. image.src = url;
  67611. };
  67612. image.src = blobTextureURL;
  67613. }
  67614. else {
  67615. notInDBCallback();
  67616. }
  67617. };
  67618. var getRequest = transaction.objectStore("textures").get(url);
  67619. getRequest.onsuccess = function (event) {
  67620. texture = (event.target).result;
  67621. };
  67622. getRequest.onerror = function (event) {
  67623. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  67624. image.src = url;
  67625. };
  67626. }
  67627. else {
  67628. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67629. image.src = url;
  67630. }
  67631. };
  67632. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  67633. var _this = this;
  67634. if (this.isSupported) {
  67635. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  67636. var generateBlobUrl = function () {
  67637. var blobTextureURL;
  67638. if (blob) {
  67639. var URL = window.URL || window.webkitURL;
  67640. try {
  67641. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  67642. }
  67643. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  67644. catch (ex) {
  67645. blobTextureURL = URL.createObjectURL(blob);
  67646. }
  67647. }
  67648. if (blobTextureURL) {
  67649. image.src = blobTextureURL;
  67650. }
  67651. };
  67652. if (Database.IsUASupportingBlobStorage) {
  67653. var xhr = new XMLHttpRequest(), blob;
  67654. xhr.open("GET", url, true);
  67655. xhr.responseType = "blob";
  67656. xhr.addEventListener("load", function () {
  67657. if (xhr.status === 200 && _this.db) {
  67658. // Blob as response (XHR2)
  67659. blob = xhr.response;
  67660. var transaction = _this.db.transaction(["textures"], "readwrite");
  67661. // the transaction could abort because of a QuotaExceededError error
  67662. transaction.onabort = function (event) {
  67663. try {
  67664. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  67665. var srcElement = (event.srcElement || event.target);
  67666. var error = srcElement.error;
  67667. if (error && error.name === "QuotaExceededError") {
  67668. _this.hasReachedQuota = true;
  67669. }
  67670. }
  67671. catch (ex) { }
  67672. generateBlobUrl();
  67673. };
  67674. transaction.oncomplete = function (event) {
  67675. generateBlobUrl();
  67676. };
  67677. var newTexture = { textureUrl: url, data: blob };
  67678. try {
  67679. // Put the blob into the dabase
  67680. var addRequest = transaction.objectStore("textures").put(newTexture);
  67681. addRequest.onsuccess = function (event) {
  67682. };
  67683. addRequest.onerror = function (event) {
  67684. generateBlobUrl();
  67685. };
  67686. }
  67687. catch (ex) {
  67688. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  67689. if (ex.code === 25) {
  67690. Database.IsUASupportingBlobStorage = false;
  67691. }
  67692. image.src = url;
  67693. }
  67694. }
  67695. else {
  67696. image.src = url;
  67697. }
  67698. }, false);
  67699. xhr.addEventListener("error", function (event) {
  67700. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  67701. image.src = url;
  67702. }, false);
  67703. xhr.send();
  67704. }
  67705. else {
  67706. image.src = url;
  67707. }
  67708. }
  67709. else {
  67710. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67711. image.src = url;
  67712. }
  67713. };
  67714. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  67715. var _this = this;
  67716. var updateVersion = function () {
  67717. // the version is not yet in the DB or we need to update it
  67718. _this._saveVersionIntoDBAsync(url, versionLoaded);
  67719. };
  67720. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  67721. };
  67722. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  67723. var _this = this;
  67724. if (this.isSupported && this.db) {
  67725. var version;
  67726. try {
  67727. var transaction = this.db.transaction(["versions"]);
  67728. transaction.oncomplete = function (event) {
  67729. if (version) {
  67730. // If the version in the JSON file is > than the version in DB
  67731. if (_this.manifestVersionFound > version.data) {
  67732. _this.mustUpdateRessources = true;
  67733. updateInDBCallback();
  67734. }
  67735. else {
  67736. callback(version.data);
  67737. }
  67738. }
  67739. else {
  67740. _this.mustUpdateRessources = true;
  67741. updateInDBCallback();
  67742. }
  67743. };
  67744. transaction.onabort = function (event) {
  67745. callback(-1);
  67746. };
  67747. var getRequest = transaction.objectStore("versions").get(url);
  67748. getRequest.onsuccess = function (event) {
  67749. version = (event.target).result;
  67750. };
  67751. getRequest.onerror = function (event) {
  67752. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  67753. callback(-1);
  67754. };
  67755. }
  67756. catch (ex) {
  67757. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  67758. callback(-1);
  67759. }
  67760. }
  67761. else {
  67762. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67763. callback(-1);
  67764. }
  67765. };
  67766. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  67767. var _this = this;
  67768. if (this.isSupported && !this.hasReachedQuota && this.db) {
  67769. try {
  67770. // Open a transaction to the database
  67771. var transaction = this.db.transaction(["versions"], "readwrite");
  67772. // the transaction could abort because of a QuotaExceededError error
  67773. transaction.onabort = function (event) {
  67774. try {
  67775. var error = event.srcElement['error'];
  67776. if (error && error.name === "QuotaExceededError") {
  67777. _this.hasReachedQuota = true;
  67778. }
  67779. }
  67780. catch (ex) { }
  67781. callback(-1);
  67782. };
  67783. transaction.oncomplete = function (event) {
  67784. callback(_this.manifestVersionFound);
  67785. };
  67786. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  67787. // Put the scene into the database
  67788. var addRequest = transaction.objectStore("versions").put(newVersion);
  67789. addRequest.onsuccess = function (event) {
  67790. };
  67791. addRequest.onerror = function (event) {
  67792. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  67793. };
  67794. }
  67795. catch (ex) {
  67796. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  67797. callback(-1);
  67798. }
  67799. }
  67800. else {
  67801. callback(-1);
  67802. }
  67803. };
  67804. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  67805. var _this = this;
  67806. var completeUrl = Database.ReturnFullUrlLocation(url);
  67807. var saveAndLoadFile = function () {
  67808. // the scene is not yet in the DB, let's try to save it
  67809. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  67810. };
  67811. this._checkVersionFromDB(completeUrl, function (version) {
  67812. if (version !== -1) {
  67813. if (!_this.mustUpdateRessources) {
  67814. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  67815. }
  67816. else {
  67817. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  67818. }
  67819. }
  67820. else {
  67821. if (errorCallback) {
  67822. errorCallback();
  67823. }
  67824. }
  67825. });
  67826. };
  67827. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  67828. if (this.isSupported && this.db) {
  67829. var targetStore;
  67830. if (url.indexOf(".babylon") !== -1) {
  67831. targetStore = "scenes";
  67832. }
  67833. else {
  67834. targetStore = "textures";
  67835. }
  67836. var file;
  67837. var transaction = this.db.transaction([targetStore]);
  67838. transaction.oncomplete = function (event) {
  67839. if (file) {
  67840. callback(file.data);
  67841. }
  67842. else {
  67843. notInDBCallback();
  67844. }
  67845. };
  67846. transaction.onabort = function (event) {
  67847. notInDBCallback();
  67848. };
  67849. var getRequest = transaction.objectStore(targetStore).get(url);
  67850. getRequest.onsuccess = function (event) {
  67851. file = (event.target).result;
  67852. };
  67853. getRequest.onerror = function (event) {
  67854. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  67855. notInDBCallback();
  67856. };
  67857. }
  67858. else {
  67859. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67860. callback();
  67861. }
  67862. };
  67863. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  67864. var _this = this;
  67865. if (this.isSupported) {
  67866. var targetStore;
  67867. if (url.indexOf(".babylon") !== -1) {
  67868. targetStore = "scenes";
  67869. }
  67870. else {
  67871. targetStore = "textures";
  67872. }
  67873. // Create XHR
  67874. var xhr = new XMLHttpRequest();
  67875. var fileData;
  67876. xhr.open("GET", url, true);
  67877. if (useArrayBuffer) {
  67878. xhr.responseType = "arraybuffer";
  67879. }
  67880. if (progressCallback) {
  67881. xhr.onprogress = progressCallback;
  67882. }
  67883. xhr.addEventListener("load", function () {
  67884. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  67885. // Blob as response (XHR2)
  67886. //fileData = xhr.responseText;
  67887. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  67888. if (!_this.hasReachedQuota && _this.db) {
  67889. // Open a transaction to the database
  67890. var transaction = _this.db.transaction([targetStore], "readwrite");
  67891. // the transaction could abort because of a QuotaExceededError error
  67892. transaction.onabort = function (event) {
  67893. try {
  67894. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  67895. var error = event.srcElement['error'];
  67896. if (error && error.name === "QuotaExceededError") {
  67897. _this.hasReachedQuota = true;
  67898. }
  67899. }
  67900. catch (ex) { }
  67901. callback(fileData);
  67902. };
  67903. transaction.oncomplete = function (event) {
  67904. callback(fileData);
  67905. };
  67906. var newFile;
  67907. if (targetStore === "scenes") {
  67908. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  67909. }
  67910. else {
  67911. newFile = { textureUrl: url, data: fileData };
  67912. }
  67913. try {
  67914. // Put the scene into the database
  67915. var addRequest = transaction.objectStore(targetStore).put(newFile);
  67916. addRequest.onsuccess = function (event) {
  67917. };
  67918. addRequest.onerror = function (event) {
  67919. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  67920. };
  67921. }
  67922. catch (ex) {
  67923. callback(fileData);
  67924. }
  67925. }
  67926. else {
  67927. callback(fileData);
  67928. }
  67929. }
  67930. else {
  67931. callback();
  67932. }
  67933. }, false);
  67934. xhr.addEventListener("error", function (event) {
  67935. BABYLON.Tools.Error("error on XHR request.");
  67936. callback();
  67937. }, false);
  67938. xhr.send();
  67939. }
  67940. else {
  67941. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67942. callback();
  67943. }
  67944. };
  67945. Database.IsUASupportingBlobStorage = true;
  67946. Database.IDBStorageEnabled = true;
  67947. Database.parseURL = function (url) {
  67948. var a = document.createElement('a');
  67949. a.href = url;
  67950. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  67951. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  67952. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  67953. return absLocation;
  67954. };
  67955. Database.ReturnFullUrlLocation = function (url) {
  67956. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  67957. return (Database.parseURL(window.location.href) + url);
  67958. }
  67959. else {
  67960. return url;
  67961. }
  67962. };
  67963. return Database;
  67964. }());
  67965. BABYLON.Database = Database;
  67966. })(BABYLON || (BABYLON = {}));
  67967. //# sourceMappingURL=babylon.database.js.map
  67968. "use strict";
  67969. var BABYLON;
  67970. (function (BABYLON) {
  67971. var FresnelParameters = /** @class */ (function () {
  67972. function FresnelParameters() {
  67973. this._isEnabled = true;
  67974. this.leftColor = BABYLON.Color3.White();
  67975. this.rightColor = BABYLON.Color3.Black();
  67976. this.bias = 0;
  67977. this.power = 1;
  67978. }
  67979. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  67980. get: function () {
  67981. return this._isEnabled;
  67982. },
  67983. set: function (value) {
  67984. if (this._isEnabled === value) {
  67985. return;
  67986. }
  67987. this._isEnabled = value;
  67988. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  67989. },
  67990. enumerable: true,
  67991. configurable: true
  67992. });
  67993. FresnelParameters.prototype.clone = function () {
  67994. var newFresnelParameters = new FresnelParameters();
  67995. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  67996. return newFresnelParameters;
  67997. };
  67998. FresnelParameters.prototype.serialize = function () {
  67999. var serializationObject = {};
  68000. serializationObject.isEnabled = this.isEnabled;
  68001. serializationObject.leftColor = this.leftColor.asArray();
  68002. serializationObject.rightColor = this.rightColor.asArray();
  68003. serializationObject.bias = this.bias;
  68004. serializationObject.power = this.power;
  68005. return serializationObject;
  68006. };
  68007. FresnelParameters.Parse = function (parsedFresnelParameters) {
  68008. var fresnelParameters = new FresnelParameters();
  68009. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  68010. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  68011. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  68012. fresnelParameters.bias = parsedFresnelParameters.bias;
  68013. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  68014. return fresnelParameters;
  68015. };
  68016. return FresnelParameters;
  68017. }());
  68018. BABYLON.FresnelParameters = FresnelParameters;
  68019. })(BABYLON || (BABYLON = {}));
  68020. //# sourceMappingURL=babylon.fresnelParameters.js.map
  68021. "use strict";
  68022. var BABYLON;
  68023. (function (BABYLON) {
  68024. var MultiMaterial = /** @class */ (function (_super) {
  68025. __extends(MultiMaterial, _super);
  68026. function MultiMaterial(name, scene) {
  68027. var _this = _super.call(this, name, scene, true) || this;
  68028. scene.multiMaterials.push(_this);
  68029. _this.subMaterials = new Array();
  68030. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  68031. return _this;
  68032. }
  68033. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  68034. get: function () {
  68035. return this._subMaterials;
  68036. },
  68037. set: function (value) {
  68038. this._subMaterials = value;
  68039. this._hookArray(value);
  68040. },
  68041. enumerable: true,
  68042. configurable: true
  68043. });
  68044. MultiMaterial.prototype._hookArray = function (array) {
  68045. var _this = this;
  68046. var oldPush = array.push;
  68047. array.push = function () {
  68048. var items = [];
  68049. for (var _i = 0; _i < arguments.length; _i++) {
  68050. items[_i] = arguments[_i];
  68051. }
  68052. var result = oldPush.apply(array, items);
  68053. _this._markAllSubMeshesAsTexturesDirty();
  68054. return result;
  68055. };
  68056. var oldSplice = array.splice;
  68057. array.splice = function (index, deleteCount) {
  68058. var deleted = oldSplice.apply(array, [index, deleteCount]);
  68059. _this._markAllSubMeshesAsTexturesDirty();
  68060. return deleted;
  68061. };
  68062. };
  68063. // Properties
  68064. MultiMaterial.prototype.getSubMaterial = function (index) {
  68065. if (index < 0 || index >= this.subMaterials.length) {
  68066. return this.getScene().defaultMaterial;
  68067. }
  68068. return this.subMaterials[index];
  68069. };
  68070. MultiMaterial.prototype.getActiveTextures = function () {
  68071. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  68072. if (subMaterial) {
  68073. return subMaterial.getActiveTextures();
  68074. }
  68075. else {
  68076. return [];
  68077. }
  68078. }));
  68079. var _a;
  68080. };
  68081. // Methods
  68082. MultiMaterial.prototype.getClassName = function () {
  68083. return "MultiMaterial";
  68084. };
  68085. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  68086. for (var index = 0; index < this.subMaterials.length; index++) {
  68087. var subMaterial = this.subMaterials[index];
  68088. if (subMaterial) {
  68089. if (subMaterial.storeEffectOnSubMeshes) {
  68090. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  68091. return false;
  68092. }
  68093. continue;
  68094. }
  68095. if (!subMaterial.isReady(mesh)) {
  68096. return false;
  68097. }
  68098. }
  68099. }
  68100. return true;
  68101. };
  68102. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  68103. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  68104. for (var index = 0; index < this.subMaterials.length; index++) {
  68105. var subMaterial = null;
  68106. var current = this.subMaterials[index];
  68107. if (cloneChildren && current) {
  68108. subMaterial = current.clone(name + "-" + current.name);
  68109. }
  68110. else {
  68111. subMaterial = this.subMaterials[index];
  68112. }
  68113. newMultiMaterial.subMaterials.push(subMaterial);
  68114. }
  68115. return newMultiMaterial;
  68116. };
  68117. MultiMaterial.prototype.serialize = function () {
  68118. var serializationObject = {};
  68119. serializationObject.name = this.name;
  68120. serializationObject.id = this.id;
  68121. if (BABYLON.Tags) {
  68122. serializationObject.tags = BABYLON.Tags.GetTags(this);
  68123. }
  68124. serializationObject.materials = [];
  68125. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  68126. var subMat = this.subMaterials[matIndex];
  68127. if (subMat) {
  68128. serializationObject.materials.push(subMat.id);
  68129. }
  68130. else {
  68131. serializationObject.materials.push(null);
  68132. }
  68133. }
  68134. return serializationObject;
  68135. };
  68136. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  68137. var scene = this.getScene();
  68138. if (!scene) {
  68139. return;
  68140. }
  68141. var index = scene.multiMaterials.indexOf(this);
  68142. if (index >= 0) {
  68143. scene.multiMaterials.splice(index, 1);
  68144. }
  68145. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  68146. };
  68147. return MultiMaterial;
  68148. }(BABYLON.Material));
  68149. BABYLON.MultiMaterial = MultiMaterial;
  68150. })(BABYLON || (BABYLON = {}));
  68151. //# sourceMappingURL=babylon.multiMaterial.js.map
  68152. "use strict";
  68153. var BABYLON;
  68154. (function (BABYLON) {
  68155. var FreeCameraTouchInput = /** @class */ (function () {
  68156. function FreeCameraTouchInput() {
  68157. this._offsetX = null;
  68158. this._offsetY = null;
  68159. this._pointerPressed = new Array();
  68160. this.touchAngularSensibility = 200000.0;
  68161. this.touchMoveSensibility = 250.0;
  68162. }
  68163. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  68164. var _this = this;
  68165. var previousPosition = null;
  68166. if (this._pointerInput === undefined) {
  68167. this._onLostFocus = function (evt) {
  68168. _this._offsetX = null;
  68169. _this._offsetY = null;
  68170. };
  68171. this._pointerInput = function (p, s) {
  68172. var evt = p.event;
  68173. if (evt.pointerType === "mouse") {
  68174. return;
  68175. }
  68176. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  68177. if (!noPreventDefault) {
  68178. evt.preventDefault();
  68179. }
  68180. _this._pointerPressed.push(evt.pointerId);
  68181. if (_this._pointerPressed.length !== 1) {
  68182. return;
  68183. }
  68184. previousPosition = {
  68185. x: evt.clientX,
  68186. y: evt.clientY
  68187. };
  68188. }
  68189. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  68190. if (!noPreventDefault) {
  68191. evt.preventDefault();
  68192. }
  68193. var index = _this._pointerPressed.indexOf(evt.pointerId);
  68194. if (index === -1) {
  68195. return;
  68196. }
  68197. _this._pointerPressed.splice(index, 1);
  68198. if (index != 0) {
  68199. return;
  68200. }
  68201. previousPosition = null;
  68202. _this._offsetX = null;
  68203. _this._offsetY = null;
  68204. }
  68205. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  68206. if (!noPreventDefault) {
  68207. evt.preventDefault();
  68208. }
  68209. if (!previousPosition) {
  68210. return;
  68211. }
  68212. var index = _this._pointerPressed.indexOf(evt.pointerId);
  68213. if (index != 0) {
  68214. return;
  68215. }
  68216. _this._offsetX = evt.clientX - previousPosition.x;
  68217. _this._offsetY = -(evt.clientY - previousPosition.y);
  68218. }
  68219. };
  68220. }
  68221. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  68222. if (this._onLostFocus) {
  68223. element.addEventListener("blur", this._onLostFocus);
  68224. }
  68225. };
  68226. FreeCameraTouchInput.prototype.detachControl = function (element) {
  68227. if (this._pointerInput && element) {
  68228. if (this._observer) {
  68229. this.camera.getScene().onPointerObservable.remove(this._observer);
  68230. this._observer = null;
  68231. }
  68232. if (this._onLostFocus) {
  68233. element.removeEventListener("blur", this._onLostFocus);
  68234. this._onLostFocus = null;
  68235. }
  68236. this._pointerPressed = [];
  68237. this._offsetX = null;
  68238. this._offsetY = null;
  68239. }
  68240. };
  68241. FreeCameraTouchInput.prototype.checkInputs = function () {
  68242. if (this._offsetX && this._offsetY) {
  68243. var camera = this.camera;
  68244. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  68245. if (this._pointerPressed.length > 1) {
  68246. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  68247. }
  68248. else {
  68249. var speed = camera._computeLocalCameraSpeed();
  68250. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  68251. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  68252. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  68253. }
  68254. }
  68255. };
  68256. FreeCameraTouchInput.prototype.getClassName = function () {
  68257. return "FreeCameraTouchInput";
  68258. };
  68259. FreeCameraTouchInput.prototype.getSimpleName = function () {
  68260. return "touch";
  68261. };
  68262. __decorate([
  68263. BABYLON.serialize()
  68264. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  68265. __decorate([
  68266. BABYLON.serialize()
  68267. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  68268. return FreeCameraTouchInput;
  68269. }());
  68270. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  68271. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  68272. })(BABYLON || (BABYLON = {}));
  68273. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  68274. "use strict";
  68275. var BABYLON;
  68276. (function (BABYLON) {
  68277. // We're mainly based on the logic defined into the FreeCamera code
  68278. var TouchCamera = /** @class */ (function (_super) {
  68279. __extends(TouchCamera, _super);
  68280. //-- end properties for backward compatibility for inputs
  68281. function TouchCamera(name, position, scene) {
  68282. var _this = _super.call(this, name, position, scene) || this;
  68283. _this.inputs.addTouch();
  68284. _this._setupInputs();
  68285. return _this;
  68286. }
  68287. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  68288. //-- Begin properties for backward compatibility for inputs
  68289. get: function () {
  68290. var touch = this.inputs.attached["touch"];
  68291. if (touch)
  68292. return touch.touchAngularSensibility;
  68293. return 0;
  68294. },
  68295. set: function (value) {
  68296. var touch = this.inputs.attached["touch"];
  68297. if (touch)
  68298. touch.touchAngularSensibility = value;
  68299. },
  68300. enumerable: true,
  68301. configurable: true
  68302. });
  68303. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  68304. get: function () {
  68305. var touch = this.inputs.attached["touch"];
  68306. if (touch)
  68307. return touch.touchMoveSensibility;
  68308. return 0;
  68309. },
  68310. set: function (value) {
  68311. var touch = this.inputs.attached["touch"];
  68312. if (touch)
  68313. touch.touchMoveSensibility = value;
  68314. },
  68315. enumerable: true,
  68316. configurable: true
  68317. });
  68318. TouchCamera.prototype.getClassName = function () {
  68319. return "TouchCamera";
  68320. };
  68321. TouchCamera.prototype._setupInputs = function () {
  68322. var mouse = this.inputs.attached["mouse"];
  68323. if (mouse) {
  68324. mouse.touchEnabled = false;
  68325. }
  68326. };
  68327. return TouchCamera;
  68328. }(BABYLON.FreeCamera));
  68329. BABYLON.TouchCamera = TouchCamera;
  68330. })(BABYLON || (BABYLON = {}));
  68331. //# sourceMappingURL=babylon.touchCamera.js.map
  68332. "use strict";
  68333. var BABYLON;
  68334. (function (BABYLON) {
  68335. var ProceduralTexture = /** @class */ (function (_super) {
  68336. __extends(ProceduralTexture, _super);
  68337. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  68338. if (fallbackTexture === void 0) { fallbackTexture = null; }
  68339. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68340. if (isCube === void 0) { isCube = false; }
  68341. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  68342. _this.isCube = isCube;
  68343. _this.isEnabled = true;
  68344. _this._currentRefreshId = -1;
  68345. _this._refreshRate = 1;
  68346. _this._vertexBuffers = {};
  68347. _this._uniforms = new Array();
  68348. _this._samplers = new Array();
  68349. _this._textures = {};
  68350. _this._floats = {};
  68351. _this._floatsArrays = {};
  68352. _this._colors3 = {};
  68353. _this._colors4 = {};
  68354. _this._vectors2 = {};
  68355. _this._vectors3 = {};
  68356. _this._matrices = {};
  68357. _this._fallbackTextureUsed = false;
  68358. scene.proceduralTextures.push(_this);
  68359. _this._engine = scene.getEngine();
  68360. _this.name = name;
  68361. _this.isRenderTarget = true;
  68362. _this._size = size;
  68363. _this._generateMipMaps = generateMipMaps;
  68364. _this.setFragment(fragment);
  68365. _this._fallbackTexture = fallbackTexture;
  68366. if (isCube) {
  68367. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  68368. _this.setFloat("face", 0);
  68369. }
  68370. else {
  68371. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  68372. }
  68373. // VBO
  68374. var vertices = [];
  68375. vertices.push(1, 1);
  68376. vertices.push(-1, 1);
  68377. vertices.push(-1, -1);
  68378. vertices.push(1, -1);
  68379. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68380. _this._createIndexBuffer();
  68381. return _this;
  68382. }
  68383. ProceduralTexture.prototype._createIndexBuffer = function () {
  68384. var engine = this._engine;
  68385. // Indices
  68386. var indices = [];
  68387. indices.push(0);
  68388. indices.push(1);
  68389. indices.push(2);
  68390. indices.push(0);
  68391. indices.push(2);
  68392. indices.push(3);
  68393. this._indexBuffer = engine.createIndexBuffer(indices);
  68394. };
  68395. ProceduralTexture.prototype._rebuild = function () {
  68396. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68397. if (vb) {
  68398. vb._rebuild();
  68399. }
  68400. this._createIndexBuffer();
  68401. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  68402. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  68403. }
  68404. };
  68405. ProceduralTexture.prototype.reset = function () {
  68406. if (this._effect === undefined) {
  68407. return;
  68408. }
  68409. var engine = this._engine;
  68410. engine._releaseEffect(this._effect);
  68411. };
  68412. ProceduralTexture.prototype.isReady = function () {
  68413. var _this = this;
  68414. var engine = this._engine;
  68415. var shaders;
  68416. if (!this._fragment) {
  68417. return false;
  68418. }
  68419. if (this._fallbackTextureUsed) {
  68420. return true;
  68421. }
  68422. if (this._fragment.fragmentElement !== undefined) {
  68423. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  68424. }
  68425. else {
  68426. shaders = { vertex: "procedural", fragment: this._fragment };
  68427. }
  68428. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  68429. _this.releaseInternalTexture();
  68430. if (_this._fallbackTexture) {
  68431. _this._texture = _this._fallbackTexture._texture;
  68432. if (_this._texture) {
  68433. _this._texture.incrementReferences();
  68434. }
  68435. }
  68436. _this._fallbackTextureUsed = true;
  68437. });
  68438. return this._effect.isReady();
  68439. };
  68440. ProceduralTexture.prototype.resetRefreshCounter = function () {
  68441. this._currentRefreshId = -1;
  68442. };
  68443. ProceduralTexture.prototype.setFragment = function (fragment) {
  68444. this._fragment = fragment;
  68445. };
  68446. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  68447. get: function () {
  68448. return this._refreshRate;
  68449. },
  68450. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  68451. set: function (value) {
  68452. this._refreshRate = value;
  68453. this.resetRefreshCounter();
  68454. },
  68455. enumerable: true,
  68456. configurable: true
  68457. });
  68458. ProceduralTexture.prototype._shouldRender = function () {
  68459. if (!this.isEnabled || !this.isReady() || !this._texture) {
  68460. return false;
  68461. }
  68462. if (this._fallbackTextureUsed) {
  68463. return false;
  68464. }
  68465. if (this._currentRefreshId === -1) {
  68466. this._currentRefreshId = 1;
  68467. return true;
  68468. }
  68469. if (this.refreshRate === this._currentRefreshId) {
  68470. this._currentRefreshId = 1;
  68471. return true;
  68472. }
  68473. this._currentRefreshId++;
  68474. return false;
  68475. };
  68476. ProceduralTexture.prototype.getRenderSize = function () {
  68477. return this._size;
  68478. };
  68479. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  68480. if (this._fallbackTextureUsed) {
  68481. return;
  68482. }
  68483. this.releaseInternalTexture();
  68484. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  68485. };
  68486. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  68487. if (this._uniforms.indexOf(uniformName) === -1) {
  68488. this._uniforms.push(uniformName);
  68489. }
  68490. };
  68491. ProceduralTexture.prototype.setTexture = function (name, texture) {
  68492. if (this._samplers.indexOf(name) === -1) {
  68493. this._samplers.push(name);
  68494. }
  68495. this._textures[name] = texture;
  68496. return this;
  68497. };
  68498. ProceduralTexture.prototype.setFloat = function (name, value) {
  68499. this._checkUniform(name);
  68500. this._floats[name] = value;
  68501. return this;
  68502. };
  68503. ProceduralTexture.prototype.setFloats = function (name, value) {
  68504. this._checkUniform(name);
  68505. this._floatsArrays[name] = value;
  68506. return this;
  68507. };
  68508. ProceduralTexture.prototype.setColor3 = function (name, value) {
  68509. this._checkUniform(name);
  68510. this._colors3[name] = value;
  68511. return this;
  68512. };
  68513. ProceduralTexture.prototype.setColor4 = function (name, value) {
  68514. this._checkUniform(name);
  68515. this._colors4[name] = value;
  68516. return this;
  68517. };
  68518. ProceduralTexture.prototype.setVector2 = function (name, value) {
  68519. this._checkUniform(name);
  68520. this._vectors2[name] = value;
  68521. return this;
  68522. };
  68523. ProceduralTexture.prototype.setVector3 = function (name, value) {
  68524. this._checkUniform(name);
  68525. this._vectors3[name] = value;
  68526. return this;
  68527. };
  68528. ProceduralTexture.prototype.setMatrix = function (name, value) {
  68529. this._checkUniform(name);
  68530. this._matrices[name] = value;
  68531. return this;
  68532. };
  68533. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  68534. var scene = this.getScene();
  68535. if (!scene) {
  68536. return;
  68537. }
  68538. var engine = this._engine;
  68539. // Render
  68540. engine.enableEffect(this._effect);
  68541. engine.setState(false);
  68542. // Texture
  68543. for (var name in this._textures) {
  68544. this._effect.setTexture(name, this._textures[name]);
  68545. }
  68546. // Float
  68547. for (name in this._floats) {
  68548. this._effect.setFloat(name, this._floats[name]);
  68549. }
  68550. // Floats
  68551. for (name in this._floatsArrays) {
  68552. this._effect.setArray(name, this._floatsArrays[name]);
  68553. }
  68554. // Color3
  68555. for (name in this._colors3) {
  68556. this._effect.setColor3(name, this._colors3[name]);
  68557. }
  68558. // Color4
  68559. for (name in this._colors4) {
  68560. var color = this._colors4[name];
  68561. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  68562. }
  68563. // Vector2
  68564. for (name in this._vectors2) {
  68565. this._effect.setVector2(name, this._vectors2[name]);
  68566. }
  68567. // Vector3
  68568. for (name in this._vectors3) {
  68569. this._effect.setVector3(name, this._vectors3[name]);
  68570. }
  68571. // Matrix
  68572. for (name in this._matrices) {
  68573. this._effect.setMatrix(name, this._matrices[name]);
  68574. }
  68575. if (!this._texture) {
  68576. return;
  68577. }
  68578. if (this.isCube) {
  68579. for (var face = 0; face < 6; face++) {
  68580. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  68581. // VBOs
  68582. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  68583. this._effect.setFloat("face", face);
  68584. // Clear
  68585. engine.clear(scene.clearColor, true, true, true);
  68586. // Draw order
  68587. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68588. // Mipmaps
  68589. if (face === 5) {
  68590. engine.generateMipMapsForCubemap(this._texture);
  68591. }
  68592. }
  68593. }
  68594. else {
  68595. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  68596. // VBOs
  68597. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  68598. // Clear
  68599. engine.clear(scene.clearColor, true, true, true);
  68600. // Draw order
  68601. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68602. }
  68603. // Unbind
  68604. engine.unBindFramebuffer(this._texture, this.isCube);
  68605. if (this.onGenerated) {
  68606. this.onGenerated();
  68607. }
  68608. };
  68609. ProceduralTexture.prototype.clone = function () {
  68610. var textureSize = this.getSize();
  68611. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  68612. // Base texture
  68613. newTexture.hasAlpha = this.hasAlpha;
  68614. newTexture.level = this.level;
  68615. // RenderTarget Texture
  68616. newTexture.coordinatesMode = this.coordinatesMode;
  68617. return newTexture;
  68618. };
  68619. ProceduralTexture.prototype.dispose = function () {
  68620. var scene = this.getScene();
  68621. if (!scene) {
  68622. return;
  68623. }
  68624. var index = scene.proceduralTextures.indexOf(this);
  68625. if (index >= 0) {
  68626. scene.proceduralTextures.splice(index, 1);
  68627. }
  68628. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68629. if (vertexBuffer) {
  68630. vertexBuffer.dispose();
  68631. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68632. }
  68633. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  68634. this._indexBuffer = null;
  68635. }
  68636. _super.prototype.dispose.call(this);
  68637. };
  68638. return ProceduralTexture;
  68639. }(BABYLON.Texture));
  68640. BABYLON.ProceduralTexture = ProceduralTexture;
  68641. })(BABYLON || (BABYLON = {}));
  68642. //# sourceMappingURL=babylon.proceduralTexture.js.map
  68643. "use strict";
  68644. var BABYLON;
  68645. (function (BABYLON) {
  68646. var CustomProceduralTexture = /** @class */ (function (_super) {
  68647. __extends(CustomProceduralTexture, _super);
  68648. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  68649. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  68650. _this._animate = true;
  68651. _this._time = 0;
  68652. _this._texturePath = texturePath;
  68653. //Try to load json
  68654. _this.loadJson(texturePath);
  68655. _this.refreshRate = 1;
  68656. return _this;
  68657. }
  68658. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  68659. var _this = this;
  68660. var noConfigFile = function () {
  68661. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  68662. try {
  68663. _this.setFragment(_this._texturePath);
  68664. }
  68665. catch (ex) {
  68666. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  68667. }
  68668. };
  68669. var configFileUrl = jsonUrl + "/config.json";
  68670. var xhr = new XMLHttpRequest();
  68671. xhr.open("GET", configFileUrl, true);
  68672. xhr.addEventListener("load", function () {
  68673. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68674. try {
  68675. _this._config = JSON.parse(xhr.response);
  68676. _this.updateShaderUniforms();
  68677. _this.updateTextures();
  68678. _this.setFragment(_this._texturePath + "/custom");
  68679. _this._animate = _this._config.animate;
  68680. _this.refreshRate = _this._config.refreshrate;
  68681. }
  68682. catch (ex) {
  68683. noConfigFile();
  68684. }
  68685. }
  68686. else {
  68687. noConfigFile();
  68688. }
  68689. }, false);
  68690. xhr.addEventListener("error", function () {
  68691. noConfigFile();
  68692. }, false);
  68693. try {
  68694. xhr.send();
  68695. }
  68696. catch (ex) {
  68697. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  68698. }
  68699. };
  68700. CustomProceduralTexture.prototype.isReady = function () {
  68701. if (!_super.prototype.isReady.call(this)) {
  68702. return false;
  68703. }
  68704. for (var name in this._textures) {
  68705. var texture = this._textures[name];
  68706. if (!texture.isReady()) {
  68707. return false;
  68708. }
  68709. }
  68710. return true;
  68711. };
  68712. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  68713. var scene = this.getScene();
  68714. if (this._animate && scene) {
  68715. this._time += scene.getAnimationRatio() * 0.03;
  68716. this.updateShaderUniforms();
  68717. }
  68718. _super.prototype.render.call(this, useCameraPostProcess);
  68719. };
  68720. CustomProceduralTexture.prototype.updateTextures = function () {
  68721. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  68722. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  68723. }
  68724. };
  68725. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  68726. if (this._config) {
  68727. for (var j = 0; j < this._config.uniforms.length; j++) {
  68728. var uniform = this._config.uniforms[j];
  68729. switch (uniform.type) {
  68730. case "float":
  68731. this.setFloat(uniform.name, uniform.value);
  68732. break;
  68733. case "color3":
  68734. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  68735. break;
  68736. case "color4":
  68737. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  68738. break;
  68739. case "vector2":
  68740. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  68741. break;
  68742. case "vector3":
  68743. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  68744. break;
  68745. }
  68746. }
  68747. }
  68748. this.setFloat("time", this._time);
  68749. };
  68750. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  68751. get: function () {
  68752. return this._animate;
  68753. },
  68754. set: function (value) {
  68755. this._animate = value;
  68756. },
  68757. enumerable: true,
  68758. configurable: true
  68759. });
  68760. return CustomProceduralTexture;
  68761. }(BABYLON.ProceduralTexture));
  68762. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  68763. })(BABYLON || (BABYLON = {}));
  68764. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  68765. "use strict";
  68766. var BABYLON;
  68767. (function (BABYLON) {
  68768. var FreeCameraGamepadInput = /** @class */ (function () {
  68769. function FreeCameraGamepadInput() {
  68770. this.gamepadAngularSensibility = 200;
  68771. this.gamepadMoveSensibility = 40;
  68772. // private members
  68773. this._cameraTransform = BABYLON.Matrix.Identity();
  68774. this._deltaTransform = BABYLON.Vector3.Zero();
  68775. this._vector3 = BABYLON.Vector3.Zero();
  68776. this._vector2 = BABYLON.Vector2.Zero();
  68777. }
  68778. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  68779. var _this = this;
  68780. var manager = this.camera.getScene().gamepadManager;
  68781. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  68782. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  68783. // prioritize XBOX gamepads.
  68784. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  68785. _this.gamepad = gamepad;
  68786. }
  68787. }
  68788. });
  68789. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  68790. if (_this.gamepad === gamepad) {
  68791. _this.gamepad = null;
  68792. }
  68793. });
  68794. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  68795. };
  68796. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  68797. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  68798. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  68799. this.gamepad = null;
  68800. };
  68801. FreeCameraGamepadInput.prototype.checkInputs = function () {
  68802. if (this.gamepad && this.gamepad.leftStick) {
  68803. var camera = this.camera;
  68804. var LSValues = this.gamepad.leftStick;
  68805. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  68806. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  68807. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  68808. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  68809. var RSValues = this.gamepad.rightStick;
  68810. if (RSValues) {
  68811. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  68812. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  68813. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  68814. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  68815. }
  68816. else {
  68817. RSValues = { x: 0, y: 0 };
  68818. }
  68819. if (!camera.rotationQuaternion) {
  68820. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  68821. }
  68822. else {
  68823. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  68824. }
  68825. var speed = camera._computeLocalCameraSpeed() * 50.0;
  68826. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  68827. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  68828. camera.cameraDirection.addInPlace(this._deltaTransform);
  68829. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  68830. camera.cameraRotation.addInPlace(this._vector2);
  68831. }
  68832. };
  68833. FreeCameraGamepadInput.prototype.getClassName = function () {
  68834. return "FreeCameraGamepadInput";
  68835. };
  68836. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  68837. return "gamepad";
  68838. };
  68839. __decorate([
  68840. BABYLON.serialize()
  68841. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  68842. __decorate([
  68843. BABYLON.serialize()
  68844. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  68845. return FreeCameraGamepadInput;
  68846. }());
  68847. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  68848. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  68849. })(BABYLON || (BABYLON = {}));
  68850. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  68851. "use strict";
  68852. var BABYLON;
  68853. (function (BABYLON) {
  68854. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  68855. function ArcRotateCameraGamepadInput() {
  68856. this.gamepadRotationSensibility = 80;
  68857. this.gamepadMoveSensibility = 40;
  68858. }
  68859. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  68860. var _this = this;
  68861. var manager = this.camera.getScene().gamepadManager;
  68862. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  68863. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  68864. // prioritize XBOX gamepads.
  68865. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  68866. _this.gamepad = gamepad;
  68867. }
  68868. }
  68869. });
  68870. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  68871. if (_this.gamepad === gamepad) {
  68872. _this.gamepad = null;
  68873. }
  68874. });
  68875. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  68876. };
  68877. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  68878. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  68879. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  68880. this.gamepad = null;
  68881. };
  68882. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  68883. if (this.gamepad) {
  68884. var camera = this.camera;
  68885. var RSValues = this.gamepad.rightStick;
  68886. if (RSValues) {
  68887. if (RSValues.x != 0) {
  68888. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  68889. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  68890. camera.inertialAlphaOffset += normalizedRX;
  68891. }
  68892. }
  68893. if (RSValues.y != 0) {
  68894. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  68895. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  68896. camera.inertialBetaOffset += normalizedRY;
  68897. }
  68898. }
  68899. }
  68900. var LSValues = this.gamepad.leftStick;
  68901. if (LSValues && LSValues.y != 0) {
  68902. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  68903. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  68904. this.camera.inertialRadiusOffset -= normalizedLY;
  68905. }
  68906. }
  68907. }
  68908. };
  68909. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  68910. return "ArcRotateCameraGamepadInput";
  68911. };
  68912. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  68913. return "gamepad";
  68914. };
  68915. __decorate([
  68916. BABYLON.serialize()
  68917. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  68918. __decorate([
  68919. BABYLON.serialize()
  68920. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  68921. return ArcRotateCameraGamepadInput;
  68922. }());
  68923. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  68924. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  68925. })(BABYLON || (BABYLON = {}));
  68926. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  68927. "use strict";
  68928. var BABYLON;
  68929. (function (BABYLON) {
  68930. var GamepadManager = /** @class */ (function () {
  68931. function GamepadManager(_scene) {
  68932. var _this = this;
  68933. this._scene = _scene;
  68934. this._babylonGamepads = [];
  68935. this._oneGamepadConnected = false;
  68936. this._isMonitoring = false;
  68937. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  68938. if (!BABYLON.Tools.IsWindowObjectExist()) {
  68939. this._gamepadEventSupported = false;
  68940. }
  68941. else {
  68942. this._gamepadEventSupported = 'GamepadEvent' in window;
  68943. this._gamepadSupport = (navigator.getGamepads ||
  68944. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  68945. }
  68946. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  68947. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  68948. for (var i in _this._babylonGamepads) {
  68949. var gamepad = _this._babylonGamepads[i];
  68950. if (gamepad && gamepad._isConnected) {
  68951. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  68952. }
  68953. }
  68954. });
  68955. this._onGamepadConnectedEvent = function (evt) {
  68956. var gamepad = evt.gamepad;
  68957. if (gamepad.index in _this._babylonGamepads) {
  68958. if (_this._babylonGamepads[gamepad.index].isConnected) {
  68959. return;
  68960. }
  68961. }
  68962. var newGamepad;
  68963. if (_this._babylonGamepads[gamepad.index]) {
  68964. newGamepad = _this._babylonGamepads[gamepad.index];
  68965. newGamepad.browserGamepad = gamepad;
  68966. newGamepad._isConnected = true;
  68967. }
  68968. else {
  68969. newGamepad = _this._addNewGamepad(gamepad);
  68970. }
  68971. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  68972. _this._startMonitoringGamepads();
  68973. };
  68974. this._onGamepadDisconnectedEvent = function (evt) {
  68975. var gamepad = evt.gamepad;
  68976. // Remove the gamepad from the list of gamepads to monitor.
  68977. for (var i in _this._babylonGamepads) {
  68978. if (_this._babylonGamepads[i].index === gamepad.index) {
  68979. var disconnectedGamepad = _this._babylonGamepads[i];
  68980. disconnectedGamepad._isConnected = false;
  68981. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  68982. break;
  68983. }
  68984. }
  68985. };
  68986. if (this._gamepadSupport) {
  68987. //first add already-connected gamepads
  68988. this._updateGamepadObjects();
  68989. if (this._babylonGamepads.length) {
  68990. this._startMonitoringGamepads();
  68991. }
  68992. // Checking if the gamepad connected event is supported (like in Firefox)
  68993. if (this._gamepadEventSupported) {
  68994. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  68995. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  68996. }
  68997. else {
  68998. this._startMonitoringGamepads();
  68999. }
  69000. }
  69001. }
  69002. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  69003. get: function () {
  69004. return this._babylonGamepads;
  69005. },
  69006. enumerable: true,
  69007. configurable: true
  69008. });
  69009. GamepadManager.prototype.getGamepadByType = function (type) {
  69010. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  69011. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  69012. var gamepad = _a[_i];
  69013. if (gamepad && gamepad.type === type) {
  69014. return gamepad;
  69015. }
  69016. }
  69017. return null;
  69018. };
  69019. GamepadManager.prototype.dispose = function () {
  69020. if (this._gamepadEventSupported) {
  69021. if (this._onGamepadConnectedEvent) {
  69022. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  69023. }
  69024. if (this._onGamepadDisconnectedEvent) {
  69025. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  69026. }
  69027. this._onGamepadConnectedEvent = null;
  69028. this._onGamepadDisconnectedEvent = null;
  69029. }
  69030. this._babylonGamepads.forEach(function (gamepad) {
  69031. gamepad.dispose();
  69032. });
  69033. this.onGamepadConnectedObservable.clear();
  69034. this.onGamepadDisconnectedObservable.clear();
  69035. this._oneGamepadConnected = false;
  69036. this._stopMonitoringGamepads();
  69037. this._babylonGamepads = [];
  69038. };
  69039. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  69040. if (!this._oneGamepadConnected) {
  69041. this._oneGamepadConnected = true;
  69042. }
  69043. var newGamepad;
  69044. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  69045. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  69046. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  69047. }
  69048. else if (gamepad.pose) {
  69049. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  69050. }
  69051. else {
  69052. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  69053. }
  69054. this._babylonGamepads[newGamepad.index] = newGamepad;
  69055. return newGamepad;
  69056. };
  69057. GamepadManager.prototype._startMonitoringGamepads = function () {
  69058. if (!this._isMonitoring) {
  69059. this._isMonitoring = true;
  69060. //back-comp
  69061. if (!this._scene) {
  69062. this._checkGamepadsStatus();
  69063. }
  69064. }
  69065. };
  69066. GamepadManager.prototype._stopMonitoringGamepads = function () {
  69067. this._isMonitoring = false;
  69068. };
  69069. GamepadManager.prototype._checkGamepadsStatus = function () {
  69070. var _this = this;
  69071. // Hack to be compatible Chrome
  69072. this._updateGamepadObjects();
  69073. for (var i in this._babylonGamepads) {
  69074. var gamepad = this._babylonGamepads[i];
  69075. if (!gamepad || !gamepad.isConnected) {
  69076. continue;
  69077. }
  69078. gamepad.update();
  69079. }
  69080. if (this._isMonitoring && !this._scene) {
  69081. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  69082. }
  69083. };
  69084. // This function is called only on Chrome, which does not properly support
  69085. // connection/disconnection events and forces you to recopy again the gamepad object
  69086. GamepadManager.prototype._updateGamepadObjects = function () {
  69087. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  69088. for (var i = 0; i < gamepads.length; i++) {
  69089. if (gamepads[i]) {
  69090. if (!this._babylonGamepads[gamepads[i].index]) {
  69091. var newGamepad = this._addNewGamepad(gamepads[i]);
  69092. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69093. }
  69094. else {
  69095. // Forced to copy again this object for Chrome for unknown reason
  69096. this._babylonGamepads[i].browserGamepad = gamepads[i];
  69097. if (!this._babylonGamepads[i].isConnected) {
  69098. this._babylonGamepads[i]._isConnected = true;
  69099. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  69100. }
  69101. }
  69102. }
  69103. }
  69104. };
  69105. return GamepadManager;
  69106. }());
  69107. BABYLON.GamepadManager = GamepadManager;
  69108. })(BABYLON || (BABYLON = {}));
  69109. //# sourceMappingURL=babylon.gamepadManager.js.map
  69110. "use strict";
  69111. var BABYLON;
  69112. (function (BABYLON) {
  69113. var StickValues = /** @class */ (function () {
  69114. function StickValues(x, y) {
  69115. this.x = x;
  69116. this.y = y;
  69117. }
  69118. return StickValues;
  69119. }());
  69120. BABYLON.StickValues = StickValues;
  69121. var Gamepad = /** @class */ (function () {
  69122. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  69123. if (leftStickX === void 0) { leftStickX = 0; }
  69124. if (leftStickY === void 0) { leftStickY = 1; }
  69125. if (rightStickX === void 0) { rightStickX = 2; }
  69126. if (rightStickY === void 0) { rightStickY = 3; }
  69127. this.id = id;
  69128. this.index = index;
  69129. this.browserGamepad = browserGamepad;
  69130. this._isConnected = true;
  69131. this._invertLeftStickY = false;
  69132. this.type = Gamepad.GAMEPAD;
  69133. this._leftStickAxisX = leftStickX;
  69134. this._leftStickAxisY = leftStickY;
  69135. this._rightStickAxisX = rightStickX;
  69136. this._rightStickAxisY = rightStickY;
  69137. if (this.browserGamepad.axes.length >= 2) {
  69138. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69139. }
  69140. if (this.browserGamepad.axes.length >= 4) {
  69141. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69142. }
  69143. }
  69144. Object.defineProperty(Gamepad.prototype, "isConnected", {
  69145. get: function () {
  69146. return this._isConnected;
  69147. },
  69148. enumerable: true,
  69149. configurable: true
  69150. });
  69151. Gamepad.prototype.onleftstickchanged = function (callback) {
  69152. this._onleftstickchanged = callback;
  69153. };
  69154. Gamepad.prototype.onrightstickchanged = function (callback) {
  69155. this._onrightstickchanged = callback;
  69156. };
  69157. Object.defineProperty(Gamepad.prototype, "leftStick", {
  69158. get: function () {
  69159. return this._leftStick;
  69160. },
  69161. set: function (newValues) {
  69162. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  69163. this._onleftstickchanged(newValues);
  69164. }
  69165. this._leftStick = newValues;
  69166. },
  69167. enumerable: true,
  69168. configurable: true
  69169. });
  69170. Object.defineProperty(Gamepad.prototype, "rightStick", {
  69171. get: function () {
  69172. return this._rightStick;
  69173. },
  69174. set: function (newValues) {
  69175. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  69176. this._onrightstickchanged(newValues);
  69177. }
  69178. this._rightStick = newValues;
  69179. },
  69180. enumerable: true,
  69181. configurable: true
  69182. });
  69183. Gamepad.prototype.update = function () {
  69184. if (this._leftStick) {
  69185. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69186. if (this._invertLeftStickY) {
  69187. this.leftStick.y *= -1;
  69188. }
  69189. }
  69190. if (this._rightStick) {
  69191. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69192. }
  69193. };
  69194. Gamepad.prototype.dispose = function () {
  69195. };
  69196. Gamepad.GAMEPAD = 0;
  69197. Gamepad.GENERIC = 1;
  69198. Gamepad.XBOX = 2;
  69199. Gamepad.POSE_ENABLED = 3;
  69200. return Gamepad;
  69201. }());
  69202. BABYLON.Gamepad = Gamepad;
  69203. var GenericPad = /** @class */ (function (_super) {
  69204. __extends(GenericPad, _super);
  69205. function GenericPad(id, index, browserGamepad) {
  69206. var _this = _super.call(this, id, index, browserGamepad) || this;
  69207. _this.onButtonDownObservable = new BABYLON.Observable();
  69208. _this.onButtonUpObservable = new BABYLON.Observable();
  69209. _this.type = Gamepad.GENERIC;
  69210. _this._buttons = new Array(browserGamepad.buttons.length);
  69211. return _this;
  69212. }
  69213. GenericPad.prototype.onbuttondown = function (callback) {
  69214. this._onbuttondown = callback;
  69215. };
  69216. GenericPad.prototype.onbuttonup = function (callback) {
  69217. this._onbuttonup = callback;
  69218. };
  69219. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  69220. if (newValue !== currentValue) {
  69221. if (newValue === 1) {
  69222. if (this._onbuttondown) {
  69223. this._onbuttondown(buttonIndex);
  69224. }
  69225. this.onButtonDownObservable.notifyObservers(buttonIndex);
  69226. }
  69227. if (newValue === 0) {
  69228. if (this._onbuttonup) {
  69229. this._onbuttonup(buttonIndex);
  69230. }
  69231. this.onButtonUpObservable.notifyObservers(buttonIndex);
  69232. }
  69233. }
  69234. return newValue;
  69235. };
  69236. GenericPad.prototype.update = function () {
  69237. _super.prototype.update.call(this);
  69238. for (var index = 0; index < this._buttons.length; index++) {
  69239. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  69240. }
  69241. };
  69242. GenericPad.prototype.dispose = function () {
  69243. _super.prototype.dispose.call(this);
  69244. this.onButtonDownObservable.clear();
  69245. this.onButtonUpObservable.clear();
  69246. };
  69247. return GenericPad;
  69248. }(Gamepad));
  69249. BABYLON.GenericPad = GenericPad;
  69250. })(BABYLON || (BABYLON = {}));
  69251. //# sourceMappingURL=babylon.gamepad.js.map
  69252. "use strict";
  69253. var BABYLON;
  69254. (function (BABYLON) {
  69255. var Xbox360Button;
  69256. (function (Xbox360Button) {
  69257. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  69258. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  69259. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  69260. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  69261. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  69262. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  69263. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  69264. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  69265. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  69266. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  69267. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  69268. var Xbox360Dpad;
  69269. (function (Xbox360Dpad) {
  69270. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  69271. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  69272. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  69273. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  69274. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  69275. var Xbox360Pad = /** @class */ (function (_super) {
  69276. __extends(Xbox360Pad, _super);
  69277. function Xbox360Pad(id, index, gamepad, xboxOne) {
  69278. if (xboxOne === void 0) { xboxOne = false; }
  69279. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  69280. _this._leftTrigger = 0;
  69281. _this._rightTrigger = 0;
  69282. _this.onButtonDownObservable = new BABYLON.Observable();
  69283. _this.onButtonUpObservable = new BABYLON.Observable();
  69284. _this.onPadDownObservable = new BABYLON.Observable();
  69285. _this.onPadUpObservable = new BABYLON.Observable();
  69286. _this._buttonA = 0;
  69287. _this._buttonB = 0;
  69288. _this._buttonX = 0;
  69289. _this._buttonY = 0;
  69290. _this._buttonBack = 0;
  69291. _this._buttonStart = 0;
  69292. _this._buttonLB = 0;
  69293. _this._buttonRB = 0;
  69294. _this._buttonLeftStick = 0;
  69295. _this._buttonRightStick = 0;
  69296. _this._dPadUp = 0;
  69297. _this._dPadDown = 0;
  69298. _this._dPadLeft = 0;
  69299. _this._dPadRight = 0;
  69300. _this._isXboxOnePad = false;
  69301. _this.type = BABYLON.Gamepad.XBOX;
  69302. _this._isXboxOnePad = xboxOne;
  69303. return _this;
  69304. }
  69305. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  69306. this._onlefttriggerchanged = callback;
  69307. };
  69308. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  69309. this._onrighttriggerchanged = callback;
  69310. };
  69311. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  69312. get: function () {
  69313. return this._leftTrigger;
  69314. },
  69315. set: function (newValue) {
  69316. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  69317. this._onlefttriggerchanged(newValue);
  69318. }
  69319. this._leftTrigger = newValue;
  69320. },
  69321. enumerable: true,
  69322. configurable: true
  69323. });
  69324. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  69325. get: function () {
  69326. return this._rightTrigger;
  69327. },
  69328. set: function (newValue) {
  69329. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  69330. this._onrighttriggerchanged(newValue);
  69331. }
  69332. this._rightTrigger = newValue;
  69333. },
  69334. enumerable: true,
  69335. configurable: true
  69336. });
  69337. Xbox360Pad.prototype.onbuttondown = function (callback) {
  69338. this._onbuttondown = callback;
  69339. };
  69340. Xbox360Pad.prototype.onbuttonup = function (callback) {
  69341. this._onbuttonup = callback;
  69342. };
  69343. Xbox360Pad.prototype.ondpaddown = function (callback) {
  69344. this._ondpaddown = callback;
  69345. };
  69346. Xbox360Pad.prototype.ondpadup = function (callback) {
  69347. this._ondpadup = callback;
  69348. };
  69349. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  69350. if (newValue !== currentValue) {
  69351. if (newValue === 1) {
  69352. if (this._onbuttondown) {
  69353. this._onbuttondown(buttonType);
  69354. }
  69355. this.onButtonDownObservable.notifyObservers(buttonType);
  69356. }
  69357. if (newValue === 0) {
  69358. if (this._onbuttonup) {
  69359. this._onbuttonup(buttonType);
  69360. }
  69361. this.onButtonUpObservable.notifyObservers(buttonType);
  69362. }
  69363. }
  69364. return newValue;
  69365. };
  69366. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  69367. if (newValue !== currentValue) {
  69368. if (newValue === 1) {
  69369. if (this._ondpaddown) {
  69370. this._ondpaddown(buttonType);
  69371. }
  69372. this.onPadDownObservable.notifyObservers(buttonType);
  69373. }
  69374. if (newValue === 0) {
  69375. if (this._ondpadup) {
  69376. this._ondpadup(buttonType);
  69377. }
  69378. this.onPadUpObservable.notifyObservers(buttonType);
  69379. }
  69380. }
  69381. return newValue;
  69382. };
  69383. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  69384. get: function () {
  69385. return this._buttonA;
  69386. },
  69387. set: function (value) {
  69388. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  69389. },
  69390. enumerable: true,
  69391. configurable: true
  69392. });
  69393. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  69394. get: function () {
  69395. return this._buttonB;
  69396. },
  69397. set: function (value) {
  69398. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  69399. },
  69400. enumerable: true,
  69401. configurable: true
  69402. });
  69403. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  69404. get: function () {
  69405. return this._buttonX;
  69406. },
  69407. set: function (value) {
  69408. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  69409. },
  69410. enumerable: true,
  69411. configurable: true
  69412. });
  69413. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  69414. get: function () {
  69415. return this._buttonY;
  69416. },
  69417. set: function (value) {
  69418. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  69419. },
  69420. enumerable: true,
  69421. configurable: true
  69422. });
  69423. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  69424. get: function () {
  69425. return this._buttonStart;
  69426. },
  69427. set: function (value) {
  69428. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  69429. },
  69430. enumerable: true,
  69431. configurable: true
  69432. });
  69433. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  69434. get: function () {
  69435. return this._buttonBack;
  69436. },
  69437. set: function (value) {
  69438. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  69439. },
  69440. enumerable: true,
  69441. configurable: true
  69442. });
  69443. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  69444. get: function () {
  69445. return this._buttonLB;
  69446. },
  69447. set: function (value) {
  69448. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  69449. },
  69450. enumerable: true,
  69451. configurable: true
  69452. });
  69453. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  69454. get: function () {
  69455. return this._buttonRB;
  69456. },
  69457. set: function (value) {
  69458. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  69459. },
  69460. enumerable: true,
  69461. configurable: true
  69462. });
  69463. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  69464. get: function () {
  69465. return this._buttonLeftStick;
  69466. },
  69467. set: function (value) {
  69468. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  69469. },
  69470. enumerable: true,
  69471. configurable: true
  69472. });
  69473. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  69474. get: function () {
  69475. return this._buttonRightStick;
  69476. },
  69477. set: function (value) {
  69478. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  69479. },
  69480. enumerable: true,
  69481. configurable: true
  69482. });
  69483. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  69484. get: function () {
  69485. return this._dPadUp;
  69486. },
  69487. set: function (value) {
  69488. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  69489. },
  69490. enumerable: true,
  69491. configurable: true
  69492. });
  69493. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  69494. get: function () {
  69495. return this._dPadDown;
  69496. },
  69497. set: function (value) {
  69498. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  69499. },
  69500. enumerable: true,
  69501. configurable: true
  69502. });
  69503. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  69504. get: function () {
  69505. return this._dPadLeft;
  69506. },
  69507. set: function (value) {
  69508. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  69509. },
  69510. enumerable: true,
  69511. configurable: true
  69512. });
  69513. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  69514. get: function () {
  69515. return this._dPadRight;
  69516. },
  69517. set: function (value) {
  69518. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  69519. },
  69520. enumerable: true,
  69521. configurable: true
  69522. });
  69523. Xbox360Pad.prototype.update = function () {
  69524. _super.prototype.update.call(this);
  69525. if (this._isXboxOnePad) {
  69526. this.buttonA = this.browserGamepad.buttons[0].value;
  69527. this.buttonB = this.browserGamepad.buttons[1].value;
  69528. this.buttonX = this.browserGamepad.buttons[2].value;
  69529. this.buttonY = this.browserGamepad.buttons[3].value;
  69530. this.buttonLB = this.browserGamepad.buttons[4].value;
  69531. this.buttonRB = this.browserGamepad.buttons[5].value;
  69532. this.leftTrigger = this.browserGamepad.axes[2];
  69533. this.rightTrigger = this.browserGamepad.axes[5];
  69534. this.buttonBack = this.browserGamepad.buttons[9].value;
  69535. this.buttonStart = this.browserGamepad.buttons[8].value;
  69536. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  69537. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  69538. this.dPadUp = this.browserGamepad.buttons[11].value;
  69539. this.dPadDown = this.browserGamepad.buttons[12].value;
  69540. this.dPadLeft = this.browserGamepad.buttons[13].value;
  69541. this.dPadRight = this.browserGamepad.buttons[14].value;
  69542. }
  69543. else {
  69544. this.buttonA = this.browserGamepad.buttons[0].value;
  69545. this.buttonB = this.browserGamepad.buttons[1].value;
  69546. this.buttonX = this.browserGamepad.buttons[2].value;
  69547. this.buttonY = this.browserGamepad.buttons[3].value;
  69548. this.buttonLB = this.browserGamepad.buttons[4].value;
  69549. this.buttonRB = this.browserGamepad.buttons[5].value;
  69550. this.leftTrigger = this.browserGamepad.buttons[6].value;
  69551. this.rightTrigger = this.browserGamepad.buttons[7].value;
  69552. this.buttonBack = this.browserGamepad.buttons[8].value;
  69553. this.buttonStart = this.browserGamepad.buttons[9].value;
  69554. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  69555. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  69556. this.dPadUp = this.browserGamepad.buttons[12].value;
  69557. this.dPadDown = this.browserGamepad.buttons[13].value;
  69558. this.dPadLeft = this.browserGamepad.buttons[14].value;
  69559. this.dPadRight = this.browserGamepad.buttons[15].value;
  69560. }
  69561. };
  69562. Xbox360Pad.prototype.dispose = function () {
  69563. _super.prototype.dispose.call(this);
  69564. this.onButtonDownObservable.clear();
  69565. this.onButtonUpObservable.clear();
  69566. this.onPadDownObservable.clear();
  69567. this.onPadUpObservable.clear();
  69568. };
  69569. return Xbox360Pad;
  69570. }(BABYLON.Gamepad));
  69571. BABYLON.Xbox360Pad = Xbox360Pad;
  69572. })(BABYLON || (BABYLON = {}));
  69573. //# sourceMappingURL=babylon.xboxGamepad.js.map
  69574. "use strict";
  69575. var BABYLON;
  69576. (function (BABYLON) {
  69577. /**
  69578. * Defines the types of pose enabled controllers that are supported
  69579. */
  69580. var PoseEnabledControllerType;
  69581. (function (PoseEnabledControllerType) {
  69582. /**
  69583. * HTC Vive
  69584. */
  69585. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  69586. /**
  69587. * Oculus Rift
  69588. */
  69589. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  69590. /**
  69591. * Windows mixed reality
  69592. */
  69593. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  69594. /**
  69595. * Samsung gear VR
  69596. */
  69597. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  69598. /**
  69599. * Google Daydream
  69600. */
  69601. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  69602. /**
  69603. * Generic
  69604. */
  69605. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  69606. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  69607. /**
  69608. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  69609. */
  69610. var PoseEnabledControllerHelper = /** @class */ (function () {
  69611. function PoseEnabledControllerHelper() {
  69612. }
  69613. /**
  69614. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  69615. * @param vrGamepad the gamepad to initialized
  69616. * @returns a vr controller of the type the gamepad identified as
  69617. */
  69618. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  69619. // Oculus Touch
  69620. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  69621. return new BABYLON.OculusTouchController(vrGamepad);
  69622. }
  69623. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  69624. return new BABYLON.WindowsMotionController(vrGamepad);
  69625. }
  69626. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  69627. return new BABYLON.ViveController(vrGamepad);
  69628. }
  69629. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  69630. return new BABYLON.GearVRController(vrGamepad);
  69631. }
  69632. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  69633. return new BABYLON.DaydreamController(vrGamepad);
  69634. }
  69635. else {
  69636. return new BABYLON.GenericController(vrGamepad);
  69637. }
  69638. };
  69639. return PoseEnabledControllerHelper;
  69640. }());
  69641. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  69642. /**
  69643. * Defines the PoseEnabledController object that contains state of a vr capable controller
  69644. */
  69645. var PoseEnabledController = /** @class */ (function (_super) {
  69646. __extends(PoseEnabledController, _super);
  69647. /**
  69648. * Creates a new PoseEnabledController from a gamepad
  69649. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  69650. */
  69651. function PoseEnabledController(browserGamepad) {
  69652. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  69653. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  69654. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  69655. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  69656. /**
  69657. * The device position in babylon space
  69658. */
  69659. _this.devicePosition = BABYLON.Vector3.Zero();
  69660. /**
  69661. * The device rotation in babylon space
  69662. */
  69663. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  69664. /**
  69665. * The scale factor of the device in babylon space
  69666. */
  69667. _this.deviceScaleFactor = 1;
  69668. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  69669. /**
  69670. * Internal, matrix used to convert room space to babylon space
  69671. */
  69672. _this._deviceToWorld = BABYLON.Matrix.Identity();
  69673. /**
  69674. * Node to be used when casting a ray from the controller
  69675. */
  69676. _this._pointingPoseNode = null;
  69677. _this._workingMatrix = BABYLON.Matrix.Identity();
  69678. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  69679. _this.controllerType = PoseEnabledControllerType.GENERIC;
  69680. _this.position = BABYLON.Vector3.Zero();
  69681. _this.rotationQuaternion = new BABYLON.Quaternion();
  69682. _this._calculatedPosition = BABYLON.Vector3.Zero();
  69683. _this._calculatedRotation = new BABYLON.Quaternion();
  69684. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  69685. return _this;
  69686. }
  69687. /**
  69688. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  69689. */
  69690. PoseEnabledController.prototype.update = function () {
  69691. _super.prototype.update.call(this);
  69692. var pose = this.browserGamepad.pose;
  69693. this.updateFromDevice(pose);
  69694. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  69695. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  69696. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  69697. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  69698. if (this._mesh) {
  69699. this._mesh.position.copyFrom(this.devicePosition);
  69700. if (this._mesh.rotationQuaternion) {
  69701. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69702. }
  69703. }
  69704. };
  69705. /**
  69706. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  69707. * @param poseData raw pose fromthe device
  69708. */
  69709. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  69710. if (poseData) {
  69711. this.rawPose = poseData;
  69712. if (poseData.position) {
  69713. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  69714. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  69715. this._deviceRoomPosition.z *= -1;
  69716. }
  69717. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  69718. this._calculatedPosition.addInPlace(this.position);
  69719. }
  69720. var pose = this.rawPose;
  69721. if (poseData.orientation && pose.orientation) {
  69722. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  69723. if (this._mesh) {
  69724. if (this._mesh.getScene().useRightHandedSystem) {
  69725. this._deviceRoomRotationQuaternion.z *= -1;
  69726. this._deviceRoomRotationQuaternion.w *= -1;
  69727. }
  69728. else {
  69729. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  69730. }
  69731. }
  69732. // if the camera is set, rotate to the camera's rotation
  69733. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  69734. }
  69735. }
  69736. };
  69737. /**
  69738. * Attaches a mesh to the controller
  69739. * @param mesh the mesh to be attached
  69740. */
  69741. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  69742. if (this._mesh) {
  69743. this._mesh.parent = null;
  69744. }
  69745. this._mesh = mesh;
  69746. if (this._poseControlledCamera) {
  69747. this._mesh.parent = this._poseControlledCamera;
  69748. }
  69749. if (!this._mesh.rotationQuaternion) {
  69750. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  69751. }
  69752. };
  69753. /**
  69754. * Attaches the controllers mesh to a camera
  69755. * @param camera the camera the mesh should be attached to
  69756. */
  69757. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  69758. this._poseControlledCamera = camera;
  69759. if (this._mesh) {
  69760. this._mesh.parent = this._poseControlledCamera;
  69761. }
  69762. };
  69763. /**
  69764. * Disposes of the controller
  69765. */
  69766. PoseEnabledController.prototype.dispose = function () {
  69767. if (this._mesh) {
  69768. this._mesh.dispose();
  69769. }
  69770. this._mesh = null;
  69771. _super.prototype.dispose.call(this);
  69772. };
  69773. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  69774. /**
  69775. * The mesh that is attached to the controller
  69776. */
  69777. get: function () {
  69778. return this._mesh;
  69779. },
  69780. enumerable: true,
  69781. configurable: true
  69782. });
  69783. /**
  69784. * Gets the ray of the controller in the direction the controller is pointing
  69785. * @param length the length the resulting ray should be
  69786. * @returns a ray in the direction the controller is pointing
  69787. */
  69788. PoseEnabledController.prototype.getForwardRay = function (length) {
  69789. if (length === void 0) { length = 100; }
  69790. if (!this.mesh) {
  69791. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  69792. }
  69793. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  69794. var origin = m.getTranslation();
  69795. var forward = new BABYLON.Vector3(0, 0, -1);
  69796. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  69797. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  69798. return new BABYLON.Ray(origin, direction, length);
  69799. };
  69800. /**
  69801. * Name of the child mesh that can be used to cast a ray from the controller
  69802. */
  69803. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  69804. return PoseEnabledController;
  69805. }(BABYLON.Gamepad));
  69806. BABYLON.PoseEnabledController = PoseEnabledController;
  69807. })(BABYLON || (BABYLON = {}));
  69808. //# sourceMappingURL=babylon.poseEnabledController.js.map
  69809. "use strict";
  69810. var BABYLON;
  69811. (function (BABYLON) {
  69812. /**
  69813. * Defines the WebVRController object that represents controllers tracked in 3D space
  69814. */
  69815. var WebVRController = /** @class */ (function (_super) {
  69816. __extends(WebVRController, _super);
  69817. /**
  69818. * Creates a new WebVRController from a gamepad
  69819. * @param vrGamepad the gamepad that the WebVRController should be created from
  69820. */
  69821. function WebVRController(vrGamepad) {
  69822. var _this = _super.call(this, vrGamepad) || this;
  69823. // Observables
  69824. /**
  69825. * Fired when the trigger state has changed
  69826. */
  69827. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  69828. /**
  69829. * Fired when the main button state has changed
  69830. */
  69831. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  69832. /**
  69833. * Fired when the secondary button state has changed
  69834. */
  69835. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  69836. /**
  69837. * Fired when the pad state has changed
  69838. */
  69839. _this.onPadStateChangedObservable = new BABYLON.Observable();
  69840. /**
  69841. * Fired when controllers stick values have changed
  69842. */
  69843. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  69844. /**
  69845. * X and Y axis corrisponding to the controllers joystick
  69846. */
  69847. _this.pad = { x: 0, y: 0 };
  69848. // avoid GC, store state in a tmp object
  69849. _this._changes = {
  69850. pressChanged: false,
  69851. touchChanged: false,
  69852. valueChanged: false,
  69853. changed: false
  69854. };
  69855. _this._buttons = new Array(vrGamepad.buttons.length);
  69856. _this.hand = vrGamepad.hand;
  69857. return _this;
  69858. }
  69859. /**
  69860. * Fired when a controller button's state has changed
  69861. * @param callback the callback containing the button that was modified
  69862. */
  69863. WebVRController.prototype.onButtonStateChange = function (callback) {
  69864. this._onButtonStateChange = callback;
  69865. };
  69866. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  69867. /**
  69868. * The default controller model for the controller
  69869. */
  69870. get: function () {
  69871. return this._defaultModel;
  69872. },
  69873. enumerable: true,
  69874. configurable: true
  69875. });
  69876. /**
  69877. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  69878. */
  69879. WebVRController.prototype.update = function () {
  69880. _super.prototype.update.call(this);
  69881. for (var index = 0; index < this._buttons.length; index++) {
  69882. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  69883. }
  69884. ;
  69885. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  69886. this.pad.x = this.leftStick.x;
  69887. this.pad.y = this.leftStick.y;
  69888. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  69889. }
  69890. };
  69891. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  69892. if (!newState) {
  69893. newState = {
  69894. pressed: false,
  69895. touched: false,
  69896. value: 0
  69897. };
  69898. }
  69899. if (!currentState) {
  69900. this._buttons[buttonIndex] = {
  69901. pressed: newState.pressed,
  69902. touched: newState.touched,
  69903. value: newState.value
  69904. };
  69905. return;
  69906. }
  69907. this._checkChanges(newState, currentState);
  69908. if (this._changes.changed) {
  69909. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  69910. this._handleButtonChange(buttonIndex, newState, this._changes);
  69911. }
  69912. this._buttons[buttonIndex].pressed = newState.pressed;
  69913. this._buttons[buttonIndex].touched = newState.touched;
  69914. // oculus triggers are never 0, thou not touched.
  69915. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  69916. };
  69917. WebVRController.prototype._checkChanges = function (newState, currentState) {
  69918. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  69919. this._changes.touchChanged = newState.touched !== currentState.touched;
  69920. this._changes.valueChanged = newState.value !== currentState.value;
  69921. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  69922. return this._changes;
  69923. };
  69924. /**
  69925. * Disposes of th webVRCOntroller
  69926. */
  69927. WebVRController.prototype.dispose = function () {
  69928. _super.prototype.dispose.call(this);
  69929. this.onTriggerStateChangedObservable.clear();
  69930. this.onMainButtonStateChangedObservable.clear();
  69931. this.onSecondaryButtonStateChangedObservable.clear();
  69932. this.onPadStateChangedObservable.clear();
  69933. this.onPadValuesChangedObservable.clear();
  69934. };
  69935. return WebVRController;
  69936. }(BABYLON.PoseEnabledController));
  69937. BABYLON.WebVRController = WebVRController;
  69938. })(BABYLON || (BABYLON = {}));
  69939. //# sourceMappingURL=babylon.webVRController.js.map
  69940. "use strict";
  69941. var BABYLON;
  69942. (function (BABYLON) {
  69943. /**
  69944. * Oculus Touch Controller
  69945. */
  69946. var OculusTouchController = /** @class */ (function (_super) {
  69947. __extends(OculusTouchController, _super);
  69948. /**
  69949. * Creates a new OculusTouchController from a gamepad
  69950. * @param vrGamepad the gamepad that the controller should be created from
  69951. */
  69952. function OculusTouchController(vrGamepad) {
  69953. var _this = _super.call(this, vrGamepad) || this;
  69954. /**
  69955. * Fired when the secondary trigger on this controller is modified
  69956. */
  69957. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  69958. /**
  69959. * Fired when the thumb rest on this controller is modified
  69960. */
  69961. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  69962. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  69963. return _this;
  69964. }
  69965. /**
  69966. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69967. * @param scene scene in which to add meshes
  69968. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69969. */
  69970. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69971. var _this = this;
  69972. var meshName;
  69973. // Hand
  69974. if (this.hand === 'left') {
  69975. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  69976. }
  69977. else {
  69978. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  69979. }
  69980. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  69981. /*
  69982. Parent Mesh name: oculus_touch_left
  69983. - body
  69984. - trigger
  69985. - thumbstick
  69986. - grip
  69987. - button_y
  69988. - button_x
  69989. - button_enter
  69990. */
  69991. _this._defaultModel = newMeshes[1];
  69992. _this.attachToMesh(_this._defaultModel);
  69993. if (meshLoaded) {
  69994. meshLoaded(_this._defaultModel);
  69995. }
  69996. });
  69997. };
  69998. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  69999. /**
  70000. * Fired when the A button on this controller is modified
  70001. */
  70002. get: function () {
  70003. if (this.hand === 'right') {
  70004. return this.onMainButtonStateChangedObservable;
  70005. }
  70006. else {
  70007. throw new Error('No A button on left hand');
  70008. }
  70009. },
  70010. enumerable: true,
  70011. configurable: true
  70012. });
  70013. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  70014. /**
  70015. * Fired when the B button on this controller is modified
  70016. */
  70017. get: function () {
  70018. if (this.hand === 'right') {
  70019. return this.onSecondaryButtonStateChangedObservable;
  70020. }
  70021. else {
  70022. throw new Error('No B button on left hand');
  70023. }
  70024. },
  70025. enumerable: true,
  70026. configurable: true
  70027. });
  70028. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  70029. /**
  70030. * Fired when the X button on this controller is modified
  70031. */
  70032. get: function () {
  70033. if (this.hand === 'left') {
  70034. return this.onMainButtonStateChangedObservable;
  70035. }
  70036. else {
  70037. throw new Error('No X button on right hand');
  70038. }
  70039. },
  70040. enumerable: true,
  70041. configurable: true
  70042. });
  70043. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  70044. /**
  70045. * Fired when the Y button on this controller is modified
  70046. */
  70047. get: function () {
  70048. if (this.hand === 'left') {
  70049. return this.onSecondaryButtonStateChangedObservable;
  70050. }
  70051. else {
  70052. throw new Error('No Y button on right hand');
  70053. }
  70054. },
  70055. enumerable: true,
  70056. configurable: true
  70057. });
  70058. /**
  70059. * Called once for each button that changed state since the last frame
  70060. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  70061. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  70062. * 2) secondary trigger (same)
  70063. * 3) A (right) X (left), touch, pressed = value
  70064. * 4) B / Y
  70065. * 5) thumb rest
  70066. * @param buttonIdx Which button index changed
  70067. * @param state New state of the button
  70068. * @param changes Which properties on the state changed since last frame
  70069. */
  70070. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70071. var notifyObject = state; //{ state: state, changes: changes };
  70072. var triggerDirection = this.hand === 'right' ? -1 : 1;
  70073. switch (buttonIdx) {
  70074. case 0:
  70075. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  70076. return;
  70077. case 1:// index trigger
  70078. if (this._defaultModel) {
  70079. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  70080. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  70081. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  70082. }
  70083. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  70084. return;
  70085. case 2:// secondary trigger
  70086. if (this._defaultModel) {
  70087. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  70088. }
  70089. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  70090. return;
  70091. case 3:
  70092. if (this._defaultModel) {
  70093. if (notifyObject.pressed) {
  70094. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  70095. }
  70096. else {
  70097. (this._defaultModel.getChildren()[1]).position.y = 0;
  70098. }
  70099. }
  70100. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  70101. return;
  70102. case 4:
  70103. if (this._defaultModel) {
  70104. if (notifyObject.pressed) {
  70105. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  70106. }
  70107. else {
  70108. (this._defaultModel.getChildren()[2]).position.y = 0;
  70109. }
  70110. }
  70111. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  70112. return;
  70113. case 5:
  70114. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  70115. return;
  70116. }
  70117. };
  70118. /**
  70119. * Base Url for the controller model.
  70120. */
  70121. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  70122. /**
  70123. * File name for the left controller model.
  70124. */
  70125. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  70126. /**
  70127. * File name for the right controller model.
  70128. */
  70129. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  70130. return OculusTouchController;
  70131. }(BABYLON.WebVRController));
  70132. BABYLON.OculusTouchController = OculusTouchController;
  70133. })(BABYLON || (BABYLON = {}));
  70134. //# sourceMappingURL=babylon.oculusTouchController.js.map
  70135. "use strict";
  70136. var BABYLON;
  70137. (function (BABYLON) {
  70138. /**
  70139. * Vive Controller
  70140. */
  70141. var ViveController = /** @class */ (function (_super) {
  70142. __extends(ViveController, _super);
  70143. /**
  70144. * Creates a new ViveController from a gamepad
  70145. * @param vrGamepad the gamepad that the controller should be created from
  70146. */
  70147. function ViveController(vrGamepad) {
  70148. var _this = _super.call(this, vrGamepad) || this;
  70149. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  70150. _this._invertLeftStickY = true;
  70151. return _this;
  70152. }
  70153. /**
  70154. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70155. * @param scene scene in which to add meshes
  70156. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70157. */
  70158. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70159. var _this = this;
  70160. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  70161. /*
  70162. Parent Mesh name: ViveWand
  70163. - body
  70164. - r_gripper
  70165. - l_gripper
  70166. - menu_button
  70167. - system_button
  70168. - trackpad
  70169. - trigger
  70170. - LED
  70171. */
  70172. _this._defaultModel = newMeshes[1];
  70173. _this.attachToMesh(_this._defaultModel);
  70174. if (meshLoaded) {
  70175. meshLoaded(_this._defaultModel);
  70176. }
  70177. });
  70178. };
  70179. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  70180. /**
  70181. * Fired when the left button on this controller is modified
  70182. */
  70183. get: function () {
  70184. return this.onMainButtonStateChangedObservable;
  70185. },
  70186. enumerable: true,
  70187. configurable: true
  70188. });
  70189. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  70190. /**
  70191. * Fired when the right button on this controller is modified
  70192. */
  70193. get: function () {
  70194. return this.onMainButtonStateChangedObservable;
  70195. },
  70196. enumerable: true,
  70197. configurable: true
  70198. });
  70199. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  70200. /**
  70201. * Fired when the menu button on this controller is modified
  70202. */
  70203. get: function () {
  70204. return this.onSecondaryButtonStateChangedObservable;
  70205. },
  70206. enumerable: true,
  70207. configurable: true
  70208. });
  70209. /**
  70210. * Called once for each button that changed state since the last frame
  70211. * Vive mapping:
  70212. * 0: touchpad
  70213. * 1: trigger
  70214. * 2: left AND right buttons
  70215. * 3: menu button
  70216. * @param buttonIdx Which button index changed
  70217. * @param state New state of the button
  70218. * @param changes Which properties on the state changed since last frame
  70219. */
  70220. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70221. var notifyObject = state; //{ state: state, changes: changes };
  70222. switch (buttonIdx) {
  70223. case 0:
  70224. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  70225. return;
  70226. case 1:// index trigger
  70227. if (this._defaultModel) {
  70228. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  70229. }
  70230. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  70231. return;
  70232. case 2:// left AND right button
  70233. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  70234. return;
  70235. case 3:
  70236. if (this._defaultModel) {
  70237. if (notifyObject.pressed) {
  70238. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  70239. }
  70240. else {
  70241. (this._defaultModel.getChildren()[2]).position.y = 0;
  70242. }
  70243. }
  70244. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  70245. return;
  70246. }
  70247. };
  70248. /**
  70249. * Base Url for the controller model.
  70250. */
  70251. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  70252. /**
  70253. * File name for the controller model.
  70254. */
  70255. ViveController.MODEL_FILENAME = 'wand.babylon';
  70256. return ViveController;
  70257. }(BABYLON.WebVRController));
  70258. BABYLON.ViveController = ViveController;
  70259. })(BABYLON || (BABYLON = {}));
  70260. //# sourceMappingURL=babylon.viveController.js.map
  70261. "use strict";
  70262. var BABYLON;
  70263. (function (BABYLON) {
  70264. /**
  70265. * Generic Controller
  70266. */
  70267. var GenericController = /** @class */ (function (_super) {
  70268. __extends(GenericController, _super);
  70269. /**
  70270. * Creates a new GenericController from a gamepad
  70271. * @param vrGamepad the gamepad that the controller should be created from
  70272. */
  70273. function GenericController(vrGamepad) {
  70274. return _super.call(this, vrGamepad) || this;
  70275. }
  70276. /**
  70277. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70278. * @param scene scene in which to add meshes
  70279. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70280. */
  70281. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70282. var _this = this;
  70283. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  70284. _this._defaultModel = newMeshes[1];
  70285. _this.attachToMesh(_this._defaultModel);
  70286. if (meshLoaded) {
  70287. meshLoaded(_this._defaultModel);
  70288. }
  70289. });
  70290. };
  70291. /**
  70292. * Called once for each button that changed state since the last frame
  70293. * @param buttonIdx Which button index changed
  70294. * @param state New state of the button
  70295. * @param changes Which properties on the state changed since last frame
  70296. */
  70297. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70298. console.log("Button id: " + buttonIdx + "state: ");
  70299. console.dir(state);
  70300. };
  70301. /**
  70302. * Base Url for the controller model.
  70303. */
  70304. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70305. /**
  70306. * File name for the controller model.
  70307. */
  70308. GenericController.MODEL_FILENAME = 'generic.babylon';
  70309. return GenericController;
  70310. }(BABYLON.WebVRController));
  70311. BABYLON.GenericController = GenericController;
  70312. })(BABYLON || (BABYLON = {}));
  70313. //# sourceMappingURL=babylon.genericController.js.map
  70314. "use strict";
  70315. var BABYLON;
  70316. (function (BABYLON) {
  70317. /**
  70318. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  70319. */
  70320. var LoadedMeshInfo = /** @class */ (function () {
  70321. function LoadedMeshInfo() {
  70322. /**
  70323. * Map of the button meshes contained in the controller
  70324. */
  70325. this.buttonMeshes = {};
  70326. /**
  70327. * Map of the axis meshes contained in the controller
  70328. */
  70329. this.axisMeshes = {};
  70330. }
  70331. return LoadedMeshInfo;
  70332. }());
  70333. /**
  70334. * Defines the WindowsMotionController object that the state of the windows motion controller
  70335. */
  70336. var WindowsMotionController = /** @class */ (function (_super) {
  70337. __extends(WindowsMotionController, _super);
  70338. /**
  70339. * Creates a new WindowsMotionController from a gamepad
  70340. * @param vrGamepad the gamepad that the controller should be created from
  70341. */
  70342. function WindowsMotionController(vrGamepad) {
  70343. var _this = _super.call(this, vrGamepad) || this;
  70344. _this._mapping = {
  70345. // Semantic button names
  70346. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  70347. // A mapping of the button name to glTF model node name
  70348. // that should be transformed by button value.
  70349. buttonMeshNames: {
  70350. 'trigger': 'SELECT',
  70351. 'menu': 'MENU',
  70352. 'grip': 'GRASP',
  70353. 'thumbstick': 'THUMBSTICK_PRESS',
  70354. 'trackpad': 'TOUCHPAD_PRESS'
  70355. },
  70356. // This mapping is used to translate from the Motion Controller to Babylon semantics
  70357. buttonObservableNames: {
  70358. 'trigger': 'onTriggerStateChangedObservable',
  70359. 'menu': 'onSecondaryButtonStateChangedObservable',
  70360. 'grip': 'onMainButtonStateChangedObservable',
  70361. 'thumbstick': 'onPadStateChangedObservable',
  70362. 'trackpad': 'onTrackpadChangedObservable'
  70363. },
  70364. // A mapping of the axis name to glTF model node name
  70365. // that should be transformed by axis value.
  70366. // This array mirrors the browserGamepad.axes array, such that
  70367. // the mesh corresponding to axis 0 is in this array index 0.
  70368. axisMeshNames: [
  70369. 'THUMBSTICK_X',
  70370. 'THUMBSTICK_Y',
  70371. 'TOUCHPAD_TOUCH_X',
  70372. 'TOUCHPAD_TOUCH_Y'
  70373. ],
  70374. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  70375. };
  70376. /**
  70377. * Fired when the trackpad on this controller is clicked
  70378. */
  70379. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  70380. /**
  70381. * Fired when the trackpad on this controller is modified
  70382. */
  70383. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  70384. /**
  70385. * The current x and y values of this controller's trackpad
  70386. */
  70387. _this.trackpad = { x: 0, y: 0 };
  70388. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  70389. _this._loadedMeshInfo = null;
  70390. return _this;
  70391. }
  70392. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  70393. /**
  70394. * Fired when the trigger on this controller is modified
  70395. */
  70396. get: function () {
  70397. return this.onTriggerStateChangedObservable;
  70398. },
  70399. enumerable: true,
  70400. configurable: true
  70401. });
  70402. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  70403. /**
  70404. * Fired when the menu button on this controller is modified
  70405. */
  70406. get: function () {
  70407. return this.onSecondaryButtonStateChangedObservable;
  70408. },
  70409. enumerable: true,
  70410. configurable: true
  70411. });
  70412. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  70413. /**
  70414. * Fired when the grip button on this controller is modified
  70415. */
  70416. get: function () {
  70417. return this.onMainButtonStateChangedObservable;
  70418. },
  70419. enumerable: true,
  70420. configurable: true
  70421. });
  70422. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  70423. /**
  70424. * Fired when the thumbstick button on this controller is modified
  70425. */
  70426. get: function () {
  70427. return this.onPadStateChangedObservable;
  70428. },
  70429. enumerable: true,
  70430. configurable: true
  70431. });
  70432. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  70433. /**
  70434. * Fired when the touchpad button on this controller is modified
  70435. */
  70436. get: function () {
  70437. return this.onTrackpadChangedObservable;
  70438. },
  70439. enumerable: true,
  70440. configurable: true
  70441. });
  70442. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  70443. /**
  70444. * Fired when the touchpad values on this controller are modified
  70445. */
  70446. get: function () {
  70447. return this.onTrackpadValuesChangedObservable;
  70448. },
  70449. enumerable: true,
  70450. configurable: true
  70451. });
  70452. /**
  70453. * Called once per frame by the engine.
  70454. */
  70455. WindowsMotionController.prototype.update = function () {
  70456. _super.prototype.update.call(this);
  70457. if (this.browserGamepad.axes) {
  70458. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  70459. this.trackpad.x = this.browserGamepad["axes"][2];
  70460. this.trackpad.y = this.browserGamepad["axes"][3];
  70461. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  70462. }
  70463. // Only need to animate axes if there is a loaded mesh
  70464. if (this._loadedMeshInfo) {
  70465. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  70466. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  70467. }
  70468. }
  70469. }
  70470. };
  70471. /**
  70472. * Called once for each button that changed state since the last frame
  70473. * @param buttonIdx Which button index changed
  70474. * @param state New state of the button
  70475. * @param changes Which properties on the state changed since last frame
  70476. */
  70477. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70478. var buttonName = this._mapping.buttons[buttonIdx];
  70479. if (!buttonName) {
  70480. return;
  70481. }
  70482. // Only emit events for buttons that we know how to map from index to name
  70483. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  70484. if (observable) {
  70485. observable.notifyObservers(state);
  70486. }
  70487. this._lerpButtonTransform(buttonName, state.value);
  70488. };
  70489. /**
  70490. * Moves the buttons on the controller mesh based on their current state
  70491. * @param buttonName the name of the button to move
  70492. * @param buttonValue the value of the button which determines the buttons new position
  70493. */
  70494. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  70495. // If there is no loaded mesh, there is nothing to transform.
  70496. if (!this._loadedMeshInfo) {
  70497. return;
  70498. }
  70499. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  70500. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  70501. return;
  70502. }
  70503. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  70504. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  70505. };
  70506. /**
  70507. * Moves the axis on the controller mesh based on its current state
  70508. * @param axis the index of the axis
  70509. * @param axisValue the value of the axis which determines the meshes new position
  70510. * @ignore
  70511. */
  70512. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  70513. if (!this._loadedMeshInfo) {
  70514. return;
  70515. }
  70516. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  70517. if (!meshInfo) {
  70518. return;
  70519. }
  70520. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  70521. return;
  70522. }
  70523. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  70524. var lerpValue = axisValue * 0.5 + 0.5;
  70525. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  70526. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  70527. };
  70528. /**
  70529. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70530. * @param scene scene in which to add meshes
  70531. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70532. */
  70533. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  70534. var _this = this;
  70535. if (forceDefault === void 0) { forceDefault = false; }
  70536. var path;
  70537. var filename;
  70538. // Checking if GLB loader is present
  70539. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  70540. // Determine the device specific folder based on the ID suffix
  70541. var device = 'default';
  70542. if (this.id && !forceDefault) {
  70543. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  70544. device = ((match && match[0]) || device);
  70545. }
  70546. // Hand
  70547. if (this.hand === 'left') {
  70548. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  70549. }
  70550. else {
  70551. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  70552. }
  70553. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  70554. }
  70555. else {
  70556. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  70557. path = BABYLON.GenericController.MODEL_BASE_URL;
  70558. filename = BABYLON.GenericController.MODEL_FILENAME;
  70559. }
  70560. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  70561. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  70562. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  70563. if (!_this._loadedMeshInfo) {
  70564. return;
  70565. }
  70566. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  70567. _this.attachToMesh(_this._defaultModel);
  70568. if (meshLoaded) {
  70569. meshLoaded(_this._defaultModel);
  70570. }
  70571. }, null, function (scene, message) {
  70572. BABYLON.Tools.Log(message);
  70573. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  70574. if (!forceDefault) {
  70575. _this.initControllerMesh(scene, meshLoaded, true);
  70576. }
  70577. });
  70578. };
  70579. /**
  70580. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  70581. * can be transformed by button presses and axes values, based on this._mapping.
  70582. *
  70583. * @param scene scene in which the meshes exist
  70584. * @param meshes list of meshes that make up the controller model to process
  70585. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  70586. */
  70587. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  70588. var loadedMeshInfo = null;
  70589. // Create a new mesh to contain the glTF hierarchy
  70590. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  70591. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  70592. var childMesh = null;
  70593. for (var i = 0; i < meshes.length; i++) {
  70594. var mesh = meshes[i];
  70595. if (!mesh.parent) {
  70596. // Exclude controller meshes from picking results
  70597. mesh.isPickable = false;
  70598. // Handle root node, attach to the new parentMesh
  70599. childMesh = mesh;
  70600. break;
  70601. }
  70602. }
  70603. if (childMesh) {
  70604. childMesh.setParent(parentMesh);
  70605. // Create our mesh info. Note that this method will always return non-null.
  70606. loadedMeshInfo = this.createMeshInfo(parentMesh);
  70607. }
  70608. else {
  70609. BABYLON.Tools.Warn('Could not find root node in model file.');
  70610. }
  70611. return loadedMeshInfo;
  70612. };
  70613. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  70614. var loadedMeshInfo = new LoadedMeshInfo();
  70615. var i;
  70616. loadedMeshInfo.rootNode = rootNode;
  70617. // Reset the caches
  70618. loadedMeshInfo.buttonMeshes = {};
  70619. loadedMeshInfo.axisMeshes = {};
  70620. // Button Meshes
  70621. for (i = 0; i < this._mapping.buttons.length; i++) {
  70622. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  70623. if (!buttonMeshName) {
  70624. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  70625. continue;
  70626. }
  70627. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  70628. if (!buttonMesh) {
  70629. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  70630. continue;
  70631. }
  70632. var buttonMeshInfo = {
  70633. index: i,
  70634. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  70635. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  70636. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  70637. };
  70638. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  70639. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  70640. }
  70641. else {
  70642. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  70643. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  70644. '(VALUE: ' + !!buttonMeshInfo.value +
  70645. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  70646. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  70647. ')');
  70648. }
  70649. }
  70650. // Axis Meshes
  70651. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  70652. var axisMeshName = this._mapping.axisMeshNames[i];
  70653. if (!axisMeshName) {
  70654. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  70655. continue;
  70656. }
  70657. var axisMesh = getChildByName(rootNode, axisMeshName);
  70658. if (!axisMesh) {
  70659. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  70660. continue;
  70661. }
  70662. var axisMeshInfo = {
  70663. index: i,
  70664. value: getImmediateChildByName(axisMesh, 'VALUE'),
  70665. min: getImmediateChildByName(axisMesh, 'MIN'),
  70666. max: getImmediateChildByName(axisMesh, 'MAX')
  70667. };
  70668. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  70669. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  70670. }
  70671. else {
  70672. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  70673. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  70674. '(VALUE: ' + !!axisMeshInfo.value +
  70675. ', MIN: ' + !!axisMeshInfo.min +
  70676. ', MAX:' + !!axisMeshInfo.max +
  70677. ')');
  70678. }
  70679. }
  70680. // Pointing Ray
  70681. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  70682. if (!loadedMeshInfo.pointingPoseNode) {
  70683. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  70684. }
  70685. return loadedMeshInfo;
  70686. // Look through all children recursively. This will return null if no mesh exists with the given name.
  70687. function getChildByName(node, name) {
  70688. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  70689. }
  70690. // Look through only immediate children. This will return null if no mesh exists with the given name.
  70691. function getImmediateChildByName(node, name) {
  70692. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  70693. }
  70694. };
  70695. /**
  70696. * Gets the ray of the controller in the direction the controller is pointing
  70697. * @param length the length the resulting ray should be
  70698. * @returns a ray in the direction the controller is pointing
  70699. */
  70700. WindowsMotionController.prototype.getForwardRay = function (length) {
  70701. if (length === void 0) { length = 100; }
  70702. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  70703. return _super.prototype.getForwardRay.call(this, length);
  70704. }
  70705. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  70706. var origin = m.getTranslation();
  70707. var forward = new BABYLON.Vector3(0, 0, -1);
  70708. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  70709. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  70710. return new BABYLON.Ray(origin, direction, length);
  70711. };
  70712. /**
  70713. * Disposes of the controller
  70714. */
  70715. WindowsMotionController.prototype.dispose = function () {
  70716. _super.prototype.dispose.call(this);
  70717. this.onTrackpadChangedObservable.clear();
  70718. };
  70719. /**
  70720. * The base url used to load the left and right controller models
  70721. */
  70722. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  70723. /**
  70724. * The name of the left controller model file
  70725. */
  70726. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  70727. /**
  70728. * The name of the right controller model file
  70729. */
  70730. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  70731. /**
  70732. * The controller name prefix for this controller type
  70733. */
  70734. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  70735. /**
  70736. * The controller id pattern for this controller type
  70737. */
  70738. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  70739. return WindowsMotionController;
  70740. }(BABYLON.WebVRController));
  70741. BABYLON.WindowsMotionController = WindowsMotionController;
  70742. })(BABYLON || (BABYLON = {}));
  70743. //# sourceMappingURL=babylon.windowsMotionController.js.map
  70744. "use strict";
  70745. var BABYLON;
  70746. (function (BABYLON) {
  70747. /**
  70748. * Gear VR Controller
  70749. */
  70750. var GearVRController = /** @class */ (function (_super) {
  70751. __extends(GearVRController, _super);
  70752. /**
  70753. * Creates a new GearVRController from a gamepad
  70754. * @param vrGamepad the gamepad that the controller should be created from
  70755. */
  70756. function GearVRController(vrGamepad) {
  70757. var _this = _super.call(this, vrGamepad) || this;
  70758. _this._buttonIndexToObservableNameMap = [
  70759. 'onTrackpadChangedObservable',
  70760. 'onTriggerStateChangedObservable' // Trigger
  70761. ];
  70762. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  70763. return _this;
  70764. }
  70765. /**
  70766. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70767. * @param scene scene in which to add meshes
  70768. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70769. */
  70770. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70771. var _this = this;
  70772. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  70773. _this._defaultModel = newMeshes[1];
  70774. _this.attachToMesh(_this._defaultModel);
  70775. if (meshLoaded) {
  70776. meshLoaded(_this._defaultModel);
  70777. }
  70778. });
  70779. };
  70780. /**
  70781. * Called once for each button that changed state since the last frame
  70782. * @param buttonIdx Which button index changed
  70783. * @param state New state of the button
  70784. * @param changes Which properties on the state changed since last frame
  70785. */
  70786. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70787. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  70788. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  70789. // Only emit events for buttons that we know how to map from index to observable
  70790. var observable = this[observableName];
  70791. if (observable) {
  70792. observable.notifyObservers(state);
  70793. }
  70794. }
  70795. };
  70796. /**
  70797. * Base Url for the controller model.
  70798. */
  70799. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70800. /**
  70801. * File name for the controller model.
  70802. */
  70803. GearVRController.MODEL_FILENAME = 'generic.babylon';
  70804. /**
  70805. * Gamepad Id prefix used to identify this controller.
  70806. */
  70807. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  70808. return GearVRController;
  70809. }(BABYLON.WebVRController));
  70810. BABYLON.GearVRController = GearVRController;
  70811. })(BABYLON || (BABYLON = {}));
  70812. //# sourceMappingURL=babylon.gearVRController.js.map
  70813. "use strict";
  70814. var BABYLON;
  70815. (function (BABYLON) {
  70816. /**
  70817. * Google Daydream controller
  70818. */
  70819. var DaydreamController = /** @class */ (function (_super) {
  70820. __extends(DaydreamController, _super);
  70821. /**
  70822. * Creates a new DaydreamController from a gamepad
  70823. * @param vrGamepad the gamepad that the controller should be created from
  70824. */
  70825. function DaydreamController(vrGamepad) {
  70826. var _this = _super.call(this, vrGamepad) || this;
  70827. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  70828. return _this;
  70829. }
  70830. /**
  70831. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70832. * @param scene scene in which to add meshes
  70833. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70834. */
  70835. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70836. var _this = this;
  70837. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  70838. _this._defaultModel = newMeshes[1];
  70839. _this.attachToMesh(_this._defaultModel);
  70840. if (meshLoaded) {
  70841. meshLoaded(_this._defaultModel);
  70842. }
  70843. });
  70844. };
  70845. /**
  70846. * Called once for each button that changed state since the last frame
  70847. * @param buttonIdx Which button index changed
  70848. * @param state New state of the button
  70849. * @param changes Which properties on the state changed since last frame
  70850. */
  70851. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70852. // Daydream controller only has 1 GamepadButton (on the trackpad).
  70853. if (buttonIdx === 0) {
  70854. var observable = this.onTriggerStateChangedObservable;
  70855. if (observable) {
  70856. observable.notifyObservers(state);
  70857. }
  70858. }
  70859. else {
  70860. // If the app or home buttons are ever made available
  70861. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  70862. }
  70863. };
  70864. /**
  70865. * Base Url for the controller model.
  70866. */
  70867. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70868. /**
  70869. * File name for the controller model.
  70870. */
  70871. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  70872. /**
  70873. * Gamepad Id prefix used to identify Daydream Controller.
  70874. */
  70875. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  70876. return DaydreamController;
  70877. }(BABYLON.WebVRController));
  70878. BABYLON.DaydreamController = DaydreamController;
  70879. })(BABYLON || (BABYLON = {}));
  70880. //# sourceMappingURL=babylon.daydreamController.js.map
  70881. "use strict";
  70882. var BABYLON;
  70883. (function (BABYLON) {
  70884. var FollowCamera = /** @class */ (function (_super) {
  70885. __extends(FollowCamera, _super);
  70886. function FollowCamera(name, position, scene, lockedTarget) {
  70887. if (lockedTarget === void 0) { lockedTarget = null; }
  70888. var _this = _super.call(this, name, position, scene) || this;
  70889. _this.radius = 12;
  70890. _this.rotationOffset = 0;
  70891. _this.heightOffset = 4;
  70892. _this.cameraAcceleration = 0.05;
  70893. _this.maxCameraSpeed = 20;
  70894. _this.lockedTarget = lockedTarget;
  70895. return _this;
  70896. }
  70897. FollowCamera.prototype.getRadians = function (degrees) {
  70898. return degrees * Math.PI / 180;
  70899. };
  70900. FollowCamera.prototype.follow = function (cameraTarget) {
  70901. if (!cameraTarget)
  70902. return;
  70903. var yRotation;
  70904. if (cameraTarget.rotationQuaternion) {
  70905. var rotMatrix = new BABYLON.Matrix();
  70906. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  70907. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  70908. }
  70909. else {
  70910. yRotation = cameraTarget.rotation.y;
  70911. }
  70912. var radians = this.getRadians(this.rotationOffset) + yRotation;
  70913. var targetPosition = cameraTarget.getAbsolutePosition();
  70914. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  70915. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  70916. var dx = targetX - this.position.x;
  70917. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  70918. var dz = (targetZ) - this.position.z;
  70919. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  70920. var vy = dy * this.cameraAcceleration;
  70921. var vz = dz * this.cameraAcceleration * 2;
  70922. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  70923. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70924. }
  70925. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  70926. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70927. }
  70928. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  70929. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70930. }
  70931. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  70932. this.setTarget(targetPosition);
  70933. };
  70934. FollowCamera.prototype._checkInputs = function () {
  70935. _super.prototype._checkInputs.call(this);
  70936. if (this.lockedTarget) {
  70937. this.follow(this.lockedTarget);
  70938. }
  70939. };
  70940. FollowCamera.prototype.getClassName = function () {
  70941. return "FollowCamera";
  70942. };
  70943. __decorate([
  70944. BABYLON.serialize()
  70945. ], FollowCamera.prototype, "radius", void 0);
  70946. __decorate([
  70947. BABYLON.serialize()
  70948. ], FollowCamera.prototype, "rotationOffset", void 0);
  70949. __decorate([
  70950. BABYLON.serialize()
  70951. ], FollowCamera.prototype, "heightOffset", void 0);
  70952. __decorate([
  70953. BABYLON.serialize()
  70954. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  70955. __decorate([
  70956. BABYLON.serialize()
  70957. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  70958. __decorate([
  70959. BABYLON.serializeAsMeshReference("lockedTargetId")
  70960. ], FollowCamera.prototype, "lockedTarget", void 0);
  70961. return FollowCamera;
  70962. }(BABYLON.TargetCamera));
  70963. BABYLON.FollowCamera = FollowCamera;
  70964. var ArcFollowCamera = /** @class */ (function (_super) {
  70965. __extends(ArcFollowCamera, _super);
  70966. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  70967. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  70968. _this.alpha = alpha;
  70969. _this.beta = beta;
  70970. _this.radius = radius;
  70971. _this.target = target;
  70972. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  70973. _this.follow();
  70974. return _this;
  70975. }
  70976. ArcFollowCamera.prototype.follow = function () {
  70977. if (!this.target) {
  70978. return;
  70979. }
  70980. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  70981. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  70982. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  70983. var targetPosition = this.target.getAbsolutePosition();
  70984. this.position = targetPosition.add(this._cartesianCoordinates);
  70985. this.setTarget(targetPosition);
  70986. };
  70987. ArcFollowCamera.prototype._checkInputs = function () {
  70988. _super.prototype._checkInputs.call(this);
  70989. this.follow();
  70990. };
  70991. ArcFollowCamera.prototype.getClassName = function () {
  70992. return "ArcFollowCamera";
  70993. };
  70994. return ArcFollowCamera;
  70995. }(BABYLON.TargetCamera));
  70996. BABYLON.ArcFollowCamera = ArcFollowCamera;
  70997. })(BABYLON || (BABYLON = {}));
  70998. //# sourceMappingURL=babylon.followCamera.js.map
  70999. "use strict";
  71000. var BABYLON;
  71001. (function (BABYLON) {
  71002. // We're mainly based on the logic defined into the FreeCamera code
  71003. var UniversalCamera = /** @class */ (function (_super) {
  71004. __extends(UniversalCamera, _super);
  71005. //-- end properties for backward compatibility for inputs
  71006. function UniversalCamera(name, position, scene) {
  71007. var _this = _super.call(this, name, position, scene) || this;
  71008. _this.inputs.addGamepad();
  71009. return _this;
  71010. }
  71011. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  71012. //-- Begin properties for backward compatibility for inputs
  71013. get: function () {
  71014. var gamepad = this.inputs.attached["gamepad"];
  71015. if (gamepad)
  71016. return gamepad.gamepadAngularSensibility;
  71017. return 0;
  71018. },
  71019. set: function (value) {
  71020. var gamepad = this.inputs.attached["gamepad"];
  71021. if (gamepad)
  71022. gamepad.gamepadAngularSensibility = value;
  71023. },
  71024. enumerable: true,
  71025. configurable: true
  71026. });
  71027. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  71028. get: function () {
  71029. var gamepad = this.inputs.attached["gamepad"];
  71030. if (gamepad)
  71031. return gamepad.gamepadMoveSensibility;
  71032. return 0;
  71033. },
  71034. set: function (value) {
  71035. var gamepad = this.inputs.attached["gamepad"];
  71036. if (gamepad)
  71037. gamepad.gamepadMoveSensibility = value;
  71038. },
  71039. enumerable: true,
  71040. configurable: true
  71041. });
  71042. UniversalCamera.prototype.getClassName = function () {
  71043. return "UniversalCamera";
  71044. };
  71045. return UniversalCamera;
  71046. }(BABYLON.TouchCamera));
  71047. BABYLON.UniversalCamera = UniversalCamera;
  71048. })(BABYLON || (BABYLON = {}));
  71049. //# sourceMappingURL=babylon.universalCamera.js.map
  71050. "use strict";
  71051. var BABYLON;
  71052. (function (BABYLON) {
  71053. // We're mainly based on the logic defined into the FreeCamera code
  71054. var GamepadCamera = /** @class */ (function (_super) {
  71055. __extends(GamepadCamera, _super);
  71056. //-- end properties for backward compatibility for inputs
  71057. function GamepadCamera(name, position, scene) {
  71058. return _super.call(this, name, position, scene) || this;
  71059. }
  71060. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  71061. //-- Begin properties for backward compatibility for inputs
  71062. get: function () {
  71063. var gamepad = this.inputs.attached["gamepad"];
  71064. if (gamepad)
  71065. return gamepad.gamepadAngularSensibility;
  71066. return 0;
  71067. },
  71068. set: function (value) {
  71069. var gamepad = this.inputs.attached["gamepad"];
  71070. if (gamepad)
  71071. gamepad.gamepadAngularSensibility = value;
  71072. },
  71073. enumerable: true,
  71074. configurable: true
  71075. });
  71076. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  71077. get: function () {
  71078. var gamepad = this.inputs.attached["gamepad"];
  71079. if (gamepad)
  71080. return gamepad.gamepadMoveSensibility;
  71081. return 0;
  71082. },
  71083. set: function (value) {
  71084. var gamepad = this.inputs.attached["gamepad"];
  71085. if (gamepad)
  71086. gamepad.gamepadMoveSensibility = value;
  71087. },
  71088. enumerable: true,
  71089. configurable: true
  71090. });
  71091. GamepadCamera.prototype.getClassName = function () {
  71092. return "GamepadCamera";
  71093. };
  71094. return GamepadCamera;
  71095. }(BABYLON.UniversalCamera));
  71096. BABYLON.GamepadCamera = GamepadCamera;
  71097. })(BABYLON || (BABYLON = {}));
  71098. //# sourceMappingURL=babylon.gamepadCamera.js.map
  71099. "use strict";
  71100. var BABYLON;
  71101. (function (BABYLON) {
  71102. var PostProcessRenderPipelineManager = /** @class */ (function () {
  71103. function PostProcessRenderPipelineManager() {
  71104. this._renderPipelines = {};
  71105. }
  71106. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  71107. this._renderPipelines[renderPipeline._name] = renderPipeline;
  71108. };
  71109. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  71110. if (unique === void 0) { unique = false; }
  71111. var renderPipeline = this._renderPipelines[renderPipelineName];
  71112. if (!renderPipeline) {
  71113. return;
  71114. }
  71115. renderPipeline._attachCameras(cameras, unique);
  71116. };
  71117. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  71118. var renderPipeline = this._renderPipelines[renderPipelineName];
  71119. if (!renderPipeline) {
  71120. return;
  71121. }
  71122. renderPipeline._detachCameras(cameras);
  71123. };
  71124. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  71125. var renderPipeline = this._renderPipelines[renderPipelineName];
  71126. if (!renderPipeline) {
  71127. return;
  71128. }
  71129. renderPipeline._enableEffect(renderEffectName, cameras);
  71130. };
  71131. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  71132. var renderPipeline = this._renderPipelines[renderPipelineName];
  71133. if (!renderPipeline) {
  71134. return;
  71135. }
  71136. renderPipeline._disableEffect(renderEffectName, cameras);
  71137. };
  71138. PostProcessRenderPipelineManager.prototype.update = function () {
  71139. for (var renderPipelineName in this._renderPipelines) {
  71140. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71141. var pipeline = this._renderPipelines[renderPipelineName];
  71142. if (!pipeline.isSupported) {
  71143. pipeline.dispose();
  71144. delete this._renderPipelines[renderPipelineName];
  71145. }
  71146. else {
  71147. pipeline._update();
  71148. }
  71149. }
  71150. }
  71151. };
  71152. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  71153. for (var renderPipelineName in this._renderPipelines) {
  71154. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71155. var pipeline = this._renderPipelines[renderPipelineName];
  71156. pipeline._rebuild();
  71157. }
  71158. }
  71159. };
  71160. PostProcessRenderPipelineManager.prototype.dispose = function () {
  71161. for (var renderPipelineName in this._renderPipelines) {
  71162. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71163. var pipeline = this._renderPipelines[renderPipelineName];
  71164. pipeline.dispose();
  71165. }
  71166. }
  71167. };
  71168. return PostProcessRenderPipelineManager;
  71169. }());
  71170. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  71171. })(BABYLON || (BABYLON = {}));
  71172. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  71173. "use strict";
  71174. var BABYLON;
  71175. (function (BABYLON) {
  71176. /**
  71177. * This represents a set of one or more post processes in Babylon.
  71178. * A post process can be used to apply a shader to a texture after it is rendered.
  71179. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  71180. */
  71181. var PostProcessRenderEffect = /** @class */ (function () {
  71182. /**
  71183. * Instantiates a post process render effect.
  71184. * A post process can be used to apply a shader to a texture after it is rendered.
  71185. * @param engine The engine the effect is tied to
  71186. * @param name The name of the effect
  71187. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  71188. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  71189. */
  71190. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  71191. this._name = name;
  71192. this._singleInstance = singleInstance || true;
  71193. this._getPostProcesses = getPostProcesses;
  71194. this._cameras = {};
  71195. this._indicesForCamera = {};
  71196. this._postProcesses = {};
  71197. }
  71198. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  71199. /**
  71200. * Checks if all the post processes in the effect are supported.
  71201. */
  71202. get: function () {
  71203. for (var index in this._postProcesses) {
  71204. if (this._postProcesses.hasOwnProperty(index)) {
  71205. var pps = this._postProcesses[index];
  71206. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  71207. if (!pps[ppIndex].isSupported) {
  71208. return false;
  71209. }
  71210. }
  71211. }
  71212. }
  71213. return true;
  71214. },
  71215. enumerable: true,
  71216. configurable: true
  71217. });
  71218. /**
  71219. * Updates the current state of the effect
  71220. */
  71221. PostProcessRenderEffect.prototype._update = function () {
  71222. };
  71223. /**
  71224. * Attaches the effect on cameras
  71225. * @param cameras The camera to attach to.
  71226. */
  71227. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  71228. var _this = this;
  71229. var cameraKey;
  71230. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71231. if (!cams) {
  71232. return;
  71233. }
  71234. for (var i = 0; i < cams.length; i++) {
  71235. var camera = cams[i];
  71236. var cameraName = camera.name;
  71237. if (this._singleInstance) {
  71238. cameraKey = 0;
  71239. }
  71240. else {
  71241. cameraKey = cameraName;
  71242. }
  71243. if (!this._postProcesses[cameraKey]) {
  71244. var postProcess = this._getPostProcesses();
  71245. if (postProcess) {
  71246. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  71247. }
  71248. }
  71249. if (!this._indicesForCamera[cameraName]) {
  71250. this._indicesForCamera[cameraName] = [];
  71251. }
  71252. this._postProcesses[cameraKey].forEach(function (postProcess) {
  71253. var index = camera.attachPostProcess(postProcess);
  71254. _this._indicesForCamera[cameraName].push(index);
  71255. });
  71256. if (!this._cameras[cameraName]) {
  71257. this._cameras[cameraName] = camera;
  71258. }
  71259. }
  71260. };
  71261. /**
  71262. * Detatches the effect on cameras
  71263. * @param cameras The camera to detatch from.
  71264. */
  71265. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  71266. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71267. if (!cams) {
  71268. return;
  71269. }
  71270. for (var i = 0; i < cams.length; i++) {
  71271. var camera = cams[i];
  71272. var cameraName = camera.name;
  71273. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71274. camera.detachPostProcess(postProcess);
  71275. });
  71276. if (this._cameras[cameraName]) {
  71277. //this._indicesForCamera.splice(index, 1);
  71278. this._cameras[cameraName] = null;
  71279. }
  71280. }
  71281. };
  71282. /**
  71283. * Enables the effect on given cameras
  71284. * @param cameras The camera to enable.
  71285. */
  71286. PostProcessRenderEffect.prototype._enable = function (cameras) {
  71287. var _this = this;
  71288. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71289. if (!cams) {
  71290. return;
  71291. }
  71292. for (var i = 0; i < cams.length; i++) {
  71293. var camera = cams[i];
  71294. var cameraName = camera.name;
  71295. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  71296. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  71297. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71298. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  71299. });
  71300. }
  71301. }
  71302. }
  71303. };
  71304. /**
  71305. * Disables the effect on the given cameras
  71306. * @param cameras The camera to disable.
  71307. */
  71308. PostProcessRenderEffect.prototype._disable = function (cameras) {
  71309. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71310. if (!cams) {
  71311. return;
  71312. }
  71313. for (var i = 0; i < cams.length; i++) {
  71314. var camera = cams[i];
  71315. var cameraName = camera.name;
  71316. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71317. camera.detachPostProcess(postProcess);
  71318. });
  71319. }
  71320. };
  71321. /**
  71322. * Gets a list of the post processes contained in the effect.
  71323. * @param camera The camera to get the post processes on.
  71324. * @returns The list of the post processes in the effect.
  71325. */
  71326. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  71327. if (this._singleInstance) {
  71328. return this._postProcesses[0];
  71329. }
  71330. else {
  71331. if (!camera) {
  71332. return null;
  71333. }
  71334. return this._postProcesses[camera.name];
  71335. }
  71336. };
  71337. return PostProcessRenderEffect;
  71338. }());
  71339. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  71340. })(BABYLON || (BABYLON = {}));
  71341. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  71342. "use strict";
  71343. var BABYLON;
  71344. (function (BABYLON) {
  71345. var PostProcessRenderPipeline = /** @class */ (function () {
  71346. function PostProcessRenderPipeline(engine, name) {
  71347. this.engine = engine;
  71348. this._name = name;
  71349. this._renderEffects = {};
  71350. this._renderEffectsForIsolatedPass = new Array();
  71351. this._cameras = [];
  71352. }
  71353. PostProcessRenderPipeline.prototype.getClassName = function () {
  71354. return "PostProcessRenderPipeline";
  71355. };
  71356. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  71357. get: function () {
  71358. for (var renderEffectName in this._renderEffects) {
  71359. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71360. if (!this._renderEffects[renderEffectName].isSupported) {
  71361. return false;
  71362. }
  71363. }
  71364. }
  71365. return true;
  71366. },
  71367. enumerable: true,
  71368. configurable: true
  71369. });
  71370. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  71371. this._renderEffects[renderEffect._name] = renderEffect;
  71372. };
  71373. // private
  71374. PostProcessRenderPipeline.prototype._rebuild = function () {
  71375. };
  71376. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  71377. var renderEffects = this._renderEffects[renderEffectName];
  71378. if (!renderEffects) {
  71379. return;
  71380. }
  71381. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  71382. };
  71383. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  71384. var renderEffects = this._renderEffects[renderEffectName];
  71385. if (!renderEffects) {
  71386. return;
  71387. }
  71388. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  71389. };
  71390. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  71391. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71392. if (!cams) {
  71393. return;
  71394. }
  71395. var indicesToDelete = [];
  71396. var i;
  71397. for (i = 0; i < cams.length; i++) {
  71398. var camera = cams[i];
  71399. var cameraName = camera.name;
  71400. if (this._cameras.indexOf(camera) === -1) {
  71401. this._cameras[cameraName] = camera;
  71402. }
  71403. else if (unique) {
  71404. indicesToDelete.push(i);
  71405. }
  71406. }
  71407. for (i = 0; i < indicesToDelete.length; i++) {
  71408. cameras.splice(indicesToDelete[i], 1);
  71409. }
  71410. for (var renderEffectName in this._renderEffects) {
  71411. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71412. this._renderEffects[renderEffectName]._attachCameras(cams);
  71413. }
  71414. }
  71415. };
  71416. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  71417. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71418. if (!cams) {
  71419. return;
  71420. }
  71421. for (var renderEffectName in this._renderEffects) {
  71422. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71423. this._renderEffects[renderEffectName]._detachCameras(cams);
  71424. }
  71425. }
  71426. for (var i = 0; i < cams.length; i++) {
  71427. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  71428. }
  71429. };
  71430. PostProcessRenderPipeline.prototype._update = function () {
  71431. for (var renderEffectName in this._renderEffects) {
  71432. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71433. this._renderEffects[renderEffectName]._update();
  71434. }
  71435. }
  71436. for (var i = 0; i < this._cameras.length; i++) {
  71437. var cameraName = this._cameras[i].name;
  71438. if (this._renderEffectsForIsolatedPass[cameraName]) {
  71439. this._renderEffectsForIsolatedPass[cameraName]._update();
  71440. }
  71441. }
  71442. };
  71443. PostProcessRenderPipeline.prototype._reset = function () {
  71444. this._renderEffects = {};
  71445. this._renderEffectsForIsolatedPass = new Array();
  71446. };
  71447. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  71448. // 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)
  71449. var effectKeys = Object.keys(this._renderEffects);
  71450. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  71451. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  71452. if (postProcesses) {
  71453. postProcesses[0].samples = sampleCount;
  71454. return true;
  71455. }
  71456. }
  71457. return false;
  71458. };
  71459. PostProcessRenderPipeline.prototype.dispose = function () {
  71460. // Must be implemented by children
  71461. };
  71462. __decorate([
  71463. BABYLON.serialize()
  71464. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  71465. return PostProcessRenderPipeline;
  71466. }());
  71467. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  71468. })(BABYLON || (BABYLON = {}));
  71469. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  71470. "use strict";
  71471. var BABYLON;
  71472. (function (BABYLON) {
  71473. /**
  71474. * This represents a depth renderer in Babylon.
  71475. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  71476. */
  71477. var DepthRenderer = /** @class */ (function () {
  71478. /**
  71479. * Instantiates a depth renderer
  71480. * @param scene The scene the renderer belongs to
  71481. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  71482. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  71483. */
  71484. function DepthRenderer(scene, type, camera) {
  71485. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  71486. if (camera === void 0) { camera = null; }
  71487. var _this = this;
  71488. this._scene = scene;
  71489. this._camera = camera;
  71490. var engine = scene.getEngine();
  71491. // Render target
  71492. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  71493. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71494. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71495. this._depthMap.refreshRate = 1;
  71496. this._depthMap.renderParticles = false;
  71497. this._depthMap.renderList = null;
  71498. // Camera to get depth map from to support multiple concurrent cameras
  71499. this._depthMap.activeCamera = this._camera;
  71500. this._depthMap.ignoreCameraViewport = true;
  71501. this._depthMap.useCameraPostProcesses = false;
  71502. // set default depth value to 1.0 (far away)
  71503. this._depthMap.onClearObservable.add(function (engine) {
  71504. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  71505. });
  71506. // Custom render function
  71507. var renderSubMesh = function (subMesh) {
  71508. var mesh = subMesh.getRenderingMesh();
  71509. var scene = _this._scene;
  71510. var engine = scene.getEngine();
  71511. var material = subMesh.getMaterial();
  71512. if (!material) {
  71513. return;
  71514. }
  71515. // Culling and reverse (right handed system)
  71516. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  71517. // Managing instances
  71518. var batch = mesh._getInstancesRenderList(subMesh._id);
  71519. if (batch.mustReturn) {
  71520. return;
  71521. }
  71522. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71523. var camera = _this._camera || scene.activeCamera;
  71524. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  71525. engine.enableEffect(_this._effect);
  71526. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  71527. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71528. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  71529. // Alpha test
  71530. if (material && material.needAlphaTesting()) {
  71531. var alphaTexture = material.getAlphaTestTexture();
  71532. if (alphaTexture) {
  71533. _this._effect.setTexture("diffuseSampler", alphaTexture);
  71534. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71535. }
  71536. }
  71537. // Bones
  71538. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71539. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71540. }
  71541. // Draw
  71542. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71543. }
  71544. };
  71545. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71546. var index;
  71547. if (depthOnlySubMeshes.length) {
  71548. engine.setColorWrite(false);
  71549. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71550. renderSubMesh(depthOnlySubMeshes.data[index]);
  71551. }
  71552. engine.setColorWrite(true);
  71553. }
  71554. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71555. renderSubMesh(opaqueSubMeshes.data[index]);
  71556. }
  71557. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71558. renderSubMesh(alphaTestSubMeshes.data[index]);
  71559. }
  71560. };
  71561. }
  71562. /**
  71563. * Creates the depth rendering effect and checks if the effect is ready.
  71564. * @param subMesh The submesh to be used to render the depth map of
  71565. * @param useInstances If multiple world instances should be used
  71566. * @returns if the depth renderer is ready to render the depth map
  71567. */
  71568. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  71569. var material = subMesh.getMaterial();
  71570. if (material.disableDepthWrite) {
  71571. return false;
  71572. }
  71573. var defines = [];
  71574. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71575. var mesh = subMesh.getMesh();
  71576. // Alpha test
  71577. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  71578. defines.push("#define ALPHATEST");
  71579. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71580. attribs.push(BABYLON.VertexBuffer.UVKind);
  71581. defines.push("#define UV1");
  71582. }
  71583. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71584. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71585. defines.push("#define UV2");
  71586. }
  71587. }
  71588. // Bones
  71589. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71590. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71591. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71592. if (mesh.numBoneInfluencers > 4) {
  71593. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71594. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71595. }
  71596. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71597. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71598. }
  71599. else {
  71600. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71601. }
  71602. // Instances
  71603. if (useInstances) {
  71604. defines.push("#define INSTANCES");
  71605. attribs.push("world0");
  71606. attribs.push("world1");
  71607. attribs.push("world2");
  71608. attribs.push("world3");
  71609. }
  71610. // Get correct effect
  71611. var join = defines.join("\n");
  71612. if (this._cachedDefines !== join) {
  71613. this._cachedDefines = join;
  71614. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  71615. }
  71616. return this._effect.isReady();
  71617. };
  71618. /**
  71619. * Gets the texture which the depth map will be written to.
  71620. * @returns The depth map texture
  71621. */
  71622. DepthRenderer.prototype.getDepthMap = function () {
  71623. return this._depthMap;
  71624. };
  71625. /**
  71626. * Disposes of the depth renderer.
  71627. */
  71628. DepthRenderer.prototype.dispose = function () {
  71629. this._depthMap.dispose();
  71630. };
  71631. return DepthRenderer;
  71632. }());
  71633. BABYLON.DepthRenderer = DepthRenderer;
  71634. })(BABYLON || (BABYLON = {}));
  71635. //# sourceMappingURL=babylon.depthRenderer.js.map
  71636. "use strict";
  71637. var BABYLON;
  71638. (function (BABYLON) {
  71639. var SSAORenderingPipeline = /** @class */ (function (_super) {
  71640. __extends(SSAORenderingPipeline, _super);
  71641. /**
  71642. * @constructor
  71643. * @param {string} name - The rendering pipeline name
  71644. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71645. * @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 }
  71646. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71647. */
  71648. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  71649. var _this = _super.call(this, scene.getEngine(), name) || this;
  71650. // Members
  71651. /**
  71652. * The PassPostProcess id in the pipeline that contains the original scene color
  71653. */
  71654. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  71655. /**
  71656. * The SSAO PostProcess id in the pipeline
  71657. */
  71658. _this.SSAORenderEffect = "SSAORenderEffect";
  71659. /**
  71660. * The horizontal blur PostProcess id in the pipeline
  71661. */
  71662. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  71663. /**
  71664. * The vertical blur PostProcess id in the pipeline
  71665. */
  71666. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  71667. /**
  71668. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  71669. */
  71670. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  71671. /**
  71672. * The output strength of the SSAO post-process. Default value is 1.0.
  71673. */
  71674. _this.totalStrength = 1.0;
  71675. /**
  71676. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  71677. */
  71678. _this.radius = 0.0001;
  71679. /**
  71680. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  71681. * Must not be equal to fallOff and superior to fallOff.
  71682. * Default value is 0.975
  71683. */
  71684. _this.area = 0.0075;
  71685. /**
  71686. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  71687. * Must not be equal to area and inferior to area.
  71688. * Default value is 0.0
  71689. */
  71690. _this.fallOff = 0.000001;
  71691. /**
  71692. * The base color of the SSAO post-process
  71693. * The final result is "base + ssao" between [0, 1]
  71694. */
  71695. _this.base = 0.5;
  71696. _this._firstUpdate = true;
  71697. _this._scene = scene;
  71698. // Set up assets
  71699. _this._createRandomTexture();
  71700. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  71701. var ssaoRatio = ratio.ssaoRatio || ratio;
  71702. var combineRatio = ratio.combineRatio || ratio;
  71703. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  71704. _this._createSSAOPostProcess(ssaoRatio);
  71705. _this._createBlurPostProcess(ssaoRatio);
  71706. _this._createSSAOCombinePostProcess(combineRatio);
  71707. // Set up pipeline
  71708. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  71709. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  71710. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  71711. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  71712. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  71713. // Finish
  71714. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71715. if (cameras)
  71716. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  71717. return _this;
  71718. }
  71719. // Public Methods
  71720. /**
  71721. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  71722. */
  71723. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  71724. if (disableDepthRender === void 0) { disableDepthRender = false; }
  71725. for (var i = 0; i < this._scene.cameras.length; i++) {
  71726. var camera = this._scene.cameras[i];
  71727. this._originalColorPostProcess.dispose(camera);
  71728. this._ssaoPostProcess.dispose(camera);
  71729. this._blurHPostProcess.dispose(camera);
  71730. this._blurVPostProcess.dispose(camera);
  71731. this._ssaoCombinePostProcess.dispose(camera);
  71732. }
  71733. this._randomTexture.dispose();
  71734. if (disableDepthRender)
  71735. this._scene.disableDepthRenderer();
  71736. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  71737. _super.prototype.dispose.call(this);
  71738. };
  71739. // Private Methods
  71740. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  71741. var _this = this;
  71742. var size = 16;
  71743. 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);
  71744. 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);
  71745. this._blurHPostProcess.onActivateObservable.add(function () {
  71746. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  71747. _this._blurHPostProcess.kernel = size * dw;
  71748. });
  71749. this._blurVPostProcess.onActivateObservable.add(function () {
  71750. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  71751. _this._blurVPostProcess.kernel = size * dw;
  71752. });
  71753. };
  71754. SSAORenderingPipeline.prototype._rebuild = function () {
  71755. this._firstUpdate = true;
  71756. _super.prototype._rebuild.call(this);
  71757. };
  71758. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  71759. var _this = this;
  71760. var numSamples = 16;
  71761. var sampleSphere = [
  71762. 0.5381, 0.1856, -0.4319,
  71763. 0.1379, 0.2486, 0.4430,
  71764. 0.3371, 0.5679, -0.0057,
  71765. -0.6999, -0.0451, -0.0019,
  71766. 0.0689, -0.1598, -0.8547,
  71767. 0.0560, 0.0069, -0.1843,
  71768. -0.0146, 0.1402, 0.0762,
  71769. 0.0100, -0.1924, -0.0344,
  71770. -0.3577, -0.5301, -0.4358,
  71771. -0.3169, 0.1063, 0.0158,
  71772. 0.0103, -0.5869, 0.0046,
  71773. -0.0897, -0.4940, 0.3287,
  71774. 0.7119, -0.0154, -0.0918,
  71775. -0.0533, 0.0596, -0.5411,
  71776. 0.0352, -0.0631, 0.5460,
  71777. -0.4776, 0.2847, -0.0271
  71778. ];
  71779. var samplesFactor = 1.0 / numSamples;
  71780. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  71781. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  71782. "area", "fallOff", "base", "range", "viewport"
  71783. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  71784. this._ssaoPostProcess.onApply = function (effect) {
  71785. if (_this._firstUpdate) {
  71786. effect.setArray3("sampleSphere", sampleSphere);
  71787. effect.setFloat("samplesFactor", samplesFactor);
  71788. effect.setFloat("randTextureTiles", 4.0);
  71789. }
  71790. effect.setFloat("totalStrength", _this.totalStrength);
  71791. effect.setFloat("radius", _this.radius);
  71792. effect.setFloat("area", _this.area);
  71793. effect.setFloat("fallOff", _this.fallOff);
  71794. effect.setFloat("base", _this.base);
  71795. effect.setTexture("textureSampler", _this._depthTexture);
  71796. effect.setTexture("randomSampler", _this._randomTexture);
  71797. };
  71798. };
  71799. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  71800. var _this = this;
  71801. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71802. this._ssaoCombinePostProcess.onApply = function (effect) {
  71803. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  71804. };
  71805. };
  71806. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  71807. var size = 512;
  71808. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71809. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71810. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71811. var context = this._randomTexture.getContext();
  71812. var rand = function (min, max) {
  71813. return Math.random() * (max - min) + min;
  71814. };
  71815. var randVector = BABYLON.Vector3.Zero();
  71816. for (var x = 0; x < size; x++) {
  71817. for (var y = 0; y < size; y++) {
  71818. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  71819. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  71820. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  71821. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  71822. context.fillRect(x, y, 1, 1);
  71823. }
  71824. }
  71825. this._randomTexture.update(false);
  71826. };
  71827. __decorate([
  71828. BABYLON.serialize()
  71829. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  71830. __decorate([
  71831. BABYLON.serialize()
  71832. ], SSAORenderingPipeline.prototype, "radius", void 0);
  71833. __decorate([
  71834. BABYLON.serialize()
  71835. ], SSAORenderingPipeline.prototype, "area", void 0);
  71836. __decorate([
  71837. BABYLON.serialize()
  71838. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  71839. __decorate([
  71840. BABYLON.serialize()
  71841. ], SSAORenderingPipeline.prototype, "base", void 0);
  71842. return SSAORenderingPipeline;
  71843. }(BABYLON.PostProcessRenderPipeline));
  71844. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  71845. })(BABYLON || (BABYLON = {}));
  71846. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  71847. "use strict";
  71848. var BABYLON;
  71849. (function (BABYLON) {
  71850. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  71851. __extends(SSAO2RenderingPipeline, _super);
  71852. /**
  71853. * @constructor
  71854. * @param {string} name - The rendering pipeline name
  71855. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71856. * @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 }
  71857. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71858. */
  71859. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  71860. var _this = _super.call(this, scene.getEngine(), name) || this;
  71861. // Members
  71862. /**
  71863. * The PassPostProcess id in the pipeline that contains the original scene color
  71864. */
  71865. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  71866. /**
  71867. * The SSAO PostProcess id in the pipeline
  71868. */
  71869. _this.SSAORenderEffect = "SSAORenderEffect";
  71870. /**
  71871. * The horizontal blur PostProcess id in the pipeline
  71872. */
  71873. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  71874. /**
  71875. * The vertical blur PostProcess id in the pipeline
  71876. */
  71877. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  71878. /**
  71879. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  71880. */
  71881. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  71882. /**
  71883. * The output strength of the SSAO post-process. Default value is 1.0.
  71884. */
  71885. _this.totalStrength = 1.0;
  71886. /**
  71887. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  71888. */
  71889. _this.maxZ = 100.0;
  71890. /**
  71891. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  71892. */
  71893. _this.minZAspect = 0.2;
  71894. /**
  71895. * Number of samples used for the SSAO calculations. Default value is 8
  71896. */
  71897. _this._samples = 8;
  71898. /**
  71899. * Are we using bilateral blur ?
  71900. */
  71901. _this._expensiveBlur = true;
  71902. /**
  71903. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  71904. */
  71905. _this.radius = 2.0;
  71906. /**
  71907. * The base color of the SSAO post-process
  71908. * The final result is "base + ssao" between [0, 1]
  71909. */
  71910. _this.base = 0.1;
  71911. _this._firstUpdate = true;
  71912. _this._scene = scene;
  71913. if (!_this.isSupported) {
  71914. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  71915. return _this;
  71916. }
  71917. var ssaoRatio = ratio.ssaoRatio || ratio;
  71918. var blurRatio = ratio.blurRatio || ratio;
  71919. // Set up assets
  71920. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  71921. _this._createRandomTexture();
  71922. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  71923. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  71924. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  71925. _this._createSSAOPostProcess(1.0);
  71926. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  71927. _this._createSSAOCombinePostProcess(blurRatio);
  71928. // Set up pipeline
  71929. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  71930. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  71931. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  71932. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  71933. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  71934. // Finish
  71935. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71936. if (cameras)
  71937. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  71938. return _this;
  71939. }
  71940. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  71941. get: function () {
  71942. return this._samples;
  71943. },
  71944. set: function (n) {
  71945. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  71946. this._samples = n;
  71947. this._sampleSphere = this._generateHemisphere();
  71948. this._firstUpdate = true;
  71949. },
  71950. enumerable: true,
  71951. configurable: true
  71952. });
  71953. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  71954. get: function () {
  71955. return this._expensiveBlur;
  71956. },
  71957. set: function (b) {
  71958. 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"]);
  71959. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  71960. this._expensiveBlur = b;
  71961. this._firstUpdate = true;
  71962. },
  71963. enumerable: true,
  71964. configurable: true
  71965. });
  71966. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  71967. /**
  71968. * Support test.
  71969. */
  71970. get: function () {
  71971. var engine = BABYLON.Engine.LastCreatedEngine;
  71972. if (!engine) {
  71973. return false;
  71974. }
  71975. return engine.getCaps().drawBuffersExtension;
  71976. },
  71977. enumerable: true,
  71978. configurable: true
  71979. });
  71980. // Public Methods
  71981. /**
  71982. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  71983. */
  71984. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  71985. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  71986. for (var i = 0; i < this._scene.cameras.length; i++) {
  71987. var camera = this._scene.cameras[i];
  71988. this._originalColorPostProcess.dispose(camera);
  71989. this._ssaoPostProcess.dispose(camera);
  71990. this._blurHPostProcess.dispose(camera);
  71991. this._blurVPostProcess.dispose(camera);
  71992. this._ssaoCombinePostProcess.dispose(camera);
  71993. }
  71994. this._randomTexture.dispose();
  71995. if (disableGeometryBufferRenderer)
  71996. this._scene.disableGeometryBufferRenderer();
  71997. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  71998. _super.prototype.dispose.call(this);
  71999. };
  72000. // Private Methods
  72001. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  72002. var _this = this;
  72003. this._samplerOffsets = [];
  72004. var expensive = this.expensiveBlur;
  72005. for (var i = -8; i < 8; i++) {
  72006. this._samplerOffsets.push(i * 2 + 0.5);
  72007. }
  72008. 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");
  72009. this._blurHPostProcess.onApply = function (effect) {
  72010. if (!_this._scene.activeCamera) {
  72011. return;
  72012. }
  72013. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  72014. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72015. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72016. effect.setFloat("radius", _this.radius);
  72017. effect.setTexture("depthSampler", _this._depthTexture);
  72018. if (_this._firstUpdate) {
  72019. effect.setArray("samplerOffsets", _this._samplerOffsets);
  72020. }
  72021. };
  72022. 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");
  72023. this._blurVPostProcess.onApply = function (effect) {
  72024. if (!_this._scene.activeCamera) {
  72025. return;
  72026. }
  72027. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  72028. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72029. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72030. effect.setFloat("radius", _this.radius);
  72031. effect.setTexture("depthSampler", _this._depthTexture);
  72032. if (_this._firstUpdate) {
  72033. effect.setArray("samplerOffsets", _this._samplerOffsets);
  72034. _this._firstUpdate = false;
  72035. }
  72036. };
  72037. };
  72038. SSAO2RenderingPipeline.prototype._rebuild = function () {
  72039. this._firstUpdate = true;
  72040. _super.prototype._rebuild.call(this);
  72041. };
  72042. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  72043. var numSamples = this.samples;
  72044. var result = [];
  72045. var vector, scale;
  72046. var rand = function (min, max) {
  72047. return Math.random() * (max - min) + min;
  72048. };
  72049. var i = 0;
  72050. while (i < numSamples) {
  72051. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  72052. vector.normalize();
  72053. scale = i / numSamples;
  72054. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  72055. vector.scaleInPlace(scale);
  72056. result.push(vector.x, vector.y, vector.z);
  72057. i++;
  72058. }
  72059. return result;
  72060. };
  72061. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72062. var _this = this;
  72063. var numSamples = this.samples;
  72064. this._sampleSphere = this._generateHemisphere();
  72065. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  72066. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72067. "base", "range", "projection", "near", "far", "texelSize",
  72068. "xViewport", "yViewport", "maxZ", "minZAspect"
  72069. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72070. this._ssaoPostProcess.onApply = function (effect) {
  72071. if (_this._firstUpdate) {
  72072. effect.setArray3("sampleSphere", _this._sampleSphere);
  72073. effect.setFloat("randTextureTiles", 4.0);
  72074. }
  72075. if (!_this._scene.activeCamera) {
  72076. return;
  72077. }
  72078. effect.setFloat("samplesFactor", 1 / _this.samples);
  72079. effect.setFloat("totalStrength", _this.totalStrength);
  72080. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  72081. effect.setFloat("radius", _this.radius);
  72082. effect.setFloat("maxZ", _this.maxZ);
  72083. effect.setFloat("minZAspect", _this.minZAspect);
  72084. effect.setFloat("base", _this.base);
  72085. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72086. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72087. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  72088. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  72089. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  72090. effect.setTexture("textureSampler", _this._depthTexture);
  72091. effect.setTexture("normalSampler", _this._normalTexture);
  72092. effect.setTexture("randomSampler", _this._randomTexture);
  72093. };
  72094. };
  72095. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72096. var _this = this;
  72097. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72098. this._ssaoCombinePostProcess.onApply = function (effect) {
  72099. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72100. };
  72101. };
  72102. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  72103. var size = 512;
  72104. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72105. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72106. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72107. var context = this._randomTexture.getContext();
  72108. var rand = function (min, max) {
  72109. return Math.random() * (max - min) + min;
  72110. };
  72111. var randVector = BABYLON.Vector3.Zero();
  72112. for (var x = 0; x < size; x++) {
  72113. for (var y = 0; y < size; y++) {
  72114. randVector.x = rand(0.0, 1.0);
  72115. randVector.y = rand(0.0, 1.0);
  72116. randVector.z = 0.0;
  72117. randVector.normalize();
  72118. randVector.scaleInPlace(255);
  72119. randVector.x = Math.floor(randVector.x);
  72120. randVector.y = Math.floor(randVector.y);
  72121. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  72122. context.fillRect(x, y, 1, 1);
  72123. }
  72124. }
  72125. this._randomTexture.update(false);
  72126. };
  72127. __decorate([
  72128. BABYLON.serialize()
  72129. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  72130. __decorate([
  72131. BABYLON.serialize()
  72132. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  72133. __decorate([
  72134. BABYLON.serialize()
  72135. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  72136. __decorate([
  72137. BABYLON.serialize("samples")
  72138. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  72139. __decorate([
  72140. BABYLON.serialize("expensiveBlur")
  72141. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  72142. __decorate([
  72143. BABYLON.serialize()
  72144. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  72145. __decorate([
  72146. BABYLON.serialize()
  72147. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  72148. return SSAO2RenderingPipeline;
  72149. }(BABYLON.PostProcessRenderPipeline));
  72150. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  72151. })(BABYLON || (BABYLON = {}));
  72152. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  72153. "use strict";
  72154. // BABYLON.JS Chromatic Aberration GLSL Shader
  72155. // Author: Olivier Guyot
  72156. // Separates very slightly R, G and B colors on the edges of the screen
  72157. // Inspired by Francois Tarlier & Martins Upitis
  72158. var BABYLON;
  72159. (function (BABYLON) {
  72160. var LensRenderingPipeline = /** @class */ (function (_super) {
  72161. __extends(LensRenderingPipeline, _super);
  72162. /**
  72163. * @constructor
  72164. *
  72165. * Effect parameters are as follow:
  72166. * {
  72167. * chromatic_aberration: number; // from 0 to x (1 for realism)
  72168. * edge_blur: number; // from 0 to x (1 for realism)
  72169. * distortion: number; // from 0 to x (1 for realism)
  72170. * grain_amount: number; // from 0 to 1
  72171. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  72172. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  72173. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  72174. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  72175. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  72176. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  72177. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  72178. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  72179. * }
  72180. * Note: if an effect parameter is unset, effect is disabled
  72181. *
  72182. * @param {string} name - The rendering pipeline name
  72183. * @param {object} parameters - An object containing all parameters (see above)
  72184. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72185. * @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)
  72186. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72187. */
  72188. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  72189. if (ratio === void 0) { ratio = 1.0; }
  72190. var _this = _super.call(this, scene.getEngine(), name) || this;
  72191. // Lens effects can be of the following:
  72192. // - chromatic aberration (slight shift of RGB colors)
  72193. // - blur on the edge of the lens
  72194. // - lens distortion
  72195. // - depth-of-field blur & highlights enhancing
  72196. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  72197. // - grain effect (noise or custom texture)
  72198. // Two additional texture samplers are needed:
  72199. // - depth map (for depth-of-field)
  72200. // - grain texture
  72201. /**
  72202. * The chromatic aberration PostProcess id in the pipeline
  72203. */
  72204. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  72205. /**
  72206. * The highlights enhancing PostProcess id in the pipeline
  72207. */
  72208. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  72209. /**
  72210. * The depth-of-field PostProcess id in the pipeline
  72211. */
  72212. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  72213. _this._scene = scene;
  72214. // Fetch texture samplers
  72215. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72216. if (parameters.grain_texture) {
  72217. _this._grainTexture = parameters.grain_texture;
  72218. }
  72219. else {
  72220. _this._createGrainTexture();
  72221. }
  72222. // save parameters
  72223. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  72224. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  72225. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  72226. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  72227. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  72228. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  72229. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  72230. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  72231. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  72232. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  72233. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  72234. // Create effects
  72235. _this._createChromaticAberrationPostProcess(ratio);
  72236. _this._createHighlightsPostProcess(ratio);
  72237. _this._createDepthOfFieldPostProcess(ratio / 4);
  72238. // Set up pipeline
  72239. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  72240. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  72241. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  72242. if (_this._highlightsGain === -1) {
  72243. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  72244. }
  72245. // Finish
  72246. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72247. if (cameras) {
  72248. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72249. }
  72250. return _this;
  72251. }
  72252. // public methods (self explanatory)
  72253. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  72254. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  72255. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  72256. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  72257. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  72258. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  72259. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  72260. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  72261. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  72262. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  72263. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  72264. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  72265. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  72266. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  72267. };
  72268. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  72269. this._highlightsPostProcess.updateEffect();
  72270. };
  72271. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  72272. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  72273. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  72274. this._highlightsGain = amount;
  72275. };
  72276. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  72277. if (this._highlightsGain === -1) {
  72278. this._highlightsGain = 1.0;
  72279. }
  72280. this._highlightsThreshold = amount;
  72281. };
  72282. LensRenderingPipeline.prototype.disableHighlights = function () {
  72283. this._highlightsGain = -1;
  72284. };
  72285. /**
  72286. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  72287. */
  72288. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72289. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72290. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72291. this._chromaticAberrationPostProcess = null;
  72292. this._highlightsPostProcess = null;
  72293. this._depthOfFieldPostProcess = null;
  72294. this._grainTexture.dispose();
  72295. if (disableDepthRender)
  72296. this._scene.disableDepthRenderer();
  72297. };
  72298. // colors shifting and distortion
  72299. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  72300. var _this = this;
  72301. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  72302. [], // samplers
  72303. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72304. this._chromaticAberrationPostProcess.onApply = function (effect) {
  72305. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  72306. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  72307. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  72308. effect.setFloat('radialIntensity', 1);
  72309. effect.setFloat2('direction', 17, 17);
  72310. effect.setFloat2('centerPosition', 0.5, 0.5);
  72311. };
  72312. };
  72313. // highlights enhancing
  72314. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  72315. var _this = this;
  72316. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  72317. [], // samplers
  72318. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  72319. this._highlightsPostProcess.onApply = function (effect) {
  72320. effect.setFloat('gain', _this._highlightsGain);
  72321. effect.setFloat('threshold', _this._highlightsThreshold);
  72322. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  72323. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  72324. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  72325. };
  72326. };
  72327. // colors shifting and distortion
  72328. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  72329. var _this = this;
  72330. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  72331. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  72332. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  72333. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72334. this._depthOfFieldPostProcess.onApply = function (effect) {
  72335. effect.setTexture("depthSampler", _this._depthTexture);
  72336. effect.setTexture("grainSampler", _this._grainTexture);
  72337. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  72338. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  72339. effect.setFloat('grain_amount', _this._grainAmount);
  72340. effect.setBool('blur_noise', _this._blurNoise);
  72341. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  72342. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  72343. effect.setFloat('distortion', _this._distortion);
  72344. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  72345. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  72346. effect.setFloat('aperture', _this._dofAperture);
  72347. effect.setFloat('darken', _this._dofDarken);
  72348. effect.setFloat('edge_blur', _this._edgeBlur);
  72349. effect.setBool('highlights', (_this._highlightsGain !== -1));
  72350. if (_this._scene.activeCamera) {
  72351. effect.setFloat('near', _this._scene.activeCamera.minZ);
  72352. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  72353. }
  72354. };
  72355. };
  72356. // creates a black and white random noise texture, 512x512
  72357. LensRenderingPipeline.prototype._createGrainTexture = function () {
  72358. var size = 512;
  72359. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72360. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72361. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72362. var context = this._grainTexture.getContext();
  72363. var rand = function (min, max) {
  72364. return Math.random() * (max - min) + min;
  72365. };
  72366. var value;
  72367. for (var x = 0; x < size; x++) {
  72368. for (var y = 0; y < size; y++) {
  72369. value = Math.floor(rand(0.42, 0.58) * 255);
  72370. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  72371. context.fillRect(x, y, 1, 1);
  72372. }
  72373. }
  72374. this._grainTexture.update(false);
  72375. };
  72376. return LensRenderingPipeline;
  72377. }(BABYLON.PostProcessRenderPipeline));
  72378. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  72379. })(BABYLON || (BABYLON = {}));
  72380. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  72381. "use strict";
  72382. var BABYLON;
  72383. (function (BABYLON) {
  72384. var StandardRenderingPipeline = /** @class */ (function (_super) {
  72385. __extends(StandardRenderingPipeline, _super);
  72386. /**
  72387. * @constructor
  72388. * @param {string} name - The rendering pipeline name
  72389. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72390. * @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)
  72391. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  72392. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72393. */
  72394. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  72395. if (originalPostProcess === void 0) { originalPostProcess = null; }
  72396. var _this = _super.call(this, scene.getEngine(), name) || this;
  72397. _this.downSampleX4PostProcess = null;
  72398. _this.brightPassPostProcess = null;
  72399. _this.blurHPostProcesses = [];
  72400. _this.blurVPostProcesses = [];
  72401. _this.textureAdderPostProcess = null;
  72402. _this.volumetricLightPostProcess = null;
  72403. _this.volumetricLightSmoothXPostProcess = null;
  72404. _this.volumetricLightSmoothYPostProcess = null;
  72405. _this.volumetricLightMergePostProces = null;
  72406. _this.volumetricLightFinalPostProcess = null;
  72407. _this.luminancePostProcess = null;
  72408. _this.luminanceDownSamplePostProcesses = [];
  72409. _this.hdrPostProcess = null;
  72410. _this.textureAdderFinalPostProcess = null;
  72411. _this.lensFlareFinalPostProcess = null;
  72412. _this.hdrFinalPostProcess = null;
  72413. _this.lensFlarePostProcess = null;
  72414. _this.lensFlareComposePostProcess = null;
  72415. _this.motionBlurPostProcess = null;
  72416. _this.depthOfFieldPostProcess = null;
  72417. // Values
  72418. _this.brightThreshold = 1.0;
  72419. _this.blurWidth = 512.0;
  72420. _this.horizontalBlur = false;
  72421. _this.exposure = 1.0;
  72422. _this.lensTexture = null;
  72423. _this.volumetricLightCoefficient = 0.2;
  72424. _this.volumetricLightPower = 4.0;
  72425. _this.volumetricLightBlurScale = 64.0;
  72426. _this.sourceLight = null;
  72427. _this.hdrMinimumLuminance = 1.0;
  72428. _this.hdrDecreaseRate = 0.5;
  72429. _this.hdrIncreaseRate = 0.5;
  72430. _this.lensColorTexture = null;
  72431. _this.lensFlareStrength = 20.0;
  72432. _this.lensFlareGhostDispersal = 1.4;
  72433. _this.lensFlareHaloWidth = 0.7;
  72434. _this.lensFlareDistortionStrength = 16.0;
  72435. _this.lensStarTexture = null;
  72436. _this.lensFlareDirtTexture = null;
  72437. _this.depthOfFieldDistance = 10.0;
  72438. _this.depthOfFieldBlurWidth = 64.0;
  72439. _this.motionStrength = 1.0;
  72440. // IAnimatable
  72441. _this.animations = [];
  72442. _this._currentDepthOfFieldSource = null;
  72443. _this._hdrCurrentLuminance = 1.0;
  72444. // Getters and setters
  72445. _this._bloomEnabled = true;
  72446. _this._depthOfFieldEnabled = false;
  72447. _this._vlsEnabled = false;
  72448. _this._lensFlareEnabled = false;
  72449. _this._hdrEnabled = false;
  72450. _this._motionBlurEnabled = false;
  72451. _this._motionBlurSamples = 64.0;
  72452. _this._volumetricLightStepsCount = 50.0;
  72453. _this._cameras = cameras || [];
  72454. // Initialize
  72455. _this._scene = scene;
  72456. _this._basePostProcess = originalPostProcess;
  72457. _this._ratio = ratio;
  72458. // Misc
  72459. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72460. // Finish
  72461. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72462. _this._buildPipeline();
  72463. return _this;
  72464. }
  72465. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  72466. get: function () {
  72467. return this._bloomEnabled;
  72468. },
  72469. set: function (enabled) {
  72470. if (this._bloomEnabled === enabled) {
  72471. return;
  72472. }
  72473. this._bloomEnabled = enabled;
  72474. this._buildPipeline();
  72475. },
  72476. enumerable: true,
  72477. configurable: true
  72478. });
  72479. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  72480. get: function () {
  72481. return this._depthOfFieldEnabled;
  72482. },
  72483. set: function (enabled) {
  72484. if (this._depthOfFieldEnabled === enabled) {
  72485. return;
  72486. }
  72487. this._depthOfFieldEnabled = enabled;
  72488. this._buildPipeline();
  72489. },
  72490. enumerable: true,
  72491. configurable: true
  72492. });
  72493. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  72494. get: function () {
  72495. return this._lensFlareEnabled;
  72496. },
  72497. set: function (enabled) {
  72498. if (this._lensFlareEnabled === enabled) {
  72499. return;
  72500. }
  72501. this._lensFlareEnabled = enabled;
  72502. this._buildPipeline();
  72503. },
  72504. enumerable: true,
  72505. configurable: true
  72506. });
  72507. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  72508. get: function () {
  72509. return this._hdrEnabled;
  72510. },
  72511. set: function (enabled) {
  72512. if (this._hdrEnabled === enabled) {
  72513. return;
  72514. }
  72515. this._hdrEnabled = enabled;
  72516. this._buildPipeline();
  72517. },
  72518. enumerable: true,
  72519. configurable: true
  72520. });
  72521. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  72522. get: function () {
  72523. return this._vlsEnabled;
  72524. },
  72525. set: function (enabled) {
  72526. if (this._vlsEnabled === enabled) {
  72527. return;
  72528. }
  72529. if (enabled) {
  72530. var geometry = this._scene.enableGeometryBufferRenderer();
  72531. if (!geometry) {
  72532. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  72533. return;
  72534. }
  72535. }
  72536. this._vlsEnabled = enabled;
  72537. this._buildPipeline();
  72538. },
  72539. enumerable: true,
  72540. configurable: true
  72541. });
  72542. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  72543. get: function () {
  72544. return this._motionBlurEnabled;
  72545. },
  72546. set: function (enabled) {
  72547. if (this._motionBlurEnabled === enabled) {
  72548. return;
  72549. }
  72550. this._motionBlurEnabled = enabled;
  72551. this._buildPipeline();
  72552. },
  72553. enumerable: true,
  72554. configurable: true
  72555. });
  72556. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  72557. get: function () {
  72558. return this._volumetricLightStepsCount;
  72559. },
  72560. set: function (count) {
  72561. if (this.volumetricLightPostProcess) {
  72562. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  72563. }
  72564. this._volumetricLightStepsCount = count;
  72565. },
  72566. enumerable: true,
  72567. configurable: true
  72568. });
  72569. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  72570. get: function () {
  72571. return this._motionBlurSamples;
  72572. },
  72573. set: function (samples) {
  72574. if (this.motionBlurPostProcess) {
  72575. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  72576. }
  72577. this._motionBlurSamples = samples;
  72578. },
  72579. enumerable: true,
  72580. configurable: true
  72581. });
  72582. StandardRenderingPipeline.prototype._buildPipeline = function () {
  72583. var _this = this;
  72584. var ratio = this._ratio;
  72585. var scene = this._scene;
  72586. this._disposePostProcesses();
  72587. this._reset();
  72588. // Create pass post-process
  72589. if (!this._basePostProcess) {
  72590. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  72591. this.originalPostProcess.onApply = function (effect) {
  72592. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  72593. };
  72594. }
  72595. else {
  72596. this.originalPostProcess = this._basePostProcess;
  72597. }
  72598. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  72599. this._currentDepthOfFieldSource = this.originalPostProcess;
  72600. if (this._vlsEnabled) {
  72601. // Create volumetric light
  72602. this._createVolumetricLightPostProcess(scene, ratio);
  72603. // Create volumetric light final post-process
  72604. 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);
  72605. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  72606. }
  72607. if (this._bloomEnabled) {
  72608. // Create down sample X4 post-process
  72609. this._createDownSampleX4PostProcess(scene, ratio / 2);
  72610. // Create bright pass post-process
  72611. this._createBrightPassPostProcess(scene, ratio / 2);
  72612. // Create gaussian blur post-processes (down sampling blurs)
  72613. this._createBlurPostProcesses(scene, ratio / 4, 1);
  72614. // Create texture adder post-process
  72615. this._createTextureAdderPostProcess(scene, ratio);
  72616. // Create depth-of-field source post-process
  72617. 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);
  72618. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  72619. }
  72620. if (this._lensFlareEnabled) {
  72621. // Create lens flare post-process
  72622. this._createLensFlarePostProcess(scene, ratio);
  72623. // Create depth-of-field source post-process post lens-flare and disable it now
  72624. 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);
  72625. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  72626. }
  72627. if (this._hdrEnabled) {
  72628. // Create luminance
  72629. this._createLuminancePostProcesses(scene, this._floatTextureType);
  72630. // Create HDR
  72631. this._createHdrPostProcess(scene, ratio);
  72632. // Create depth-of-field source post-process post hdr and disable it now
  72633. 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);
  72634. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  72635. }
  72636. if (this._depthOfFieldEnabled) {
  72637. // Create gaussian blur used by depth-of-field
  72638. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  72639. // Create depth-of-field post-process
  72640. this._createDepthOfFieldPostProcess(scene, ratio);
  72641. }
  72642. if (this._motionBlurEnabled) {
  72643. // Create motion blur post-process
  72644. this._createMotionBlurPostProcess(scene, ratio);
  72645. }
  72646. if (this._cameras !== null) {
  72647. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  72648. }
  72649. };
  72650. // Down Sample X4 Post-Processs
  72651. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  72652. var _this = this;
  72653. var downSampleX4Offsets = new Array(32);
  72654. 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);
  72655. this.downSampleX4PostProcess.onApply = function (effect) {
  72656. var id = 0;
  72657. var width = _this.downSampleX4PostProcess.width;
  72658. var height = _this.downSampleX4PostProcess.height;
  72659. for (var i = -2; i < 2; i++) {
  72660. for (var j = -2; j < 2; j++) {
  72661. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  72662. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  72663. id += 2;
  72664. }
  72665. }
  72666. effect.setArray2("dsOffsets", downSampleX4Offsets);
  72667. };
  72668. // Add to pipeline
  72669. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  72670. };
  72671. // Brightpass Post-Process
  72672. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  72673. var _this = this;
  72674. var brightOffsets = new Array(8);
  72675. 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);
  72676. this.brightPassPostProcess.onApply = function (effect) {
  72677. var sU = (1.0 / _this.brightPassPostProcess.width);
  72678. var sV = (1.0 / _this.brightPassPostProcess.height);
  72679. brightOffsets[0] = -0.5 * sU;
  72680. brightOffsets[1] = 0.5 * sV;
  72681. brightOffsets[2] = 0.5 * sU;
  72682. brightOffsets[3] = 0.5 * sV;
  72683. brightOffsets[4] = -0.5 * sU;
  72684. brightOffsets[5] = -0.5 * sV;
  72685. brightOffsets[6] = 0.5 * sU;
  72686. brightOffsets[7] = -0.5 * sV;
  72687. effect.setArray2("dsOffsets", brightOffsets);
  72688. effect.setFloat("brightThreshold", _this.brightThreshold);
  72689. };
  72690. // Add to pipeline
  72691. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  72692. };
  72693. // Create blur H&V post-processes
  72694. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  72695. var _this = this;
  72696. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  72697. var engine = scene.getEngine();
  72698. 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);
  72699. 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);
  72700. blurX.onActivateObservable.add(function () {
  72701. var dw = blurX.width / engine.getRenderWidth();
  72702. blurX.kernel = _this[blurWidthKey] * dw;
  72703. });
  72704. blurY.onActivateObservable.add(function () {
  72705. var dw = blurY.height / engine.getRenderHeight();
  72706. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  72707. });
  72708. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  72709. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  72710. this.blurHPostProcesses.push(blurX);
  72711. this.blurVPostProcesses.push(blurY);
  72712. };
  72713. // Create texture adder post-process
  72714. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  72715. var _this = this;
  72716. 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);
  72717. this.textureAdderPostProcess.onApply = function (effect) {
  72718. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  72719. effect.setTexture("lensSampler", _this.lensTexture);
  72720. effect.setFloat("exposure", _this.exposure);
  72721. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  72722. };
  72723. // Add to pipeline
  72724. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  72725. };
  72726. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  72727. var _this = this;
  72728. var geometryRenderer = scene.enableGeometryBufferRenderer();
  72729. geometryRenderer.enablePosition = true;
  72730. var geometry = geometryRenderer.getGBuffer();
  72731. // Base post-process
  72732. 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));
  72733. var depthValues = BABYLON.Vector2.Zero();
  72734. this.volumetricLightPostProcess.onApply = function (effect) {
  72735. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  72736. var generator = _this.sourceLight.getShadowGenerator();
  72737. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  72738. effect.setTexture("positionSampler", geometry.textures[2]);
  72739. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  72740. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  72741. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  72742. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  72743. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  72744. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  72745. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  72746. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  72747. effect.setVector2("depthValues", depthValues);
  72748. }
  72749. };
  72750. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  72751. // Smooth
  72752. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  72753. // Merge
  72754. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  72755. this.volumetricLightMergePostProces.onApply = function (effect) {
  72756. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  72757. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  72758. };
  72759. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  72760. };
  72761. // Create luminance
  72762. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  72763. var _this = this;
  72764. // Create luminance
  72765. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  72766. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  72767. var offsets = [];
  72768. this.luminancePostProcess.onApply = function (effect) {
  72769. var sU = (1.0 / _this.luminancePostProcess.width);
  72770. var sV = (1.0 / _this.luminancePostProcess.height);
  72771. offsets[0] = -0.5 * sU;
  72772. offsets[1] = 0.5 * sV;
  72773. offsets[2] = 0.5 * sU;
  72774. offsets[3] = 0.5 * sV;
  72775. offsets[4] = -0.5 * sU;
  72776. offsets[5] = -0.5 * sV;
  72777. offsets[6] = 0.5 * sU;
  72778. offsets[7] = -0.5 * sV;
  72779. effect.setArray2("lumOffsets", offsets);
  72780. };
  72781. // Add to pipeline
  72782. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  72783. // Create down sample luminance
  72784. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  72785. var size = Math.pow(3, i);
  72786. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  72787. if (i === 0) {
  72788. defines += "#define FINAL_DOWN_SAMPLER";
  72789. }
  72790. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  72791. this.luminanceDownSamplePostProcesses.push(postProcess);
  72792. }
  72793. // Create callbacks and add effects
  72794. var lastLuminance = this.luminancePostProcess;
  72795. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  72796. var downSampleOffsets = new Array(18);
  72797. pp.onApply = function (effect) {
  72798. if (!lastLuminance) {
  72799. return;
  72800. }
  72801. var id = 0;
  72802. for (var x = -1; x < 2; x++) {
  72803. for (var y = -1; y < 2; y++) {
  72804. downSampleOffsets[id] = x / lastLuminance.width;
  72805. downSampleOffsets[id + 1] = y / lastLuminance.height;
  72806. id += 2;
  72807. }
  72808. }
  72809. effect.setArray2("dsOffsets", downSampleOffsets);
  72810. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  72811. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  72812. lastLuminance = _this.luminancePostProcess;
  72813. }
  72814. else {
  72815. lastLuminance = pp;
  72816. }
  72817. };
  72818. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  72819. pp.onAfterRender = function (effect) {
  72820. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  72821. 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);
  72822. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  72823. };
  72824. }
  72825. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  72826. });
  72827. };
  72828. // Create HDR post-process
  72829. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  72830. var _this = this;
  72831. 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);
  72832. var outputLiminance = 1;
  72833. var time = 0;
  72834. var lastTime = 0;
  72835. this.hdrPostProcess.onApply = function (effect) {
  72836. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  72837. time += scene.getEngine().getDeltaTime();
  72838. if (outputLiminance < 0) {
  72839. outputLiminance = _this._hdrCurrentLuminance;
  72840. }
  72841. else {
  72842. var dt = (lastTime - time) / 1000.0;
  72843. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  72844. outputLiminance += _this.hdrDecreaseRate * dt;
  72845. }
  72846. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  72847. outputLiminance -= _this.hdrIncreaseRate * dt;
  72848. }
  72849. else {
  72850. outputLiminance = _this._hdrCurrentLuminance;
  72851. }
  72852. }
  72853. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  72854. effect.setFloat("averageLuminance", outputLiminance);
  72855. lastTime = time;
  72856. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  72857. };
  72858. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  72859. };
  72860. // Create lens flare post-process
  72861. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  72862. var _this = this;
  72863. 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);
  72864. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  72865. this._createBlurPostProcesses(scene, ratio / 4, 2);
  72866. 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);
  72867. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  72868. var resolution = new BABYLON.Vector2(0, 0);
  72869. // Lens flare
  72870. this.lensFlarePostProcess.onApply = function (effect) {
  72871. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  72872. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  72873. effect.setFloat("strength", _this.lensFlareStrength);
  72874. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  72875. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  72876. // Shift
  72877. resolution.x = _this.lensFlarePostProcess.width;
  72878. resolution.y = _this.lensFlarePostProcess.height;
  72879. effect.setVector2("resolution", resolution);
  72880. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  72881. };
  72882. // Compose
  72883. 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);
  72884. 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);
  72885. this.lensFlareComposePostProcess.onApply = function (effect) {
  72886. if (!_this._scene.activeCamera) {
  72887. return;
  72888. }
  72889. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  72890. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  72891. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  72892. // Lens start rotation matrix
  72893. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  72894. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  72895. 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));
  72896. camRot *= 4.0;
  72897. 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);
  72898. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  72899. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  72900. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  72901. };
  72902. };
  72903. // Create depth-of-field post-process
  72904. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  72905. var _this = this;
  72906. 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);
  72907. this.depthOfFieldPostProcess.onApply = function (effect) {
  72908. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  72909. effect.setTexture("depthSampler", _this._getDepthTexture());
  72910. effect.setFloat("distance", _this.depthOfFieldDistance);
  72911. };
  72912. // Add to pipeline
  72913. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  72914. };
  72915. // Create motion blur post-process
  72916. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  72917. var _this = this;
  72918. 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);
  72919. var motionScale = 0;
  72920. var prevViewProjection = BABYLON.Matrix.Identity();
  72921. var invViewProjection = BABYLON.Matrix.Identity();
  72922. var viewProjection = BABYLON.Matrix.Identity();
  72923. var screenSize = BABYLON.Vector2.Zero();
  72924. this.motionBlurPostProcess.onApply = function (effect) {
  72925. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  72926. viewProjection.invertToRef(invViewProjection);
  72927. effect.setMatrix("inverseViewProjection", invViewProjection);
  72928. effect.setMatrix("prevViewProjection", prevViewProjection);
  72929. prevViewProjection = viewProjection;
  72930. screenSize.x = _this.motionBlurPostProcess.width;
  72931. screenSize.y = _this.motionBlurPostProcess.height;
  72932. effect.setVector2("screenSize", screenSize);
  72933. motionScale = scene.getEngine().getFps() / 60.0;
  72934. effect.setFloat("motionScale", motionScale);
  72935. effect.setFloat("motionStrength", _this.motionStrength);
  72936. effect.setTexture("depthSampler", _this._getDepthTexture());
  72937. };
  72938. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  72939. };
  72940. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  72941. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  72942. var renderer = this._scene.enableGeometryBufferRenderer();
  72943. return renderer.getGBuffer().textures[0];
  72944. }
  72945. return this._scene.enableDepthRenderer().getDepthMap();
  72946. };
  72947. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  72948. for (var i = 0; i < this._cameras.length; i++) {
  72949. var camera = this._cameras[i];
  72950. if (this.originalPostProcess) {
  72951. this.originalPostProcess.dispose(camera);
  72952. }
  72953. if (this.downSampleX4PostProcess) {
  72954. this.downSampleX4PostProcess.dispose(camera);
  72955. }
  72956. if (this.brightPassPostProcess) {
  72957. this.brightPassPostProcess.dispose(camera);
  72958. }
  72959. if (this.textureAdderPostProcess) {
  72960. this.textureAdderPostProcess.dispose(camera);
  72961. }
  72962. if (this.textureAdderFinalPostProcess) {
  72963. this.textureAdderFinalPostProcess.dispose(camera);
  72964. }
  72965. if (this.volumetricLightPostProcess) {
  72966. this.volumetricLightPostProcess.dispose(camera);
  72967. }
  72968. if (this.volumetricLightSmoothXPostProcess) {
  72969. this.volumetricLightSmoothXPostProcess.dispose(camera);
  72970. }
  72971. if (this.volumetricLightSmoothYPostProcess) {
  72972. this.volumetricLightSmoothYPostProcess.dispose(camera);
  72973. }
  72974. if (this.volumetricLightMergePostProces) {
  72975. this.volumetricLightMergePostProces.dispose(camera);
  72976. }
  72977. if (this.volumetricLightFinalPostProcess) {
  72978. this.volumetricLightFinalPostProcess.dispose(camera);
  72979. }
  72980. if (this.lensFlarePostProcess) {
  72981. this.lensFlarePostProcess.dispose(camera);
  72982. }
  72983. if (this.lensFlareComposePostProcess) {
  72984. this.lensFlareComposePostProcess.dispose(camera);
  72985. }
  72986. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  72987. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  72988. }
  72989. if (this.luminancePostProcess) {
  72990. this.luminancePostProcess.dispose(camera);
  72991. }
  72992. if (this.hdrPostProcess) {
  72993. this.hdrPostProcess.dispose(camera);
  72994. }
  72995. if (this.hdrFinalPostProcess) {
  72996. this.hdrFinalPostProcess.dispose(camera);
  72997. }
  72998. if (this.depthOfFieldPostProcess) {
  72999. this.depthOfFieldPostProcess.dispose(camera);
  73000. }
  73001. if (this.motionBlurPostProcess) {
  73002. this.motionBlurPostProcess.dispose(camera);
  73003. }
  73004. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  73005. this.blurHPostProcesses[j].dispose(camera);
  73006. }
  73007. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  73008. this.blurVPostProcesses[j].dispose(camera);
  73009. }
  73010. }
  73011. this.originalPostProcess = null;
  73012. this.downSampleX4PostProcess = null;
  73013. this.brightPassPostProcess = null;
  73014. this.textureAdderPostProcess = null;
  73015. this.textureAdderFinalPostProcess = null;
  73016. this.volumetricLightPostProcess = null;
  73017. this.volumetricLightSmoothXPostProcess = null;
  73018. this.volumetricLightSmoothYPostProcess = null;
  73019. this.volumetricLightMergePostProces = null;
  73020. this.volumetricLightFinalPostProcess = null;
  73021. this.lensFlarePostProcess = null;
  73022. this.lensFlareComposePostProcess = null;
  73023. this.luminancePostProcess = null;
  73024. this.hdrPostProcess = null;
  73025. this.hdrFinalPostProcess = null;
  73026. this.depthOfFieldPostProcess = null;
  73027. this.motionBlurPostProcess = null;
  73028. this.luminanceDownSamplePostProcesses = [];
  73029. this.blurHPostProcesses = [];
  73030. this.blurVPostProcesses = [];
  73031. };
  73032. // Dispose
  73033. StandardRenderingPipeline.prototype.dispose = function () {
  73034. this._disposePostProcesses();
  73035. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  73036. _super.prototype.dispose.call(this);
  73037. };
  73038. // Serialize rendering pipeline
  73039. StandardRenderingPipeline.prototype.serialize = function () {
  73040. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73041. serializationObject.customType = "StandardRenderingPipeline";
  73042. return serializationObject;
  73043. };
  73044. /**
  73045. * Static members
  73046. */
  73047. // Parse serialized pipeline
  73048. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  73049. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73050. };
  73051. // Luminance steps
  73052. StandardRenderingPipeline.LuminanceSteps = 6;
  73053. __decorate([
  73054. BABYLON.serialize()
  73055. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  73056. __decorate([
  73057. BABYLON.serialize()
  73058. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  73059. __decorate([
  73060. BABYLON.serialize()
  73061. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  73062. __decorate([
  73063. BABYLON.serialize()
  73064. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  73065. __decorate([
  73066. BABYLON.serializeAsTexture("lensTexture")
  73067. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  73068. __decorate([
  73069. BABYLON.serialize()
  73070. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  73071. __decorate([
  73072. BABYLON.serialize()
  73073. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  73074. __decorate([
  73075. BABYLON.serialize()
  73076. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  73077. __decorate([
  73078. BABYLON.serialize()
  73079. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  73080. __decorate([
  73081. BABYLON.serialize()
  73082. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  73083. __decorate([
  73084. BABYLON.serialize()
  73085. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  73086. __decorate([
  73087. BABYLON.serializeAsTexture("lensColorTexture")
  73088. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  73089. __decorate([
  73090. BABYLON.serialize()
  73091. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  73092. __decorate([
  73093. BABYLON.serialize()
  73094. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  73095. __decorate([
  73096. BABYLON.serialize()
  73097. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  73098. __decorate([
  73099. BABYLON.serialize()
  73100. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  73101. __decorate([
  73102. BABYLON.serializeAsTexture("lensStarTexture")
  73103. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  73104. __decorate([
  73105. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  73106. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  73107. __decorate([
  73108. BABYLON.serialize()
  73109. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  73110. __decorate([
  73111. BABYLON.serialize()
  73112. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  73113. __decorate([
  73114. BABYLON.serialize()
  73115. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  73116. __decorate([
  73117. BABYLON.serialize()
  73118. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  73119. __decorate([
  73120. BABYLON.serialize()
  73121. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  73122. __decorate([
  73123. BABYLON.serialize()
  73124. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  73125. __decorate([
  73126. BABYLON.serialize()
  73127. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  73128. __decorate([
  73129. BABYLON.serialize()
  73130. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  73131. __decorate([
  73132. BABYLON.serialize()
  73133. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  73134. __decorate([
  73135. BABYLON.serialize()
  73136. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  73137. __decorate([
  73138. BABYLON.serialize()
  73139. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  73140. __decorate([
  73141. BABYLON.serialize()
  73142. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  73143. return StandardRenderingPipeline;
  73144. }(BABYLON.PostProcessRenderPipeline));
  73145. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  73146. })(BABYLON || (BABYLON = {}));
  73147. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  73148. "use strict";
  73149. var BABYLON;
  73150. (function (BABYLON) {
  73151. var FxaaPostProcess = /** @class */ (function (_super) {
  73152. __extends(FxaaPostProcess, _super);
  73153. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  73154. if (camera === void 0) { camera = null; }
  73155. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73156. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  73157. _this.onApplyObservable.add(function (effect) {
  73158. var texelSize = _this.texelSize;
  73159. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  73160. });
  73161. return _this;
  73162. }
  73163. return FxaaPostProcess;
  73164. }(BABYLON.PostProcess));
  73165. BABYLON.FxaaPostProcess = FxaaPostProcess;
  73166. })(BABYLON || (BABYLON = {}));
  73167. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  73168. "use strict";
  73169. var BABYLON;
  73170. (function (BABYLON) {
  73171. /**
  73172. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  73173. */
  73174. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  73175. __extends(ChromaticAberrationPostProcess, _super);
  73176. /**
  73177. * Creates a new instance ChromaticAberrationPostProcess
  73178. * @param name The name of the effect.
  73179. * @param screenWidth The width of the screen to apply the effect on.
  73180. * @param screenHeight The height of the screen to apply the effect on.
  73181. * @param options The required width/height ratio to downsize to before computing the render pass.
  73182. * @param camera The camera to apply the render pass to.
  73183. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73184. * @param engine The engine which the post process will be applied. (default: current engine)
  73185. * @param reusable If the post process can be reused on the same frame. (default: false)
  73186. * @param textureType Type of textures used when performing the post process. (default: 0)
  73187. * @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)
  73188. */
  73189. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73190. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73191. if (blockCompilation === void 0) { blockCompilation = false; }
  73192. 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;
  73193. /**
  73194. * The amount of seperation of rgb channels (default: 30)
  73195. */
  73196. _this.aberrationAmount = 30;
  73197. /**
  73198. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  73199. */
  73200. _this.radialIntensity = 0;
  73201. /**
  73202. * 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))
  73203. */
  73204. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  73205. /**
  73206. * 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))
  73207. */
  73208. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  73209. _this.onApplyObservable.add(function (effect) {
  73210. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  73211. effect.setFloat('screen_width', screenWidth);
  73212. effect.setFloat('screen_height', screenHeight);
  73213. effect.setFloat('radialIntensity', _this.radialIntensity);
  73214. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  73215. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  73216. });
  73217. return _this;
  73218. }
  73219. return ChromaticAberrationPostProcess;
  73220. }(BABYLON.PostProcess));
  73221. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  73222. })(BABYLON || (BABYLON = {}));
  73223. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  73224. "use strict";
  73225. var BABYLON;
  73226. (function (BABYLON) {
  73227. /**
  73228. * The GrainPostProcess adds noise to the image at mid luminance levels
  73229. */
  73230. var GrainPostProcess = /** @class */ (function (_super) {
  73231. __extends(GrainPostProcess, _super);
  73232. /**
  73233. * Creates a new instance of @see GrainPostProcess
  73234. * @param name The name of the effect.
  73235. * @param options The required width/height ratio to downsize to before computing the render pass.
  73236. * @param camera The camera to apply the render pass to.
  73237. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73238. * @param engine The engine which the post process will be applied. (default: current engine)
  73239. * @param reusable If the post process can be reused on the same frame. (default: false)
  73240. * @param textureType Type of textures used when performing the post process. (default: 0)
  73241. * @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)
  73242. */
  73243. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73244. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73245. if (blockCompilation === void 0) { blockCompilation = false; }
  73246. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73247. /**
  73248. * The intensity of the grain added (default: 30)
  73249. */
  73250. _this.intensity = 30;
  73251. /**
  73252. * If the grain should be randomized on every frame
  73253. */
  73254. _this.animated = false;
  73255. _this.onApplyObservable.add(function (effect) {
  73256. effect.setFloat('intensity', _this.intensity);
  73257. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  73258. });
  73259. return _this;
  73260. }
  73261. return GrainPostProcess;
  73262. }(BABYLON.PostProcess));
  73263. BABYLON.GrainPostProcess = GrainPostProcess;
  73264. })(BABYLON || (BABYLON = {}));
  73265. //# sourceMappingURL=babylon.grainPostProcess.js.map
  73266. "use strict";
  73267. var BABYLON;
  73268. (function (BABYLON) {
  73269. /**
  73270. * The SharpenPostProcess applies a sharpen kernel to every pixel
  73271. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  73272. */
  73273. var SharpenPostProcess = /** @class */ (function (_super) {
  73274. __extends(SharpenPostProcess, _super);
  73275. /**
  73276. * Creates a new instance ConvolutionPostProcess
  73277. * @param name The name of the effect.
  73278. * @param options The required width/height ratio to downsize to before computing the render pass.
  73279. * @param camera The camera to apply the render pass to.
  73280. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73281. * @param engine The engine which the post process will be applied. (default: current engine)
  73282. * @param reusable If the post process can be reused on the same frame. (default: false)
  73283. * @param textureType Type of textures used when performing the post process. (default: 0)
  73284. * @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)
  73285. */
  73286. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73287. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73288. if (blockCompilation === void 0) { blockCompilation = false; }
  73289. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73290. /**
  73291. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  73292. */
  73293. _this.colorAmount = 1.0;
  73294. /**
  73295. * How much sharpness should be applied (default: 0.3)
  73296. */
  73297. _this.edgeAmount = 0.3;
  73298. _this.onApply = function (effect) {
  73299. effect.setFloat2("screenSize", _this.width, _this.height);
  73300. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  73301. };
  73302. return _this;
  73303. }
  73304. return SharpenPostProcess;
  73305. }(BABYLON.PostProcess));
  73306. BABYLON.SharpenPostProcess = SharpenPostProcess;
  73307. })(BABYLON || (BABYLON = {}));
  73308. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  73309. "use strict";
  73310. var BABYLON;
  73311. (function (BABYLON) {
  73312. /**
  73313. * The Blur Post Process which blurs an image based on a kernel and direction.
  73314. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  73315. */
  73316. var BlurPostProcess = /** @class */ (function (_super) {
  73317. __extends(BlurPostProcess, _super);
  73318. /**
  73319. * Creates a new instance BlurPostProcess
  73320. * @param name The name of the effect.
  73321. * @param direction The direction in which to blur the image.
  73322. * @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.
  73323. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  73324. * @param camera The camera to apply the render pass to.
  73325. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73326. * @param engine The engine which the post process will be applied. (default: current engine)
  73327. * @param reusable If the post process can be reused on the same frame. (default: false)
  73328. * @param textureType Type of textures used when performing the post process. (default: 0)
  73329. * @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)
  73330. */
  73331. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  73332. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  73333. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73334. if (defines === void 0) { defines = ""; }
  73335. if (blockCompilation === void 0) { blockCompilation = false; }
  73336. 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;
  73337. _this.direction = direction;
  73338. _this.blockCompilation = blockCompilation;
  73339. _this._packedFloat = false;
  73340. _this._staticDefines = "";
  73341. _this._staticDefines = defines;
  73342. _this.onApplyObservable.add(function (effect) {
  73343. if (_this._outputTexture) {
  73344. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  73345. }
  73346. else {
  73347. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  73348. }
  73349. });
  73350. _this.kernel = kernel;
  73351. return _this;
  73352. }
  73353. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  73354. /**
  73355. * Gets the length in pixels of the blur sample region
  73356. */
  73357. get: function () {
  73358. return this._idealKernel;
  73359. },
  73360. /**
  73361. * Sets the length in pixels of the blur sample region
  73362. */
  73363. set: function (v) {
  73364. if (this._idealKernel === v) {
  73365. return;
  73366. }
  73367. v = Math.max(v, 1);
  73368. this._idealKernel = v;
  73369. this._kernel = this._nearestBestKernel(v);
  73370. if (!this.blockCompilation) {
  73371. this._updateParameters();
  73372. }
  73373. },
  73374. enumerable: true,
  73375. configurable: true
  73376. });
  73377. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  73378. /**
  73379. * Gets wether or not the blur is unpacking/repacking floats
  73380. */
  73381. get: function () {
  73382. return this._packedFloat;
  73383. },
  73384. /**
  73385. * Sets wether or not the blur needs to unpack/repack floats
  73386. */
  73387. set: function (v) {
  73388. if (this._packedFloat === v) {
  73389. return;
  73390. }
  73391. this._packedFloat = v;
  73392. if (!this.blockCompilation) {
  73393. this._updateParameters();
  73394. }
  73395. },
  73396. enumerable: true,
  73397. configurable: true
  73398. });
  73399. /**
  73400. * Updates the effect with the current post process compile time values and recompiles the shader.
  73401. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  73402. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  73403. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  73404. * @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
  73405. * @param onCompiled Called when the shader has been compiled.
  73406. * @param onError Called if there is an error when compiling a shader.
  73407. */
  73408. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  73409. if (defines === void 0) { defines = null; }
  73410. if (uniforms === void 0) { uniforms = null; }
  73411. if (samplers === void 0) { samplers = null; }
  73412. this._updateParameters(onCompiled, onError);
  73413. };
  73414. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  73415. // Generate sampling offsets and weights
  73416. var N = this._kernel;
  73417. var centerIndex = (N - 1) / 2;
  73418. // Generate Gaussian sampling weights over kernel
  73419. var offsets = [];
  73420. var weights = [];
  73421. var totalWeight = 0;
  73422. for (var i = 0; i < N; i++) {
  73423. var u = i / (N - 1);
  73424. var w = this._gaussianWeight(u * 2.0 - 1);
  73425. offsets[i] = (i - centerIndex);
  73426. weights[i] = w;
  73427. totalWeight += w;
  73428. }
  73429. // Normalize weights
  73430. for (var i = 0; i < weights.length; i++) {
  73431. weights[i] /= totalWeight;
  73432. }
  73433. // Optimize: combine samples to take advantage of hardware linear sampling
  73434. // Walk from left to center, combining pairs (symmetrically)
  73435. var linearSamplingWeights = [];
  73436. var linearSamplingOffsets = [];
  73437. var linearSamplingMap = [];
  73438. for (var i = 0; i <= centerIndex; i += 2) {
  73439. var j = Math.min(i + 1, Math.floor(centerIndex));
  73440. var singleCenterSample = i === j;
  73441. if (singleCenterSample) {
  73442. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  73443. }
  73444. else {
  73445. var sharedCell = j === centerIndex;
  73446. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  73447. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  73448. if (offsetLinear === 0) {
  73449. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  73450. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  73451. }
  73452. else {
  73453. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  73454. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  73455. }
  73456. }
  73457. }
  73458. for (var i = 0; i < linearSamplingMap.length; i++) {
  73459. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  73460. linearSamplingWeights[i] = linearSamplingMap[i].w;
  73461. }
  73462. // Replace with optimized
  73463. offsets = linearSamplingOffsets;
  73464. weights = linearSamplingWeights;
  73465. // Generate shaders
  73466. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  73467. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  73468. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  73469. var defines = "";
  73470. defines += this._staticDefines;
  73471. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  73472. if (this._staticDefines.indexOf("DOF") != -1) {
  73473. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  73474. varyingCount--;
  73475. }
  73476. for (var i = 0; i < varyingCount; i++) {
  73477. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  73478. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  73479. }
  73480. var depCount = 0;
  73481. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  73482. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  73483. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  73484. depCount++;
  73485. }
  73486. if (this.packedFloat) {
  73487. defines += "#define PACKEDFLOAT 1";
  73488. }
  73489. this.blockCompilation = false;
  73490. _super.prototype.updateEffect.call(this, defines, null, null, {
  73491. varyingCount: varyingCount,
  73492. depCount: depCount
  73493. }, onCompiled, onError);
  73494. };
  73495. /**
  73496. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  73497. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  73498. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  73499. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  73500. * The gaps between physical kernels are compensated for in the weighting of the samples
  73501. * @param idealKernel Ideal blur kernel.
  73502. * @return Nearest best kernel.
  73503. */
  73504. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  73505. var v = Math.round(idealKernel);
  73506. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  73507. var k = _a[_i];
  73508. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  73509. return Math.max(k, 3);
  73510. }
  73511. }
  73512. return Math.max(v, 3);
  73513. };
  73514. /**
  73515. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  73516. * @param x The point on the Gaussian distribution to sample.
  73517. * @return the value of the Gaussian function at x.
  73518. */
  73519. BlurPostProcess.prototype._gaussianWeight = function (x) {
  73520. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  73521. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  73522. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  73523. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  73524. // truncated at around 1.3% of peak strength.
  73525. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  73526. var sigma = (1 / 3);
  73527. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  73528. var exponent = -((x * x) / (2.0 * sigma * sigma));
  73529. var weight = (1.0 / denominator) * Math.exp(exponent);
  73530. return weight;
  73531. };
  73532. /**
  73533. * Generates a string that can be used as a floating point number in GLSL.
  73534. * @param x Value to print.
  73535. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  73536. * @return GLSL float string.
  73537. */
  73538. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  73539. if (decimalFigures === void 0) { decimalFigures = 8; }
  73540. return x.toFixed(decimalFigures).replace(/0+$/, '');
  73541. };
  73542. return BlurPostProcess;
  73543. }(BABYLON.PostProcess));
  73544. BABYLON.BlurPostProcess = BlurPostProcess;
  73545. })(BABYLON || (BABYLON = {}));
  73546. //# sourceMappingURL=babylon.blurPostProcess.js.map
  73547. "use strict";
  73548. var BABYLON;
  73549. (function (BABYLON) {
  73550. /**
  73551. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  73552. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  73553. * based on samples that have a large difference in distance than the center pixel.
  73554. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  73555. */
  73556. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  73557. __extends(DepthOfFieldBlurPostProcess, _super);
  73558. /**
  73559. * Creates a new instance CircleOfConfusionPostProcess
  73560. * @param name The name of the effect.
  73561. * @param scene The scene the effect belongs to.
  73562. * @param direction The direction the blur should be applied.
  73563. * @param kernel The size of the kernel used to blur.
  73564. * @param options The required width/height ratio to downsize to before computing the render pass.
  73565. * @param camera The camera to apply the render pass to.
  73566. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  73567. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  73568. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73569. * @param engine The engine which the post process will be applied. (default: current engine)
  73570. * @param reusable If the post process can be reused on the same frame. (default: false)
  73571. * @param textureType Type of textures used when performing the post process. (default: 0)
  73572. * @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)
  73573. */
  73574. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  73575. if (imageToBlur === void 0) { imageToBlur = null; }
  73576. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  73577. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73578. if (blockCompilation === void 0) { blockCompilation = false; }
  73579. 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;
  73580. _this.direction = direction;
  73581. _this.onApplyObservable.add(function (effect) {
  73582. if (imageToBlur != null) {
  73583. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  73584. }
  73585. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  73586. if (scene.activeCamera) {
  73587. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  73588. }
  73589. });
  73590. return _this;
  73591. }
  73592. return DepthOfFieldBlurPostProcess;
  73593. }(BABYLON.BlurPostProcess));
  73594. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  73595. })(BABYLON || (BABYLON = {}));
  73596. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  73597. "use strict";
  73598. var BABYLON;
  73599. (function (BABYLON) {
  73600. /**
  73601. * Options to be set when merging outputs from the default pipeline.
  73602. */
  73603. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  73604. function DepthOfFieldMergePostProcessOptions() {
  73605. }
  73606. return DepthOfFieldMergePostProcessOptions;
  73607. }());
  73608. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  73609. /**
  73610. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  73611. */
  73612. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  73613. __extends(DepthOfFieldMergePostProcess, _super);
  73614. /**
  73615. * Creates a new instance of DepthOfFieldMergePostProcess
  73616. * @param name The name of the effect.
  73617. * @param originalFromInput Post process which's input will be used for the merge.
  73618. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  73619. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  73620. * @param options The required width/height ratio to downsize to before computing the render pass.
  73621. * @param camera The camera to apply the render pass to.
  73622. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73623. * @param engine The engine which the post process will be applied. (default: current engine)
  73624. * @param reusable If the post process can be reused on the same frame. (default: false)
  73625. * @param textureType Type of textures used when performing the post process. (default: 0)
  73626. * @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)
  73627. */
  73628. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73629. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73630. if (blockCompilation === void 0) { blockCompilation = false; }
  73631. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  73632. _this.blurSteps = blurSteps;
  73633. _this.onApplyObservable.add(function (effect) {
  73634. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  73635. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  73636. blurSteps.forEach(function (step, index) {
  73637. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  73638. });
  73639. });
  73640. if (!blockCompilation) {
  73641. _this.updateEffect();
  73642. }
  73643. return _this;
  73644. }
  73645. /**
  73646. * Updates the effect with the current post process compile time values and recompiles the shader.
  73647. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  73648. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  73649. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  73650. * @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
  73651. * @param onCompiled Called when the shader has been compiled.
  73652. * @param onError Called if there is an error when compiling a shader.
  73653. */
  73654. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  73655. if (defines === void 0) { defines = null; }
  73656. if (uniforms === void 0) { uniforms = null; }
  73657. if (samplers === void 0) { samplers = null; }
  73658. if (!defines) {
  73659. defines = "";
  73660. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  73661. }
  73662. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  73663. };
  73664. return DepthOfFieldMergePostProcess;
  73665. }(BABYLON.PostProcess));
  73666. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  73667. })(BABYLON || (BABYLON = {}));
  73668. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  73669. "use strict";
  73670. var BABYLON;
  73671. (function (BABYLON) {
  73672. /**
  73673. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  73674. */
  73675. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  73676. __extends(CircleOfConfusionPostProcess, _super);
  73677. /**
  73678. * Creates a new instance CircleOfConfusionPostProcess
  73679. * @param name The name of the effect.
  73680. * @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.
  73681. * @param options The required width/height ratio to downsize to before computing the render pass.
  73682. * @param camera The camera to apply the render pass to.
  73683. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73684. * @param engine The engine which the post process will be applied. (default: current engine)
  73685. * @param reusable If the post process can be reused on the same frame. (default: false)
  73686. * @param textureType Type of textures used when performing the post process. (default: 0)
  73687. * @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)
  73688. */
  73689. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73690. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73691. if (blockCompilation === void 0) { blockCompilation = false; }
  73692. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73693. /**
  73694. * 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.
  73695. */
  73696. _this.lensSize = 50;
  73697. /**
  73698. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  73699. */
  73700. _this.fStop = 1.4;
  73701. /**
  73702. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  73703. */
  73704. _this.focusDistance = 2000;
  73705. /**
  73706. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  73707. */
  73708. _this.focalLength = 50;
  73709. _this._depthTexture = null;
  73710. _this._depthTexture = depthTexture;
  73711. _this.onApplyObservable.add(function (effect) {
  73712. if (!_this._depthTexture) {
  73713. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  73714. return;
  73715. }
  73716. effect.setTexture("depthSampler", _this._depthTexture);
  73717. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  73718. var aperture = _this.lensSize / _this.fStop;
  73719. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  73720. effect.setFloat('focusDistance', _this.focusDistance);
  73721. effect.setFloat('cocPrecalculation', cocPrecalculation);
  73722. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  73723. });
  73724. return _this;
  73725. }
  73726. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  73727. /**
  73728. * 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.
  73729. */
  73730. set: function (value) {
  73731. this._depthTexture = value;
  73732. },
  73733. enumerable: true,
  73734. configurable: true
  73735. });
  73736. return CircleOfConfusionPostProcess;
  73737. }(BABYLON.PostProcess));
  73738. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  73739. })(BABYLON || (BABYLON = {}));
  73740. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  73741. "use strict";
  73742. var BABYLON;
  73743. (function (BABYLON) {
  73744. /**
  73745. * Specifies the level of max blur that should be applied when using the depth of field effect
  73746. */
  73747. var DepthOfFieldEffectBlurLevel;
  73748. (function (DepthOfFieldEffectBlurLevel) {
  73749. /**
  73750. * Subtle blur
  73751. */
  73752. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  73753. /**
  73754. * Medium blur
  73755. */
  73756. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  73757. /**
  73758. * Large blur
  73759. */
  73760. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  73761. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  73762. ;
  73763. /**
  73764. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  73765. */
  73766. var DepthOfFieldEffect = /** @class */ (function (_super) {
  73767. __extends(DepthOfFieldEffect, _super);
  73768. /**
  73769. * Creates a new instance DepthOfFieldEffect
  73770. * @param scene The scene the effect belongs to.
  73771. * @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.
  73772. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  73773. * @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)
  73774. */
  73775. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  73776. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  73777. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  73778. if (blockCompilation === void 0) { blockCompilation = false; }
  73779. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  73780. return _this._effects;
  73781. }, true) || this;
  73782. /**
  73783. * Internal post processes in depth of field effect
  73784. */
  73785. _this._effects = [];
  73786. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  73787. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73788. // 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)
  73789. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  73790. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  73791. _this._depthOfFieldBlurY = [];
  73792. _this._depthOfFieldBlurX = [];
  73793. var blurCount = 1;
  73794. var kernelSize = 15;
  73795. switch (blurLevel) {
  73796. case DepthOfFieldEffectBlurLevel.High: {
  73797. blurCount = 3;
  73798. kernelSize = 51;
  73799. break;
  73800. }
  73801. case DepthOfFieldEffectBlurLevel.Medium: {
  73802. blurCount = 2;
  73803. kernelSize = 31;
  73804. break;
  73805. }
  73806. default: {
  73807. kernelSize = 15;
  73808. blurCount = 1;
  73809. break;
  73810. }
  73811. }
  73812. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  73813. var ratio = 1.0;
  73814. for (var i = 0; i < blurCount; i++) {
  73815. 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);
  73816. blurY.autoClear = false;
  73817. ratio = 0.75 / Math.pow(2, i);
  73818. 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);
  73819. blurX.autoClear = false;
  73820. _this._depthOfFieldBlurY.push(blurY);
  73821. _this._depthOfFieldBlurX.push(blurX);
  73822. }
  73823. // Set all post processes on the effect.
  73824. _this._effects = [_this._circleOfConfusion];
  73825. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  73826. _this._effects.push(_this._depthOfFieldBlurY[i]);
  73827. _this._effects.push(_this._depthOfFieldBlurX[i]);
  73828. }
  73829. // Merge blurred images with original image based on circleOfConfusion
  73830. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73831. _this._dofMerge.autoClear = false;
  73832. _this._effects.push(_this._dofMerge);
  73833. return _this;
  73834. }
  73835. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  73836. get: function () {
  73837. return this._circleOfConfusion.focalLength;
  73838. },
  73839. /**
  73840. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  73841. */
  73842. set: function (value) {
  73843. this._circleOfConfusion.focalLength = value;
  73844. },
  73845. enumerable: true,
  73846. configurable: true
  73847. });
  73848. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  73849. get: function () {
  73850. return this._circleOfConfusion.fStop;
  73851. },
  73852. /**
  73853. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  73854. */
  73855. set: function (value) {
  73856. this._circleOfConfusion.fStop = value;
  73857. },
  73858. enumerable: true,
  73859. configurable: true
  73860. });
  73861. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  73862. get: function () {
  73863. return this._circleOfConfusion.focusDistance;
  73864. },
  73865. /**
  73866. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  73867. */
  73868. set: function (value) {
  73869. this._circleOfConfusion.focusDistance = value;
  73870. },
  73871. enumerable: true,
  73872. configurable: true
  73873. });
  73874. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  73875. get: function () {
  73876. return this._circleOfConfusion.lensSize;
  73877. },
  73878. /**
  73879. * 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.
  73880. */
  73881. set: function (value) {
  73882. this._circleOfConfusion.lensSize = value;
  73883. },
  73884. enumerable: true,
  73885. configurable: true
  73886. });
  73887. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  73888. /**
  73889. * 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.
  73890. */
  73891. set: function (value) {
  73892. this._circleOfConfusion.depthTexture = value;
  73893. },
  73894. enumerable: true,
  73895. configurable: true
  73896. });
  73897. /**
  73898. * Disposes each of the internal effects for a given camera.
  73899. * @param camera The camera to dispose the effect on.
  73900. */
  73901. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  73902. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  73903. this._effects[effectIndex].dispose(camera);
  73904. }
  73905. };
  73906. /**
  73907. * Internal
  73908. */
  73909. DepthOfFieldEffect.prototype._updateEffects = function () {
  73910. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  73911. this._effects[effectIndex].updateEffect();
  73912. }
  73913. };
  73914. /**
  73915. * Internal
  73916. * @returns if all the contained post processes are ready.
  73917. */
  73918. DepthOfFieldEffect.prototype._isReady = function () {
  73919. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  73920. if (!this._effects[effectIndex].isReady()) {
  73921. return false;
  73922. }
  73923. }
  73924. return true;
  73925. };
  73926. return DepthOfFieldEffect;
  73927. }(BABYLON.PostProcessRenderEffect));
  73928. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  73929. })(BABYLON || (BABYLON = {}));
  73930. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  73931. "use strict";
  73932. var BABYLON;
  73933. (function (BABYLON) {
  73934. /**
  73935. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  73936. */
  73937. var BloomMergePostProcess = /** @class */ (function (_super) {
  73938. __extends(BloomMergePostProcess, _super);
  73939. /**
  73940. * Creates a new instance of @see BloomMergePostProcess
  73941. * @param name The name of the effect.
  73942. * @param originalFromInput Post process which's input will be used for the merge.
  73943. * @param blurred Blurred highlights post process which's output will be used.
  73944. * @param weight Weight of the bloom to be added to the original input.
  73945. * @param options The required width/height ratio to downsize to before computing the render pass.
  73946. * @param camera The camera to apply the render pass to.
  73947. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73948. * @param engine The engine which the post process will be applied. (default: current engine)
  73949. * @param reusable If the post process can be reused on the same frame. (default: false)
  73950. * @param textureType Type of textures used when performing the post process. (default: 0)
  73951. * @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)
  73952. */
  73953. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73954. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73955. if (blockCompilation === void 0) { blockCompilation = false; }
  73956. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  73957. _this.weight = weight;
  73958. _this.onApplyObservable.add(function (effect) {
  73959. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  73960. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  73961. effect.setFloat("bloomWeight", _this.weight);
  73962. });
  73963. if (!blockCompilation) {
  73964. _this.updateEffect();
  73965. }
  73966. return _this;
  73967. }
  73968. return BloomMergePostProcess;
  73969. }(BABYLON.PostProcess));
  73970. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  73971. })(BABYLON || (BABYLON = {}));
  73972. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  73973. "use strict";
  73974. var BABYLON;
  73975. (function (BABYLON) {
  73976. /**
  73977. * 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.
  73978. */
  73979. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  73980. __extends(ExtractHighlightsPostProcess, _super);
  73981. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73982. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73983. if (blockCompilation === void 0) { blockCompilation = false; }
  73984. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73985. /**
  73986. * The luminance threshold, pixels below this value will be set to black.
  73987. */
  73988. _this.threshold = 0.9;
  73989. /**
  73990. * Internal
  73991. */
  73992. _this._exposure = 1;
  73993. /**
  73994. * Post process which has the input texture to be used when performing highlight extraction
  73995. */
  73996. _this._inputPostProcess = null;
  73997. _this.onApplyObservable.add(function (effect) {
  73998. if (_this._inputPostProcess) {
  73999. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  74000. }
  74001. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  74002. effect.setFloat('exposure', _this._exposure);
  74003. });
  74004. return _this;
  74005. }
  74006. return ExtractHighlightsPostProcess;
  74007. }(BABYLON.PostProcess));
  74008. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  74009. })(BABYLON || (BABYLON = {}));
  74010. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  74011. "use strict";
  74012. var BABYLON;
  74013. (function (BABYLON) {
  74014. /**
  74015. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  74016. */
  74017. var BloomEffect = /** @class */ (function (_super) {
  74018. __extends(BloomEffect, _super);
  74019. /**
  74020. * Creates a new instance of @see BloomEffect
  74021. * @param scene The scene the effect belongs to.
  74022. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  74023. * @param bloomKernel The size of the kernel to be used when applying the blur.
  74024. * @param bloomWeight The the strength of bloom.
  74025. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74026. * @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)
  74027. */
  74028. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  74029. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74030. if (blockCompilation === void 0) { blockCompilation = false; }
  74031. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  74032. return _this._effects;
  74033. }, true) || this;
  74034. _this.bloomScale = bloomScale;
  74035. /**
  74036. * Internal
  74037. */
  74038. _this._effects = [];
  74039. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74040. _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);
  74041. _this._blurX.alwaysForcePOT = true;
  74042. _this._blurX.autoClear = false;
  74043. _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);
  74044. _this._blurY.alwaysForcePOT = true;
  74045. _this._blurY.autoClear = false;
  74046. _this.kernel = bloomKernel;
  74047. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  74048. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74049. _this._merge.autoClear = false;
  74050. _this._effects.push(_this._merge);
  74051. return _this;
  74052. }
  74053. Object.defineProperty(BloomEffect.prototype, "threshold", {
  74054. /**
  74055. * The luminance threshold to find bright areas of the image to bloom.
  74056. */
  74057. get: function () {
  74058. return this._downscale.threshold;
  74059. },
  74060. set: function (value) {
  74061. this._downscale.threshold = value;
  74062. },
  74063. enumerable: true,
  74064. configurable: true
  74065. });
  74066. Object.defineProperty(BloomEffect.prototype, "weight", {
  74067. /**
  74068. * The strength of the bloom.
  74069. */
  74070. get: function () {
  74071. return this._merge.weight;
  74072. },
  74073. set: function (value) {
  74074. this._merge.weight = value;
  74075. },
  74076. enumerable: true,
  74077. configurable: true
  74078. });
  74079. Object.defineProperty(BloomEffect.prototype, "kernel", {
  74080. /**
  74081. * Specifies the size of the bloom blur kernel, relative to the final output size
  74082. */
  74083. get: function () {
  74084. return this._blurX.kernel / this.bloomScale;
  74085. },
  74086. set: function (value) {
  74087. this._blurX.kernel = value * this.bloomScale;
  74088. this._blurY.kernel = value * this.bloomScale;
  74089. },
  74090. enumerable: true,
  74091. configurable: true
  74092. });
  74093. /**
  74094. * Disposes each of the internal effects for a given camera.
  74095. * @param camera The camera to dispose the effect on.
  74096. */
  74097. BloomEffect.prototype.disposeEffects = function (camera) {
  74098. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74099. this._effects[effectIndex].dispose(camera);
  74100. }
  74101. };
  74102. /**
  74103. * Internal
  74104. */
  74105. BloomEffect.prototype._updateEffects = function () {
  74106. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74107. this._effects[effectIndex].updateEffect();
  74108. }
  74109. };
  74110. /**
  74111. * Internal
  74112. * @returns if all the contained post processes are ready.
  74113. */
  74114. BloomEffect.prototype._isReady = function () {
  74115. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74116. if (!this._effects[effectIndex].isReady()) {
  74117. return false;
  74118. }
  74119. }
  74120. return true;
  74121. };
  74122. return BloomEffect;
  74123. }(BABYLON.PostProcessRenderEffect));
  74124. BABYLON.BloomEffect = BloomEffect;
  74125. })(BABYLON || (BABYLON = {}));
  74126. //# sourceMappingURL=babylon.bloomEffect.js.map
  74127. "use strict";
  74128. var BABYLON;
  74129. (function (BABYLON) {
  74130. /**
  74131. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  74132. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  74133. */
  74134. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  74135. __extends(DefaultRenderingPipeline, _super);
  74136. /**
  74137. * @constructor
  74138. * @param {string} name - The rendering pipeline name
  74139. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74140. * @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)
  74141. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74142. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  74143. */
  74144. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  74145. if (automaticBuild === void 0) { automaticBuild = true; }
  74146. var _this = _super.call(this, scene.getEngine(), name) || this;
  74147. _this._originalCameras = [];
  74148. /**
  74149. * ID of the sharpen post process,
  74150. */
  74151. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  74152. /**
  74153. * ID of the image processing post process;
  74154. */
  74155. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  74156. /**
  74157. * ID of the Fast Approximate Anti-Aliasing post process;
  74158. */
  74159. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  74160. /**
  74161. * ID of the chromatic aberration post process,
  74162. */
  74163. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  74164. /**
  74165. * ID of the grain post process
  74166. */
  74167. _this.GrainPostProcessId = "GrainPostProcessEffect";
  74168. /**
  74169. * Animations which can be used to tweak settings over a period of time
  74170. */
  74171. _this.animations = [];
  74172. _this._imageProcessingConfigurationObserver = null;
  74173. // Values
  74174. _this._sharpenEnabled = false;
  74175. _this._bloomEnabled = false;
  74176. _this._depthOfFieldEnabled = false;
  74177. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  74178. _this._fxaaEnabled = false;
  74179. _this._imageProcessingEnabled = true;
  74180. _this._bloomScale = 0.5;
  74181. _this._chromaticAberrationEnabled = false;
  74182. _this._grainEnabled = false;
  74183. _this._buildAllowed = true;
  74184. _this._resizeObserver = null;
  74185. _this._hardwareScaleLevel = 1.0;
  74186. _this._bloomKernel = 64;
  74187. /**
  74188. * Specifies the weight of the bloom in the final rendering
  74189. */
  74190. _this._bloomWeight = 0.15;
  74191. /**
  74192. * Specifies the luma threshold for the area that will be blurred by the bloom
  74193. */
  74194. _this._bloomThreshold = 0.9;
  74195. _this._samples = 1;
  74196. _this._hasCleared = false;
  74197. _this._prevPostProcess = null;
  74198. _this._prevPrevPostProcess = null;
  74199. _this._cameras = cameras || [];
  74200. _this._originalCameras = _this._cameras.slice();
  74201. _this._buildAllowed = automaticBuild;
  74202. // Initialize
  74203. _this._scene = scene;
  74204. var caps = _this._scene.getEngine().getCaps();
  74205. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  74206. // Misc
  74207. if (_this._hdr) {
  74208. if (caps.textureHalfFloatRender) {
  74209. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74210. }
  74211. else if (caps.textureFloatRender) {
  74212. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74213. }
  74214. }
  74215. else {
  74216. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74217. }
  74218. // Attach
  74219. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74220. var engine = _this._scene.getEngine();
  74221. // Create post processes before hand so they can be modified before enabled.
  74222. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  74223. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74224. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  74225. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  74226. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  74227. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74228. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  74229. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74230. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  74231. _this._resizeObserver = engine.onResizeObservable.add(function () {
  74232. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  74233. _this.bloomKernel = _this.bloomKernel;
  74234. });
  74235. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  74236. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  74237. });
  74238. _this._buildPipeline();
  74239. return _this;
  74240. }
  74241. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  74242. get: function () {
  74243. return this._sharpenEnabled;
  74244. },
  74245. /**
  74246. * Enable or disable the sharpen process from the pipeline
  74247. */
  74248. set: function (enabled) {
  74249. if (this._sharpenEnabled === enabled) {
  74250. return;
  74251. }
  74252. this._sharpenEnabled = enabled;
  74253. this._buildPipeline();
  74254. },
  74255. enumerable: true,
  74256. configurable: true
  74257. });
  74258. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  74259. /**
  74260. * Specifies the size of the bloom blur kernel, relative to the final output size
  74261. */
  74262. get: function () {
  74263. return this._bloomKernel;
  74264. },
  74265. set: function (value) {
  74266. this._bloomKernel = value;
  74267. this.bloom.kernel = value / this._hardwareScaleLevel;
  74268. },
  74269. enumerable: true,
  74270. configurable: true
  74271. });
  74272. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  74273. get: function () {
  74274. return this._bloomWeight;
  74275. },
  74276. /**
  74277. * The strength of the bloom.
  74278. */
  74279. set: function (value) {
  74280. if (this._bloomWeight === value) {
  74281. return;
  74282. }
  74283. this.bloom.weight = value;
  74284. this._bloomWeight = value;
  74285. },
  74286. enumerable: true,
  74287. configurable: true
  74288. });
  74289. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  74290. get: function () {
  74291. return this._bloomThreshold;
  74292. },
  74293. /**
  74294. * The strength of the bloom.
  74295. */
  74296. set: function (value) {
  74297. if (this._bloomThreshold === value) {
  74298. return;
  74299. }
  74300. this.bloom.threshold = value;
  74301. this._bloomThreshold = value;
  74302. },
  74303. enumerable: true,
  74304. configurable: true
  74305. });
  74306. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  74307. get: function () {
  74308. return this._bloomScale;
  74309. },
  74310. /**
  74311. * The scale of the bloom, lower value will provide better performance.
  74312. */
  74313. set: function (value) {
  74314. if (this._bloomScale === value) {
  74315. return;
  74316. }
  74317. this._bloomScale = value;
  74318. // recreate bloom and dispose old as this setting is not dynamic
  74319. this._rebuildBloom();
  74320. this._buildPipeline();
  74321. },
  74322. enumerable: true,
  74323. configurable: true
  74324. });
  74325. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  74326. get: function () {
  74327. return this._bloomEnabled;
  74328. },
  74329. /**
  74330. * Enable or disable the bloom from the pipeline
  74331. */
  74332. set: function (enabled) {
  74333. if (this._bloomEnabled === enabled) {
  74334. return;
  74335. }
  74336. this._bloomEnabled = enabled;
  74337. this._buildPipeline();
  74338. },
  74339. enumerable: true,
  74340. configurable: true
  74341. });
  74342. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  74343. // recreate bloom and dispose old as this setting is not dynamic
  74344. var oldBloom = this.bloom;
  74345. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  74346. this.bloom.threshold = oldBloom.threshold;
  74347. for (var i = 0; i < this._cameras.length; i++) {
  74348. oldBloom.disposeEffects(this._cameras[i]);
  74349. }
  74350. };
  74351. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  74352. /**
  74353. * If the depth of field is enabled.
  74354. */
  74355. get: function () {
  74356. return this._depthOfFieldEnabled;
  74357. },
  74358. set: function (enabled) {
  74359. if (this._depthOfFieldEnabled === enabled) {
  74360. return;
  74361. }
  74362. this._depthOfFieldEnabled = enabled;
  74363. this._buildPipeline();
  74364. },
  74365. enumerable: true,
  74366. configurable: true
  74367. });
  74368. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  74369. /**
  74370. * Blur level of the depth of field effect. (Higher blur will effect performance)
  74371. */
  74372. get: function () {
  74373. return this._depthOfFieldBlurLevel;
  74374. },
  74375. set: function (value) {
  74376. if (this._depthOfFieldBlurLevel === value) {
  74377. return;
  74378. }
  74379. this._depthOfFieldBlurLevel = value;
  74380. // recreate dof and dispose old as this setting is not dynamic
  74381. var oldDof = this.depthOfField;
  74382. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  74383. this.depthOfField.focalLength = oldDof.focalLength;
  74384. this.depthOfField.focusDistance = oldDof.focusDistance;
  74385. this.depthOfField.fStop = oldDof.fStop;
  74386. this.depthOfField.lensSize = oldDof.lensSize;
  74387. for (var i = 0; i < this._cameras.length; i++) {
  74388. oldDof.disposeEffects(this._cameras[i]);
  74389. }
  74390. this._buildPipeline();
  74391. },
  74392. enumerable: true,
  74393. configurable: true
  74394. });
  74395. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  74396. get: function () {
  74397. return this._fxaaEnabled;
  74398. },
  74399. /**
  74400. * If the anti aliasing is enabled.
  74401. */
  74402. set: function (enabled) {
  74403. if (this._fxaaEnabled === enabled) {
  74404. return;
  74405. }
  74406. this._fxaaEnabled = enabled;
  74407. this._buildPipeline();
  74408. },
  74409. enumerable: true,
  74410. configurable: true
  74411. });
  74412. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  74413. get: function () {
  74414. return this._samples;
  74415. },
  74416. /**
  74417. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  74418. */
  74419. set: function (sampleCount) {
  74420. if (this._samples === sampleCount) {
  74421. return;
  74422. }
  74423. this._samples = sampleCount;
  74424. this._buildPipeline();
  74425. },
  74426. enumerable: true,
  74427. configurable: true
  74428. });
  74429. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  74430. get: function () {
  74431. return this._imageProcessingEnabled;
  74432. },
  74433. /**
  74434. * If image processing is enabled.
  74435. */
  74436. set: function (enabled) {
  74437. if (this._imageProcessingEnabled === enabled) {
  74438. return;
  74439. }
  74440. this._imageProcessingEnabled = enabled;
  74441. this._buildPipeline();
  74442. },
  74443. enumerable: true,
  74444. configurable: true
  74445. });
  74446. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  74447. get: function () {
  74448. return this._chromaticAberrationEnabled;
  74449. },
  74450. /**
  74451. * Enable or disable the chromaticAberration process from the pipeline
  74452. */
  74453. set: function (enabled) {
  74454. if (this._chromaticAberrationEnabled === enabled) {
  74455. return;
  74456. }
  74457. this._chromaticAberrationEnabled = enabled;
  74458. this._buildPipeline();
  74459. },
  74460. enumerable: true,
  74461. configurable: true
  74462. });
  74463. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  74464. get: function () {
  74465. return this._grainEnabled;
  74466. },
  74467. /**
  74468. * Enable or disable the grain process from the pipeline
  74469. */
  74470. set: function (enabled) {
  74471. if (this._grainEnabled === enabled) {
  74472. return;
  74473. }
  74474. this._grainEnabled = enabled;
  74475. this._buildPipeline();
  74476. },
  74477. enumerable: true,
  74478. configurable: true
  74479. });
  74480. /**
  74481. * Force the compilation of the entire pipeline.
  74482. */
  74483. DefaultRenderingPipeline.prototype.prepare = function () {
  74484. var previousState = this._buildAllowed;
  74485. this._buildAllowed = true;
  74486. this._buildPipeline();
  74487. this._buildAllowed = previousState;
  74488. };
  74489. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  74490. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  74491. if (this._hasCleared) {
  74492. postProcess.autoClear = false;
  74493. }
  74494. else {
  74495. postProcess.autoClear = true;
  74496. this._scene.autoClear = false;
  74497. this._hasCleared = true;
  74498. }
  74499. if (!skipTextureSharing) {
  74500. if (this._prevPrevPostProcess) {
  74501. postProcess.shareOutputWith(this._prevPrevPostProcess);
  74502. }
  74503. else {
  74504. postProcess.useOwnOutput();
  74505. }
  74506. if (this._prevPostProcess) {
  74507. this._prevPrevPostProcess = this._prevPostProcess;
  74508. }
  74509. this._prevPostProcess = postProcess;
  74510. }
  74511. };
  74512. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  74513. var _this = this;
  74514. if (!this._buildAllowed) {
  74515. return;
  74516. }
  74517. this._scene.autoClear = true;
  74518. var engine = this._scene.getEngine();
  74519. this._disposePostProcesses();
  74520. if (this._cameras !== null) {
  74521. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74522. // get back cameras to be used to reattach pipeline
  74523. this._cameras = this._originalCameras.slice();
  74524. }
  74525. this._reset();
  74526. this._prevPostProcess = null;
  74527. this._prevPrevPostProcess = null;
  74528. this._hasCleared = false;
  74529. if (this.depthOfFieldEnabled) {
  74530. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  74531. this.depthOfField.depthTexture = depthTexture;
  74532. if (!this.depthOfField._isReady()) {
  74533. this.depthOfField._updateEffects();
  74534. }
  74535. this.addEffect(this.depthOfField);
  74536. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  74537. }
  74538. if (this.bloomEnabled) {
  74539. if (!this.bloom._isReady()) {
  74540. this.bloom._updateEffects();
  74541. }
  74542. this.addEffect(this.bloom);
  74543. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  74544. }
  74545. if (this._imageProcessingEnabled) {
  74546. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  74547. if (this._hdr) {
  74548. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  74549. this._setAutoClearAndTextureSharing(this.imageProcessing);
  74550. }
  74551. else {
  74552. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  74553. }
  74554. }
  74555. if (this.sharpenEnabled) {
  74556. if (!this.sharpen.isReady()) {
  74557. this.sharpen.updateEffect();
  74558. }
  74559. this.addEffect(this._sharpenEffect);
  74560. this._setAutoClearAndTextureSharing(this.sharpen);
  74561. }
  74562. if (this.grainEnabled) {
  74563. if (!this.grain.isReady()) {
  74564. this.grain.updateEffect();
  74565. }
  74566. this.addEffect(this._grainEffect);
  74567. this._setAutoClearAndTextureSharing(this.grain);
  74568. }
  74569. if (this.chromaticAberrationEnabled) {
  74570. if (!this.chromaticAberration.isReady()) {
  74571. this.chromaticAberration.updateEffect();
  74572. }
  74573. this.addEffect(this._chromaticAberrationEffect);
  74574. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  74575. }
  74576. if (this.fxaaEnabled) {
  74577. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  74578. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  74579. this._setAutoClearAndTextureSharing(this.fxaa, true);
  74580. }
  74581. if (this._cameras !== null) {
  74582. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74583. }
  74584. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  74585. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  74586. }
  74587. };
  74588. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  74589. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  74590. for (var i = 0; i < this._cameras.length; i++) {
  74591. var camera = this._cameras[i];
  74592. if (this.imageProcessing) {
  74593. this.imageProcessing.dispose(camera);
  74594. }
  74595. if (this.fxaa) {
  74596. this.fxaa.dispose(camera);
  74597. }
  74598. // These are created in the constructor and should not be disposed on every pipeline change
  74599. if (disposeNonRecreated) {
  74600. if (this.sharpen) {
  74601. this.sharpen.dispose(camera);
  74602. }
  74603. if (this.depthOfField) {
  74604. this.depthOfField.disposeEffects(camera);
  74605. }
  74606. if (this.bloom) {
  74607. this.bloom.disposeEffects(camera);
  74608. }
  74609. if (this.chromaticAberration) {
  74610. this.chromaticAberration.dispose(camera);
  74611. }
  74612. if (this.grain) {
  74613. this.grain.dispose(camera);
  74614. }
  74615. }
  74616. }
  74617. this.imageProcessing = null;
  74618. this.fxaa = null;
  74619. if (disposeNonRecreated) {
  74620. this.sharpen = null;
  74621. this._sharpenEffect = null;
  74622. this.depthOfField = null;
  74623. this.bloom = null;
  74624. this.chromaticAberration = null;
  74625. this._chromaticAberrationEffect = null;
  74626. this.grain = null;
  74627. this._grainEffect = null;
  74628. }
  74629. };
  74630. /**
  74631. * Dispose of the pipeline and stop all post processes
  74632. */
  74633. DefaultRenderingPipeline.prototype.dispose = function () {
  74634. this._disposePostProcesses(true);
  74635. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74636. this._scene.autoClear = true;
  74637. if (this._resizeObserver) {
  74638. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  74639. this._resizeObserver = null;
  74640. }
  74641. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  74642. _super.prototype.dispose.call(this);
  74643. };
  74644. /**
  74645. * Serialize the rendering pipeline (Used when exporting)
  74646. * @returns the serialized object
  74647. */
  74648. DefaultRenderingPipeline.prototype.serialize = function () {
  74649. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74650. serializationObject.customType = "DefaultRenderingPipeline";
  74651. return serializationObject;
  74652. };
  74653. /**
  74654. * Parse the serialized pipeline
  74655. * @param source Source pipeline.
  74656. * @param scene The scene to load the pipeline to.
  74657. * @param rootUrl The URL of the serialized pipeline.
  74658. * @returns An instantiated pipeline from the serialized object.
  74659. */
  74660. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74661. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  74662. };
  74663. __decorate([
  74664. BABYLON.serialize()
  74665. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  74666. __decorate([
  74667. BABYLON.serialize()
  74668. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  74669. __decorate([
  74670. BABYLON.serialize()
  74671. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  74672. __decorate([
  74673. BABYLON.serialize()
  74674. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  74675. __decorate([
  74676. BABYLON.serialize()
  74677. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  74678. __decorate([
  74679. BABYLON.serialize()
  74680. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  74681. __decorate([
  74682. BABYLON.serialize()
  74683. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  74684. __decorate([
  74685. BABYLON.serialize()
  74686. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  74687. __decorate([
  74688. BABYLON.serialize()
  74689. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  74690. __decorate([
  74691. BABYLON.serialize()
  74692. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  74693. __decorate([
  74694. BABYLON.serialize()
  74695. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  74696. __decorate([
  74697. BABYLON.serialize()
  74698. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  74699. __decorate([
  74700. BABYLON.serialize()
  74701. ], DefaultRenderingPipeline.prototype, "samples", null);
  74702. __decorate([
  74703. BABYLON.serialize()
  74704. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  74705. __decorate([
  74706. BABYLON.serialize()
  74707. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  74708. __decorate([
  74709. BABYLON.serialize()
  74710. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  74711. return DefaultRenderingPipeline;
  74712. }(BABYLON.PostProcessRenderPipeline));
  74713. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  74714. })(BABYLON || (BABYLON = {}));
  74715. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  74716. "use strict";
  74717. var BABYLON;
  74718. (function (BABYLON) {
  74719. /**
  74720. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  74721. */
  74722. var GeometryBufferRenderer = /** @class */ (function () {
  74723. /**
  74724. * Creates a new G Buffer for the scene
  74725. * @param scene The scene the buffer belongs to
  74726. * @param ratio How big is the buffer related to the main canvas.
  74727. */
  74728. function GeometryBufferRenderer(scene, ratio) {
  74729. if (ratio === void 0) { ratio = 1; }
  74730. this._enablePosition = false;
  74731. this._scene = scene;
  74732. this._ratio = ratio;
  74733. // Render target
  74734. this._createRenderTargets();
  74735. }
  74736. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  74737. /**
  74738. * Set the render list (meshes to be rendered) used in the G buffer.
  74739. */
  74740. set: function (meshes) {
  74741. this._multiRenderTarget.renderList = meshes;
  74742. },
  74743. enumerable: true,
  74744. configurable: true
  74745. });
  74746. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  74747. /**
  74748. * Gets wether or not G buffer are supported by the running hardware.
  74749. * This requires draw buffer supports
  74750. */
  74751. get: function () {
  74752. return this._multiRenderTarget.isSupported;
  74753. },
  74754. enumerable: true,
  74755. configurable: true
  74756. });
  74757. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  74758. /**
  74759. * Gets wether or not position are enabled for the G buffer.
  74760. */
  74761. get: function () {
  74762. return this._enablePosition;
  74763. },
  74764. /**
  74765. * Sets wether or not position are enabled for the G buffer.
  74766. */
  74767. set: function (enable) {
  74768. this._enablePosition = enable;
  74769. this.dispose();
  74770. this._createRenderTargets();
  74771. },
  74772. enumerable: true,
  74773. configurable: true
  74774. });
  74775. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  74776. /**
  74777. * Gets the scene associated with the buffer.
  74778. */
  74779. get: function () {
  74780. return this._scene;
  74781. },
  74782. enumerable: true,
  74783. configurable: true
  74784. });
  74785. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  74786. /**
  74787. * Gets the ratio used by the buffer during its creation.
  74788. * How big is the buffer related to the main canvas.
  74789. */
  74790. get: function () {
  74791. return this._ratio;
  74792. },
  74793. enumerable: true,
  74794. configurable: true
  74795. });
  74796. /**
  74797. * Checks wether everything is ready to render a submesh to the G buffer.
  74798. * @param subMesh the submesh to check readiness for
  74799. * @param useInstances is the mesh drawn using instance or not
  74800. * @returns true if ready otherwise false
  74801. */
  74802. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  74803. var material = subMesh.getMaterial();
  74804. if (material && material.disableDepthWrite) {
  74805. return false;
  74806. }
  74807. var defines = [];
  74808. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  74809. var mesh = subMesh.getMesh();
  74810. // Alpha test
  74811. if (material && material.needAlphaTesting()) {
  74812. defines.push("#define ALPHATEST");
  74813. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74814. attribs.push(BABYLON.VertexBuffer.UVKind);
  74815. defines.push("#define UV1");
  74816. }
  74817. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74818. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74819. defines.push("#define UV2");
  74820. }
  74821. }
  74822. // Buffers
  74823. if (this._enablePosition) {
  74824. defines.push("#define POSITION");
  74825. }
  74826. // Bones
  74827. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74828. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74829. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74830. if (mesh.numBoneInfluencers > 4) {
  74831. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74832. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74833. }
  74834. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74835. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  74836. }
  74837. else {
  74838. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74839. }
  74840. // Instances
  74841. if (useInstances) {
  74842. defines.push("#define INSTANCES");
  74843. attribs.push("world0");
  74844. attribs.push("world1");
  74845. attribs.push("world2");
  74846. attribs.push("world3");
  74847. }
  74848. // Get correct effect
  74849. var join = defines.join("\n");
  74850. if (this._cachedDefines !== join) {
  74851. this._cachedDefines = join;
  74852. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  74853. }
  74854. return this._effect.isReady();
  74855. };
  74856. /**
  74857. * Gets the current underlying G Buffer.
  74858. * @returns the buffer
  74859. */
  74860. GeometryBufferRenderer.prototype.getGBuffer = function () {
  74861. return this._multiRenderTarget;
  74862. };
  74863. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  74864. /**
  74865. * Gets the number of samples used to render the buffer (anti aliasing).
  74866. */
  74867. get: function () {
  74868. return this._multiRenderTarget.samples;
  74869. },
  74870. /**
  74871. * Sets the number of samples used to render the buffer (anti aliasing).
  74872. */
  74873. set: function (value) {
  74874. this._multiRenderTarget.samples = value;
  74875. },
  74876. enumerable: true,
  74877. configurable: true
  74878. });
  74879. /**
  74880. * Disposes the renderer and frees up associated resources.
  74881. */
  74882. GeometryBufferRenderer.prototype.dispose = function () {
  74883. this.getGBuffer().dispose();
  74884. };
  74885. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  74886. var _this = this;
  74887. var engine = this._scene.getEngine();
  74888. var count = this._enablePosition ? 3 : 2;
  74889. 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 });
  74890. if (!this.isSupported) {
  74891. return;
  74892. }
  74893. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74894. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74895. this._multiRenderTarget.refreshRate = 1;
  74896. this._multiRenderTarget.renderParticles = false;
  74897. this._multiRenderTarget.renderList = null;
  74898. // set default depth value to 1.0 (far away)
  74899. this._multiRenderTarget.onClearObservable.add(function (engine) {
  74900. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  74901. });
  74902. // Custom render function
  74903. var renderSubMesh = function (subMesh) {
  74904. var mesh = subMesh.getRenderingMesh();
  74905. var scene = _this._scene;
  74906. var engine = scene.getEngine();
  74907. var material = subMesh.getMaterial();
  74908. if (!material) {
  74909. return;
  74910. }
  74911. // Culling
  74912. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  74913. // Managing instances
  74914. var batch = mesh._getInstancesRenderList(subMesh._id);
  74915. if (batch.mustReturn) {
  74916. return;
  74917. }
  74918. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  74919. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  74920. engine.enableEffect(_this._effect);
  74921. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  74922. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  74923. _this._effect.setMatrix("view", scene.getViewMatrix());
  74924. // Alpha test
  74925. if (material && material.needAlphaTesting()) {
  74926. var alphaTexture = material.getAlphaTestTexture();
  74927. if (alphaTexture) {
  74928. _this._effect.setTexture("diffuseSampler", alphaTexture);
  74929. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74930. }
  74931. }
  74932. // Bones
  74933. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74934. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74935. }
  74936. // Draw
  74937. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  74938. }
  74939. };
  74940. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74941. var index;
  74942. if (depthOnlySubMeshes.length) {
  74943. engine.setColorWrite(false);
  74944. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74945. renderSubMesh(depthOnlySubMeshes.data[index]);
  74946. }
  74947. engine.setColorWrite(true);
  74948. }
  74949. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74950. renderSubMesh(opaqueSubMeshes.data[index]);
  74951. }
  74952. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74953. renderSubMesh(alphaTestSubMeshes.data[index]);
  74954. }
  74955. };
  74956. };
  74957. return GeometryBufferRenderer;
  74958. }());
  74959. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  74960. })(BABYLON || (BABYLON = {}));
  74961. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  74962. "use strict";
  74963. var BABYLON;
  74964. (function (BABYLON) {
  74965. var RefractionPostProcess = /** @class */ (function (_super) {
  74966. __extends(RefractionPostProcess, _super);
  74967. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  74968. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  74969. _this.color = color;
  74970. _this.depth = depth;
  74971. _this.colorLevel = colorLevel;
  74972. _this._ownRefractionTexture = true;
  74973. _this.onActivateObservable.add(function (cam) {
  74974. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  74975. });
  74976. _this.onApplyObservable.add(function (effect) {
  74977. effect.setColor3("baseColor", _this.color);
  74978. effect.setFloat("depth", _this.depth);
  74979. effect.setFloat("colorLevel", _this.colorLevel);
  74980. effect.setTexture("refractionSampler", _this._refTexture);
  74981. });
  74982. return _this;
  74983. }
  74984. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  74985. /**
  74986. * Gets or sets the refraction texture
  74987. * Please note that you are responsible for disposing the texture if you set it manually
  74988. */
  74989. get: function () {
  74990. return this._refTexture;
  74991. },
  74992. set: function (value) {
  74993. if (this._refTexture && this._ownRefractionTexture) {
  74994. this._refTexture.dispose();
  74995. }
  74996. this._refTexture = value;
  74997. this._ownRefractionTexture = false;
  74998. },
  74999. enumerable: true,
  75000. configurable: true
  75001. });
  75002. // Methods
  75003. RefractionPostProcess.prototype.dispose = function (camera) {
  75004. if (this._refTexture && this._ownRefractionTexture) {
  75005. this._refTexture.dispose();
  75006. this._refTexture = null;
  75007. }
  75008. _super.prototype.dispose.call(this, camera);
  75009. };
  75010. return RefractionPostProcess;
  75011. }(BABYLON.PostProcess));
  75012. BABYLON.RefractionPostProcess = RefractionPostProcess;
  75013. })(BABYLON || (BABYLON = {}));
  75014. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  75015. "use strict";
  75016. var BABYLON;
  75017. (function (BABYLON) {
  75018. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  75019. __extends(BlackAndWhitePostProcess, _super);
  75020. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  75021. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  75022. _this.degree = 1;
  75023. _this.onApplyObservable.add(function (effect) {
  75024. effect.setFloat("degree", _this.degree);
  75025. });
  75026. return _this;
  75027. }
  75028. return BlackAndWhitePostProcess;
  75029. }(BABYLON.PostProcess));
  75030. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  75031. })(BABYLON || (BABYLON = {}));
  75032. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  75033. "use strict";
  75034. var BABYLON;
  75035. (function (BABYLON) {
  75036. /**
  75037. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  75038. * input texture to perform effects such as edge detection or sharpening
  75039. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75040. */
  75041. var ConvolutionPostProcess = /** @class */ (function (_super) {
  75042. __extends(ConvolutionPostProcess, _super);
  75043. /**
  75044. * Creates a new instance ConvolutionPostProcess
  75045. * @param name The name of the effect.
  75046. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  75047. * @param options The required width/height ratio to downsize to before computing the render pass.
  75048. * @param camera The camera to apply the render pass to.
  75049. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75050. * @param engine The engine which the post process will be applied. (default: current engine)
  75051. * @param reusable If the post process can be reused on the same frame. (default: false)
  75052. * @param textureType Type of textures used when performing the post process. (default: 0)
  75053. */
  75054. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  75055. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75056. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  75057. _this.kernel = kernel;
  75058. _this.onApply = function (effect) {
  75059. effect.setFloat2("screenSize", _this.width, _this.height);
  75060. effect.setArray("kernel", _this.kernel);
  75061. };
  75062. return _this;
  75063. }
  75064. // Statics
  75065. /**
  75066. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75067. */
  75068. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  75069. /**
  75070. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75071. */
  75072. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  75073. /**
  75074. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75075. */
  75076. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  75077. /**
  75078. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75079. */
  75080. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  75081. /**
  75082. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75083. */
  75084. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  75085. /**
  75086. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75087. */
  75088. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  75089. return ConvolutionPostProcess;
  75090. }(BABYLON.PostProcess));
  75091. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  75092. })(BABYLON || (BABYLON = {}));
  75093. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  75094. "use strict";
  75095. var BABYLON;
  75096. (function (BABYLON) {
  75097. var FilterPostProcess = /** @class */ (function (_super) {
  75098. __extends(FilterPostProcess, _super);
  75099. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  75100. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  75101. _this.kernelMatrix = kernelMatrix;
  75102. _this.onApply = function (effect) {
  75103. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  75104. };
  75105. return _this;
  75106. }
  75107. return FilterPostProcess;
  75108. }(BABYLON.PostProcess));
  75109. BABYLON.FilterPostProcess = FilterPostProcess;
  75110. })(BABYLON || (BABYLON = {}));
  75111. //# sourceMappingURL=babylon.filterPostProcess.js.map
  75112. "use strict";
  75113. var BABYLON;
  75114. (function (BABYLON) {
  75115. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  75116. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  75117. __extends(VolumetricLightScatteringPostProcess, _super);
  75118. /**
  75119. * @constructor
  75120. * @param {string} name - The post-process name
  75121. * @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)
  75122. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  75123. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  75124. * @param {number} samples - The post-process quality, default 100
  75125. * @param {number} samplingMode - The post-process filtering mode
  75126. * @param {BABYLON.Engine} engine - The babylon engine
  75127. * @param {boolean} reusable - If the post-process is reusable
  75128. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  75129. */
  75130. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  75131. if (samples === void 0) { samples = 100; }
  75132. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75133. 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;
  75134. _this._screenCoordinates = BABYLON.Vector2.Zero();
  75135. /**
  75136. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  75137. */
  75138. _this.customMeshPosition = BABYLON.Vector3.Zero();
  75139. /**
  75140. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  75141. */
  75142. _this.useCustomMeshPosition = false;
  75143. /**
  75144. * If the post-process should inverse the light scattering direction
  75145. */
  75146. _this.invert = true;
  75147. /**
  75148. * Array containing the excluded meshes not rendered in the internal pass
  75149. */
  75150. _this.excludedMeshes = new Array();
  75151. /**
  75152. * Controls the overall intensity of the post-process
  75153. */
  75154. _this.exposure = 0.3;
  75155. /**
  75156. * Dissipates each sample's contribution in range [0, 1]
  75157. */
  75158. _this.decay = 0.96815;
  75159. /**
  75160. * Controls the overall intensity of each sample
  75161. */
  75162. _this.weight = 0.58767;
  75163. /**
  75164. * Controls the density of each sample
  75165. */
  75166. _this.density = 0.926;
  75167. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  75168. engine = scene.getEngine();
  75169. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  75170. // Configure mesh
  75171. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  75172. // Configure
  75173. _this._createPass(scene, ratio.passRatio || ratio);
  75174. _this.onActivate = function (camera) {
  75175. if (!_this.isSupported) {
  75176. _this.dispose(camera);
  75177. }
  75178. _this.onActivate = null;
  75179. };
  75180. _this.onApplyObservable.add(function (effect) {
  75181. _this._updateMeshScreenCoordinates(scene);
  75182. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  75183. effect.setFloat("exposure", _this.exposure);
  75184. effect.setFloat("decay", _this.decay);
  75185. effect.setFloat("weight", _this.weight);
  75186. effect.setFloat("density", _this.density);
  75187. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  75188. });
  75189. return _this;
  75190. }
  75191. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  75192. get: function () {
  75193. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  75194. return false;
  75195. },
  75196. set: function (useDiffuseColor) {
  75197. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  75198. },
  75199. enumerable: true,
  75200. configurable: true
  75201. });
  75202. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  75203. return "VolumetricLightScatteringPostProcess";
  75204. };
  75205. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  75206. var mesh = subMesh.getMesh();
  75207. // Render this.mesh as default
  75208. if (mesh === this.mesh && mesh.material) {
  75209. return mesh.material.isReady(mesh);
  75210. }
  75211. var defines = [];
  75212. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75213. var material = subMesh.getMaterial();
  75214. // Alpha test
  75215. if (material) {
  75216. if (material.needAlphaTesting()) {
  75217. defines.push("#define ALPHATEST");
  75218. }
  75219. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75220. attribs.push(BABYLON.VertexBuffer.UVKind);
  75221. defines.push("#define UV1");
  75222. }
  75223. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75224. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75225. defines.push("#define UV2");
  75226. }
  75227. }
  75228. // Bones
  75229. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75230. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75231. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75232. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75233. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  75234. }
  75235. else {
  75236. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75237. }
  75238. // Instances
  75239. if (useInstances) {
  75240. defines.push("#define INSTANCES");
  75241. attribs.push("world0");
  75242. attribs.push("world1");
  75243. attribs.push("world2");
  75244. attribs.push("world3");
  75245. }
  75246. // Get correct effect
  75247. var join = defines.join("\n");
  75248. if (this._cachedDefines !== join) {
  75249. this._cachedDefines = join;
  75250. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  75251. }
  75252. return this._volumetricLightScatteringPass.isReady();
  75253. };
  75254. /**
  75255. * Sets the new light position for light scattering effect
  75256. * @param {BABYLON.Vector3} The new custom light position
  75257. */
  75258. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  75259. this.customMeshPosition = position;
  75260. };
  75261. /**
  75262. * Returns the light position for light scattering effect
  75263. * @return {BABYLON.Vector3} The custom light position
  75264. */
  75265. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  75266. return this.customMeshPosition;
  75267. };
  75268. /**
  75269. * Disposes the internal assets and detaches the post-process from the camera
  75270. */
  75271. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  75272. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  75273. if (rttIndex !== -1) {
  75274. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  75275. }
  75276. this._volumetricLightScatteringRTT.dispose();
  75277. _super.prototype.dispose.call(this, camera);
  75278. };
  75279. /**
  75280. * Returns the render target texture used by the post-process
  75281. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  75282. */
  75283. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  75284. return this._volumetricLightScatteringRTT;
  75285. };
  75286. // Private methods
  75287. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  75288. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  75289. return true;
  75290. }
  75291. return false;
  75292. };
  75293. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  75294. var _this = this;
  75295. var engine = scene.getEngine();
  75296. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75297. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75298. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75299. this._volumetricLightScatteringRTT.renderList = null;
  75300. this._volumetricLightScatteringRTT.renderParticles = false;
  75301. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  75302. var camera = this.getCamera();
  75303. if (camera) {
  75304. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  75305. }
  75306. else {
  75307. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  75308. }
  75309. // Custom render function for submeshes
  75310. var renderSubMesh = function (subMesh) {
  75311. var mesh = subMesh.getRenderingMesh();
  75312. if (_this._meshExcluded(mesh)) {
  75313. return;
  75314. }
  75315. var material = subMesh.getMaterial();
  75316. if (!material) {
  75317. return;
  75318. }
  75319. var scene = mesh.getScene();
  75320. var engine = scene.getEngine();
  75321. // Culling
  75322. engine.setState(material.backFaceCulling);
  75323. // Managing instances
  75324. var batch = mesh._getInstancesRenderList(subMesh._id);
  75325. if (batch.mustReturn) {
  75326. return;
  75327. }
  75328. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75329. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  75330. var effect = _this._volumetricLightScatteringPass;
  75331. if (mesh === _this.mesh) {
  75332. if (subMesh.effect) {
  75333. effect = subMesh.effect;
  75334. }
  75335. else {
  75336. effect = material.getEffect();
  75337. }
  75338. }
  75339. engine.enableEffect(effect);
  75340. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  75341. if (mesh === _this.mesh) {
  75342. material.bind(mesh.getWorldMatrix(), mesh);
  75343. }
  75344. else {
  75345. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  75346. // Alpha test
  75347. if (material && material.needAlphaTesting()) {
  75348. var alphaTexture = material.getAlphaTestTexture();
  75349. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  75350. if (alphaTexture) {
  75351. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75352. }
  75353. }
  75354. // Bones
  75355. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75356. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75357. }
  75358. }
  75359. // Draw
  75360. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  75361. }
  75362. };
  75363. // Render target texture callbacks
  75364. var savedSceneClearColor;
  75365. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  75366. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  75367. savedSceneClearColor = scene.clearColor;
  75368. scene.clearColor = sceneClearColor;
  75369. });
  75370. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  75371. scene.clearColor = savedSceneClearColor;
  75372. });
  75373. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75374. var engine = scene.getEngine();
  75375. var index;
  75376. if (depthOnlySubMeshes.length) {
  75377. engine.setColorWrite(false);
  75378. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75379. renderSubMesh(depthOnlySubMeshes.data[index]);
  75380. }
  75381. engine.setColorWrite(true);
  75382. }
  75383. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75384. renderSubMesh(opaqueSubMeshes.data[index]);
  75385. }
  75386. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75387. renderSubMesh(alphaTestSubMeshes.data[index]);
  75388. }
  75389. if (transparentSubMeshes.length) {
  75390. // Sort sub meshes
  75391. for (index = 0; index < transparentSubMeshes.length; index++) {
  75392. var submesh = transparentSubMeshes.data[index];
  75393. var boundingInfo = submesh.getBoundingInfo();
  75394. if (boundingInfo && scene.activeCamera) {
  75395. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  75396. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  75397. }
  75398. }
  75399. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  75400. sortedArray.sort(function (a, b) {
  75401. // Alpha index first
  75402. if (a._alphaIndex > b._alphaIndex) {
  75403. return 1;
  75404. }
  75405. if (a._alphaIndex < b._alphaIndex) {
  75406. return -1;
  75407. }
  75408. // Then distance to camera
  75409. if (a._distanceToCamera < b._distanceToCamera) {
  75410. return 1;
  75411. }
  75412. if (a._distanceToCamera > b._distanceToCamera) {
  75413. return -1;
  75414. }
  75415. return 0;
  75416. });
  75417. // Render sub meshes
  75418. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  75419. for (index = 0; index < sortedArray.length; index++) {
  75420. renderSubMesh(sortedArray[index]);
  75421. }
  75422. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75423. }
  75424. };
  75425. };
  75426. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  75427. var transform = scene.getTransformMatrix();
  75428. var meshPosition;
  75429. if (this.useCustomMeshPosition) {
  75430. meshPosition = this.customMeshPosition;
  75431. }
  75432. else if (this.attachedNode) {
  75433. meshPosition = this.attachedNode.position;
  75434. }
  75435. else {
  75436. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  75437. }
  75438. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  75439. this._screenCoordinates.x = pos.x / this._viewPort.width;
  75440. this._screenCoordinates.y = pos.y / this._viewPort.height;
  75441. if (this.invert)
  75442. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  75443. };
  75444. // Static methods
  75445. /**
  75446. * Creates a default mesh for the Volumeric Light Scattering post-process
  75447. * @param {string} The mesh name
  75448. * @param {BABYLON.Scene} The scene where to create the mesh
  75449. * @return {BABYLON.Mesh} the default mesh
  75450. */
  75451. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  75452. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  75453. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  75454. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  75455. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  75456. mesh.material = material;
  75457. return mesh;
  75458. };
  75459. __decorate([
  75460. BABYLON.serializeAsVector3()
  75461. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  75462. __decorate([
  75463. BABYLON.serialize()
  75464. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  75465. __decorate([
  75466. BABYLON.serialize()
  75467. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  75468. __decorate([
  75469. BABYLON.serializeAsMeshReference()
  75470. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  75471. __decorate([
  75472. BABYLON.serialize()
  75473. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  75474. __decorate([
  75475. BABYLON.serialize()
  75476. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  75477. __decorate([
  75478. BABYLON.serialize()
  75479. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  75480. __decorate([
  75481. BABYLON.serialize()
  75482. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  75483. __decorate([
  75484. BABYLON.serialize()
  75485. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  75486. return VolumetricLightScatteringPostProcess;
  75487. }(BABYLON.PostProcess));
  75488. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  75489. })(BABYLON || (BABYLON = {}));
  75490. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  75491. "use strict";
  75492. //
  75493. // This post-process allows the modification of rendered colors by using
  75494. // a 'look-up table' (LUT). This effect is also called Color Grading.
  75495. //
  75496. // The object needs to be provided an url to a texture containing the color
  75497. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  75498. // Use an image editing software to tweak the LUT to match your needs.
  75499. //
  75500. // For an example of a color LUT, see here:
  75501. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  75502. // For explanations on color grading, see here:
  75503. // http://udn.epicgames.com/Three/ColorGrading.html
  75504. //
  75505. var BABYLON;
  75506. (function (BABYLON) {
  75507. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  75508. __extends(ColorCorrectionPostProcess, _super);
  75509. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  75510. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  75511. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75512. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  75513. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75514. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75515. _this.onApply = function (effect) {
  75516. effect.setTexture("colorTable", _this._colorTableTexture);
  75517. };
  75518. return _this;
  75519. }
  75520. return ColorCorrectionPostProcess;
  75521. }(BABYLON.PostProcess));
  75522. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  75523. })(BABYLON || (BABYLON = {}));
  75524. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  75525. "use strict";
  75526. var BABYLON;
  75527. (function (BABYLON) {
  75528. var TonemappingOperator;
  75529. (function (TonemappingOperator) {
  75530. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  75531. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  75532. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  75533. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  75534. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  75535. ;
  75536. var TonemapPostProcess = /** @class */ (function (_super) {
  75537. __extends(TonemapPostProcess, _super);
  75538. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  75539. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75540. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75541. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  75542. _this._operator = _operator;
  75543. _this.exposureAdjustment = exposureAdjustment;
  75544. var defines = "#define ";
  75545. if (_this._operator === TonemappingOperator.Hable)
  75546. defines += "HABLE_TONEMAPPING";
  75547. else if (_this._operator === TonemappingOperator.Reinhard)
  75548. defines += "REINHARD_TONEMAPPING";
  75549. else if (_this._operator === TonemappingOperator.HejiDawson)
  75550. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  75551. else if (_this._operator === TonemappingOperator.Photographic)
  75552. defines += "PHOTOGRAPHIC_TONEMAPPING";
  75553. //sadly a second call to create the effect.
  75554. _this.updateEffect(defines);
  75555. _this.onApply = function (effect) {
  75556. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  75557. };
  75558. return _this;
  75559. }
  75560. return TonemapPostProcess;
  75561. }(BABYLON.PostProcess));
  75562. BABYLON.TonemapPostProcess = TonemapPostProcess;
  75563. })(BABYLON || (BABYLON = {}));
  75564. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  75565. "use strict";
  75566. var BABYLON;
  75567. (function (BABYLON) {
  75568. var DisplayPassPostProcess = /** @class */ (function (_super) {
  75569. __extends(DisplayPassPostProcess, _super);
  75570. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  75571. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  75572. }
  75573. return DisplayPassPostProcess;
  75574. }(BABYLON.PostProcess));
  75575. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  75576. })(BABYLON || (BABYLON = {}));
  75577. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  75578. "use strict";
  75579. var BABYLON;
  75580. (function (BABYLON) {
  75581. var HighlightsPostProcess = /** @class */ (function (_super) {
  75582. __extends(HighlightsPostProcess, _super);
  75583. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75584. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75585. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  75586. }
  75587. return HighlightsPostProcess;
  75588. }(BABYLON.PostProcess));
  75589. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  75590. })(BABYLON || (BABYLON = {}));
  75591. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  75592. "use strict";
  75593. var BABYLON;
  75594. (function (BABYLON) {
  75595. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  75596. __extends(ImageProcessingPostProcess, _super);
  75597. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  75598. if (camera === void 0) { camera = null; }
  75599. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75600. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  75601. _this._fromLinearSpace = true;
  75602. /**
  75603. * Defines cache preventing GC.
  75604. */
  75605. _this._defines = {
  75606. IMAGEPROCESSING: false,
  75607. VIGNETTE: false,
  75608. VIGNETTEBLENDMODEMULTIPLY: false,
  75609. VIGNETTEBLENDMODEOPAQUE: false,
  75610. TONEMAPPING: false,
  75611. CONTRAST: false,
  75612. COLORCURVES: false,
  75613. COLORGRADING: false,
  75614. COLORGRADING3D: false,
  75615. FROMLINEARSPACE: false,
  75616. SAMPLER3DGREENDEPTH: false,
  75617. SAMPLER3DBGRMAP: false,
  75618. IMAGEPROCESSINGPOSTPROCESS: false,
  75619. EXPOSURE: false,
  75620. };
  75621. // Setup the configuration as forced by the constructor. This would then not force the
  75622. // scene materials output in linear space and let untouched the default forward pass.
  75623. if (imageProcessingConfiguration) {
  75624. imageProcessingConfiguration.applyByPostProcess = true;
  75625. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  75626. // This will cause the shader to be compiled
  75627. _this.fromLinearSpace = false;
  75628. }
  75629. else {
  75630. _this._attachImageProcessingConfiguration(null, true);
  75631. _this.imageProcessingConfiguration.applyByPostProcess = true;
  75632. }
  75633. _this.onApply = function (effect) {
  75634. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  75635. };
  75636. return _this;
  75637. }
  75638. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  75639. /**
  75640. * Gets the image processing configuration used either in this material.
  75641. */
  75642. get: function () {
  75643. return this._imageProcessingConfiguration;
  75644. },
  75645. /**
  75646. * Sets the Default image processing configuration used either in the this material.
  75647. *
  75648. * If sets to null, the scene one is in use.
  75649. */
  75650. set: function (value) {
  75651. this._attachImageProcessingConfiguration(value);
  75652. },
  75653. enumerable: true,
  75654. configurable: true
  75655. });
  75656. /**
  75657. * Attaches a new image processing configuration to the PBR Material.
  75658. * @param configuration
  75659. */
  75660. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  75661. var _this = this;
  75662. if (doNotBuild === void 0) { doNotBuild = false; }
  75663. if (configuration === this._imageProcessingConfiguration) {
  75664. return;
  75665. }
  75666. // Detaches observer.
  75667. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75668. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75669. }
  75670. // Pick the scene configuration if needed.
  75671. if (!configuration) {
  75672. var scene = null;
  75673. var engine = this.getEngine();
  75674. var camera = this.getCamera();
  75675. if (camera) {
  75676. scene = camera.getScene();
  75677. }
  75678. else if (engine && engine.scenes) {
  75679. var scenes = engine.scenes;
  75680. scene = scenes[scenes.length - 1];
  75681. }
  75682. else {
  75683. scene = BABYLON.Engine.LastCreatedScene;
  75684. }
  75685. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  75686. }
  75687. else {
  75688. this._imageProcessingConfiguration = configuration;
  75689. }
  75690. // Attaches observer.
  75691. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  75692. _this._updateParameters();
  75693. });
  75694. // Ensure the effect will be rebuilt.
  75695. if (!doNotBuild) {
  75696. this._updateParameters();
  75697. }
  75698. };
  75699. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  75700. /**
  75701. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  75702. */
  75703. get: function () {
  75704. return this.imageProcessingConfiguration.colorCurves;
  75705. },
  75706. /**
  75707. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  75708. */
  75709. set: function (value) {
  75710. this.imageProcessingConfiguration.colorCurves = value;
  75711. },
  75712. enumerable: true,
  75713. configurable: true
  75714. });
  75715. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  75716. /**
  75717. * Gets wether the color curves effect is enabled.
  75718. */
  75719. get: function () {
  75720. return this.imageProcessingConfiguration.colorCurvesEnabled;
  75721. },
  75722. /**
  75723. * Sets wether the color curves effect is enabled.
  75724. */
  75725. set: function (value) {
  75726. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  75727. },
  75728. enumerable: true,
  75729. configurable: true
  75730. });
  75731. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  75732. /**
  75733. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  75734. */
  75735. get: function () {
  75736. return this.imageProcessingConfiguration.colorGradingTexture;
  75737. },
  75738. /**
  75739. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  75740. */
  75741. set: function (value) {
  75742. this.imageProcessingConfiguration.colorGradingTexture = value;
  75743. },
  75744. enumerable: true,
  75745. configurable: true
  75746. });
  75747. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  75748. /**
  75749. * Gets wether the color grading effect is enabled.
  75750. */
  75751. get: function () {
  75752. return this.imageProcessingConfiguration.colorGradingEnabled;
  75753. },
  75754. /**
  75755. * Gets wether the color grading effect is enabled.
  75756. */
  75757. set: function (value) {
  75758. this.imageProcessingConfiguration.colorGradingEnabled = value;
  75759. },
  75760. enumerable: true,
  75761. configurable: true
  75762. });
  75763. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  75764. /**
  75765. * Gets exposure used in the effect.
  75766. */
  75767. get: function () {
  75768. return this.imageProcessingConfiguration.exposure;
  75769. },
  75770. /**
  75771. * Sets exposure used in the effect.
  75772. */
  75773. set: function (value) {
  75774. this.imageProcessingConfiguration.exposure = value;
  75775. },
  75776. enumerable: true,
  75777. configurable: true
  75778. });
  75779. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  75780. /**
  75781. * Gets wether tonemapping is enabled or not.
  75782. */
  75783. get: function () {
  75784. return this._imageProcessingConfiguration.toneMappingEnabled;
  75785. },
  75786. /**
  75787. * Sets wether tonemapping is enabled or not
  75788. */
  75789. set: function (value) {
  75790. this._imageProcessingConfiguration.toneMappingEnabled = value;
  75791. },
  75792. enumerable: true,
  75793. configurable: true
  75794. });
  75795. ;
  75796. ;
  75797. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  75798. /**
  75799. * Gets contrast used in the effect.
  75800. */
  75801. get: function () {
  75802. return this.imageProcessingConfiguration.contrast;
  75803. },
  75804. /**
  75805. * Sets contrast used in the effect.
  75806. */
  75807. set: function (value) {
  75808. this.imageProcessingConfiguration.contrast = value;
  75809. },
  75810. enumerable: true,
  75811. configurable: true
  75812. });
  75813. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  75814. /**
  75815. * Gets Vignette stretch size.
  75816. */
  75817. get: function () {
  75818. return this.imageProcessingConfiguration.vignetteStretch;
  75819. },
  75820. /**
  75821. * Sets Vignette stretch size.
  75822. */
  75823. set: function (value) {
  75824. this.imageProcessingConfiguration.vignetteStretch = value;
  75825. },
  75826. enumerable: true,
  75827. configurable: true
  75828. });
  75829. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  75830. /**
  75831. * Gets Vignette centre X Offset.
  75832. */
  75833. get: function () {
  75834. return this.imageProcessingConfiguration.vignetteCentreX;
  75835. },
  75836. /**
  75837. * Sets Vignette centre X Offset.
  75838. */
  75839. set: function (value) {
  75840. this.imageProcessingConfiguration.vignetteCentreX = value;
  75841. },
  75842. enumerable: true,
  75843. configurable: true
  75844. });
  75845. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  75846. /**
  75847. * Gets Vignette centre Y Offset.
  75848. */
  75849. get: function () {
  75850. return this.imageProcessingConfiguration.vignetteCentreY;
  75851. },
  75852. /**
  75853. * Sets Vignette centre Y Offset.
  75854. */
  75855. set: function (value) {
  75856. this.imageProcessingConfiguration.vignetteCentreY = value;
  75857. },
  75858. enumerable: true,
  75859. configurable: true
  75860. });
  75861. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  75862. /**
  75863. * Gets Vignette weight or intensity of the vignette effect.
  75864. */
  75865. get: function () {
  75866. return this.imageProcessingConfiguration.vignetteWeight;
  75867. },
  75868. /**
  75869. * Sets Vignette weight or intensity of the vignette effect.
  75870. */
  75871. set: function (value) {
  75872. this.imageProcessingConfiguration.vignetteWeight = value;
  75873. },
  75874. enumerable: true,
  75875. configurable: true
  75876. });
  75877. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  75878. /**
  75879. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  75880. * if vignetteEnabled is set to true.
  75881. */
  75882. get: function () {
  75883. return this.imageProcessingConfiguration.vignetteColor;
  75884. },
  75885. /**
  75886. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  75887. * if vignetteEnabled is set to true.
  75888. */
  75889. set: function (value) {
  75890. this.imageProcessingConfiguration.vignetteColor = value;
  75891. },
  75892. enumerable: true,
  75893. configurable: true
  75894. });
  75895. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  75896. /**
  75897. * Gets Camera field of view used by the Vignette effect.
  75898. */
  75899. get: function () {
  75900. return this.imageProcessingConfiguration.vignetteCameraFov;
  75901. },
  75902. /**
  75903. * Sets Camera field of view used by the Vignette effect.
  75904. */
  75905. set: function (value) {
  75906. this.imageProcessingConfiguration.vignetteCameraFov = value;
  75907. },
  75908. enumerable: true,
  75909. configurable: true
  75910. });
  75911. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  75912. /**
  75913. * Gets the vignette blend mode allowing different kind of effect.
  75914. */
  75915. get: function () {
  75916. return this.imageProcessingConfiguration.vignetteBlendMode;
  75917. },
  75918. /**
  75919. * Sets the vignette blend mode allowing different kind of effect.
  75920. */
  75921. set: function (value) {
  75922. this.imageProcessingConfiguration.vignetteBlendMode = value;
  75923. },
  75924. enumerable: true,
  75925. configurable: true
  75926. });
  75927. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  75928. /**
  75929. * Gets wether the vignette effect is enabled.
  75930. */
  75931. get: function () {
  75932. return this.imageProcessingConfiguration.vignetteEnabled;
  75933. },
  75934. /**
  75935. * Sets wether the vignette effect is enabled.
  75936. */
  75937. set: function (value) {
  75938. this.imageProcessingConfiguration.vignetteEnabled = value;
  75939. },
  75940. enumerable: true,
  75941. configurable: true
  75942. });
  75943. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  75944. /**
  75945. * Gets wether the input of the processing is in Gamma or Linear Space.
  75946. */
  75947. get: function () {
  75948. return this._fromLinearSpace;
  75949. },
  75950. /**
  75951. * Sets wether the input of the processing is in Gamma or Linear Space.
  75952. */
  75953. set: function (value) {
  75954. if (this._fromLinearSpace === value) {
  75955. return;
  75956. }
  75957. this._fromLinearSpace = value;
  75958. this._updateParameters();
  75959. },
  75960. enumerable: true,
  75961. configurable: true
  75962. });
  75963. ImageProcessingPostProcess.prototype.getClassName = function () {
  75964. return "ImageProcessingPostProcess";
  75965. };
  75966. ImageProcessingPostProcess.prototype._updateParameters = function () {
  75967. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  75968. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  75969. var defines = "";
  75970. for (var define in this._defines) {
  75971. if (this._defines[define]) {
  75972. defines += "#define " + define + ";\r\n";
  75973. }
  75974. }
  75975. var samplers = ["textureSampler"];
  75976. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  75977. var uniforms = ["scale"];
  75978. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  75979. this.updateEffect(defines, uniforms, samplers);
  75980. };
  75981. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  75982. _super.prototype.dispose.call(this, camera);
  75983. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75984. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75985. }
  75986. this.imageProcessingConfiguration.applyByPostProcess = false;
  75987. };
  75988. __decorate([
  75989. BABYLON.serialize()
  75990. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  75991. return ImageProcessingPostProcess;
  75992. }(BABYLON.PostProcess));
  75993. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  75994. })(BABYLON || (BABYLON = {}));
  75995. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  75996. "use strict";
  75997. var BABYLON;
  75998. (function (BABYLON) {
  75999. var Bone = /** @class */ (function (_super) {
  76000. __extends(Bone, _super);
  76001. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  76002. if (parentBone === void 0) { parentBone = null; }
  76003. if (localMatrix === void 0) { localMatrix = null; }
  76004. if (restPose === void 0) { restPose = null; }
  76005. if (baseMatrix === void 0) { baseMatrix = null; }
  76006. if (index === void 0) { index = null; }
  76007. var _this = _super.call(this, name, skeleton.getScene()) || this;
  76008. _this.name = name;
  76009. _this.children = new Array();
  76010. _this.animations = new Array();
  76011. // Set this value to map this bone to a different index in the transform matrices.
  76012. // Set this value to -1 to exclude the bone from the transform matrices.
  76013. _this._index = null;
  76014. _this._worldTransform = new BABYLON.Matrix();
  76015. _this._absoluteTransform = new BABYLON.Matrix();
  76016. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  76017. _this._scaleMatrix = BABYLON.Matrix.Identity();
  76018. _this._scaleVector = BABYLON.Vector3.One();
  76019. _this._negateScaleChildren = BABYLON.Vector3.One();
  76020. _this._scalingDeterminant = 1;
  76021. _this._skeleton = skeleton;
  76022. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  76023. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  76024. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  76025. _this._index = index;
  76026. skeleton.bones.push(_this);
  76027. _this.setParent(parentBone, false);
  76028. _this._updateDifferenceMatrix();
  76029. return _this;
  76030. }
  76031. Object.defineProperty(Bone.prototype, "_matrix", {
  76032. get: function () {
  76033. return this._localMatrix;
  76034. },
  76035. set: function (val) {
  76036. if (this._localMatrix) {
  76037. this._localMatrix.copyFrom(val);
  76038. }
  76039. else {
  76040. this._localMatrix = val;
  76041. }
  76042. },
  76043. enumerable: true,
  76044. configurable: true
  76045. });
  76046. // Members
  76047. Bone.prototype.getSkeleton = function () {
  76048. return this._skeleton;
  76049. };
  76050. Bone.prototype.getParent = function () {
  76051. return this._parent;
  76052. };
  76053. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  76054. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  76055. if (this._parent === parent) {
  76056. return;
  76057. }
  76058. if (this._parent) {
  76059. var index = this._parent.children.indexOf(this);
  76060. if (index !== -1) {
  76061. this._parent.children.splice(index, 1);
  76062. }
  76063. }
  76064. this._parent = parent;
  76065. if (this._parent) {
  76066. this._parent.children.push(this);
  76067. }
  76068. if (updateDifferenceMatrix) {
  76069. this._updateDifferenceMatrix();
  76070. }
  76071. };
  76072. Bone.prototype.getLocalMatrix = function () {
  76073. return this._localMatrix;
  76074. };
  76075. Bone.prototype.getBaseMatrix = function () {
  76076. return this._baseMatrix;
  76077. };
  76078. Bone.prototype.getRestPose = function () {
  76079. return this._restPose;
  76080. };
  76081. Bone.prototype.returnToRest = function () {
  76082. this.updateMatrix(this._restPose.clone());
  76083. };
  76084. Bone.prototype.getWorldMatrix = function () {
  76085. return this._worldTransform;
  76086. };
  76087. Bone.prototype.getInvertedAbsoluteTransform = function () {
  76088. return this._invertedAbsoluteTransform;
  76089. };
  76090. Bone.prototype.getAbsoluteTransform = function () {
  76091. return this._absoluteTransform;
  76092. };
  76093. Object.defineProperty(Bone.prototype, "position", {
  76094. // Properties (matches AbstractMesh properties)
  76095. get: function () {
  76096. return this.getPosition();
  76097. },
  76098. set: function (newPosition) {
  76099. this.setPosition(newPosition);
  76100. },
  76101. enumerable: true,
  76102. configurable: true
  76103. });
  76104. Object.defineProperty(Bone.prototype, "rotation", {
  76105. get: function () {
  76106. return this.getRotation();
  76107. },
  76108. set: function (newRotation) {
  76109. this.setRotation(newRotation);
  76110. },
  76111. enumerable: true,
  76112. configurable: true
  76113. });
  76114. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  76115. get: function () {
  76116. return this.getRotationQuaternion();
  76117. },
  76118. set: function (newRotation) {
  76119. this.setRotationQuaternion(newRotation);
  76120. },
  76121. enumerable: true,
  76122. configurable: true
  76123. });
  76124. Object.defineProperty(Bone.prototype, "scaling", {
  76125. get: function () {
  76126. return this.getScale();
  76127. },
  76128. set: function (newScaling) {
  76129. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  76130. },
  76131. enumerable: true,
  76132. configurable: true
  76133. });
  76134. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  76135. /**
  76136. * Gets the animation properties override
  76137. */
  76138. get: function () {
  76139. return this._skeleton.animationPropertiesOverride;
  76140. },
  76141. enumerable: true,
  76142. configurable: true
  76143. });
  76144. // Methods
  76145. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  76146. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  76147. this._baseMatrix = matrix.clone();
  76148. this._localMatrix = matrix.clone();
  76149. this._skeleton._markAsDirty();
  76150. if (updateDifferenceMatrix) {
  76151. this._updateDifferenceMatrix();
  76152. }
  76153. };
  76154. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  76155. if (!rootMatrix) {
  76156. rootMatrix = this._baseMatrix;
  76157. }
  76158. if (this._parent) {
  76159. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  76160. }
  76161. else {
  76162. this._absoluteTransform.copyFrom(rootMatrix);
  76163. }
  76164. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  76165. for (var index = 0; index < this.children.length; index++) {
  76166. this.children[index]._updateDifferenceMatrix();
  76167. }
  76168. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  76169. };
  76170. Bone.prototype.markAsDirty = function () {
  76171. this._currentRenderId++;
  76172. this._childRenderId++;
  76173. this._skeleton._markAsDirty();
  76174. };
  76175. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  76176. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  76177. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  76178. // all animation may be coming from a library skeleton, so may need to create animation
  76179. if (this.animations.length === 0) {
  76180. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  76181. this.animations[0].setKeys([]);
  76182. }
  76183. // get animation info / verify there is such a range from the source bone
  76184. var sourceRange = source.animations[0].getRange(rangeName);
  76185. if (!sourceRange) {
  76186. return false;
  76187. }
  76188. var from = sourceRange.from;
  76189. var to = sourceRange.to;
  76190. var sourceKeys = source.animations[0].getKeys();
  76191. // rescaling prep
  76192. var sourceBoneLength = source.length;
  76193. var sourceParent = source.getParent();
  76194. var parent = this.getParent();
  76195. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  76196. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  76197. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  76198. var destKeys = this.animations[0].getKeys();
  76199. // loop vars declaration
  76200. var orig;
  76201. var origTranslation;
  76202. var mat;
  76203. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  76204. orig = sourceKeys[key];
  76205. if (orig.frame >= from && orig.frame <= to) {
  76206. if (rescaleAsRequired) {
  76207. mat = orig.value.clone();
  76208. // scale based on parent ratio, when bone has parent
  76209. if (parentScalingReqd) {
  76210. origTranslation = mat.getTranslation();
  76211. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  76212. // scale based on skeleton dimension ratio when root bone, and value is passed
  76213. }
  76214. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  76215. origTranslation = mat.getTranslation();
  76216. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  76217. // use original when root bone, and no data for skelDimensionsRatio
  76218. }
  76219. else {
  76220. mat = orig.value;
  76221. }
  76222. }
  76223. else {
  76224. mat = orig.value;
  76225. }
  76226. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  76227. }
  76228. }
  76229. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  76230. return true;
  76231. };
  76232. /**
  76233. * Translate the bone in local or world space.
  76234. * @param vec The amount to translate the bone.
  76235. * @param space The space that the translation is in.
  76236. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76237. */
  76238. Bone.prototype.translate = function (vec, space, mesh) {
  76239. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76240. var lm = this.getLocalMatrix();
  76241. if (space == BABYLON.Space.LOCAL) {
  76242. lm.m[12] += vec.x;
  76243. lm.m[13] += vec.y;
  76244. lm.m[14] += vec.z;
  76245. }
  76246. else {
  76247. var wm = null;
  76248. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76249. if (mesh) {
  76250. wm = mesh.getWorldMatrix();
  76251. }
  76252. this._skeleton.computeAbsoluteTransforms();
  76253. var tmat = Bone._tmpMats[0];
  76254. var tvec = Bone._tmpVecs[0];
  76255. if (this._parent) {
  76256. if (mesh && wm) {
  76257. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76258. tmat.multiplyToRef(wm, tmat);
  76259. }
  76260. else {
  76261. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76262. }
  76263. }
  76264. tmat.m[12] = 0;
  76265. tmat.m[13] = 0;
  76266. tmat.m[14] = 0;
  76267. tmat.invert();
  76268. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  76269. lm.m[12] += tvec.x;
  76270. lm.m[13] += tvec.y;
  76271. lm.m[14] += tvec.z;
  76272. }
  76273. this.markAsDirty();
  76274. };
  76275. /**
  76276. * Set the postion of the bone in local or world space.
  76277. * @param position The position to set the bone.
  76278. * @param space The space that the position is in.
  76279. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76280. */
  76281. Bone.prototype.setPosition = function (position, space, mesh) {
  76282. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76283. var lm = this.getLocalMatrix();
  76284. if (space == BABYLON.Space.LOCAL) {
  76285. lm.m[12] = position.x;
  76286. lm.m[13] = position.y;
  76287. lm.m[14] = position.z;
  76288. }
  76289. else {
  76290. var wm = null;
  76291. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76292. if (mesh) {
  76293. wm = mesh.getWorldMatrix();
  76294. }
  76295. this._skeleton.computeAbsoluteTransforms();
  76296. var tmat = Bone._tmpMats[0];
  76297. var vec = Bone._tmpVecs[0];
  76298. if (this._parent) {
  76299. if (mesh && wm) {
  76300. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76301. tmat.multiplyToRef(wm, tmat);
  76302. }
  76303. else {
  76304. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76305. }
  76306. }
  76307. tmat.invert();
  76308. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  76309. lm.m[12] = vec.x;
  76310. lm.m[13] = vec.y;
  76311. lm.m[14] = vec.z;
  76312. }
  76313. this.markAsDirty();
  76314. };
  76315. /**
  76316. * Set the absolute postion of the bone (world space).
  76317. * @param position The position to set the bone.
  76318. * @param mesh The mesh that this bone is attached to.
  76319. */
  76320. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  76321. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  76322. };
  76323. /**
  76324. * Set the scale of the bone on the x, y and z axes.
  76325. * @param x The scale of the bone on the x axis.
  76326. * @param x The scale of the bone on the y axis.
  76327. * @param z The scale of the bone on the z axis.
  76328. * @param scaleChildren Set this to true if children of the bone should be scaled.
  76329. */
  76330. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  76331. if (scaleChildren === void 0) { scaleChildren = false; }
  76332. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  76333. if (!scaleChildren) {
  76334. this._negateScaleChildren.x = 1 / x;
  76335. this._negateScaleChildren.y = 1 / y;
  76336. this._negateScaleChildren.z = 1 / z;
  76337. }
  76338. this._syncScaleVector();
  76339. }
  76340. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  76341. };
  76342. /**
  76343. * Scale the bone on the x, y and z axes.
  76344. * @param x The amount to scale the bone on the x axis.
  76345. * @param x The amount to scale the bone on the y axis.
  76346. * @param z The amount to scale the bone on the z axis.
  76347. * @param scaleChildren Set this to true if children of the bone should be scaled.
  76348. */
  76349. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  76350. if (scaleChildren === void 0) { scaleChildren = false; }
  76351. var locMat = this.getLocalMatrix();
  76352. var origLocMat = Bone._tmpMats[0];
  76353. origLocMat.copyFrom(locMat);
  76354. var origLocMatInv = Bone._tmpMats[1];
  76355. origLocMatInv.copyFrom(origLocMat);
  76356. origLocMatInv.invert();
  76357. var scaleMat = Bone._tmpMats[2];
  76358. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  76359. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  76360. this._scaleVector.x *= x;
  76361. this._scaleVector.y *= y;
  76362. this._scaleVector.z *= z;
  76363. locMat.multiplyToRef(origLocMatInv, locMat);
  76364. locMat.multiplyToRef(scaleMat, locMat);
  76365. locMat.multiplyToRef(origLocMat, locMat);
  76366. var parent = this.getParent();
  76367. if (parent) {
  76368. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  76369. }
  76370. else {
  76371. this.getAbsoluteTransform().copyFrom(locMat);
  76372. }
  76373. var len = this.children.length;
  76374. scaleMat.invert();
  76375. for (var i = 0; i < len; i++) {
  76376. var child = this.children[i];
  76377. var cm = child.getLocalMatrix();
  76378. cm.multiplyToRef(scaleMat, cm);
  76379. var lm = child.getLocalMatrix();
  76380. lm.m[12] *= x;
  76381. lm.m[13] *= y;
  76382. lm.m[14] *= z;
  76383. }
  76384. this.computeAbsoluteTransforms();
  76385. if (scaleChildren) {
  76386. for (var i = 0; i < len; i++) {
  76387. this.children[i].scale(x, y, z, scaleChildren);
  76388. }
  76389. }
  76390. this.markAsDirty();
  76391. };
  76392. /**
  76393. * Set the yaw, pitch, and roll of the bone in local or world space.
  76394. * @param yaw The rotation of the bone on the y axis.
  76395. * @param pitch The rotation of the bone on the x axis.
  76396. * @param roll The rotation of the bone on the z axis.
  76397. * @param space The space that the axes of rotation are in.
  76398. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76399. */
  76400. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  76401. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76402. var rotMat = Bone._tmpMats[0];
  76403. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  76404. var rotMatInv = Bone._tmpMats[1];
  76405. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  76406. rotMatInv.multiplyToRef(rotMat, rotMat);
  76407. this._rotateWithMatrix(rotMat, space, mesh);
  76408. };
  76409. /**
  76410. * Rotate the bone on an axis in local or world space.
  76411. * @param axis The axis to rotate the bone on.
  76412. * @param amount The amount to rotate the bone.
  76413. * @param space The space that the axis is in.
  76414. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76415. */
  76416. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  76417. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76418. var rmat = Bone._tmpMats[0];
  76419. rmat.m[12] = 0;
  76420. rmat.m[13] = 0;
  76421. rmat.m[14] = 0;
  76422. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  76423. this._rotateWithMatrix(rmat, space, mesh);
  76424. };
  76425. /**
  76426. * Set the rotation of the bone to a particular axis angle in local or world space.
  76427. * @param axis The axis to rotate the bone on.
  76428. * @param angle The angle that the bone should be rotated to.
  76429. * @param space The space that the axis is in.
  76430. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76431. */
  76432. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  76433. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76434. var rotMat = Bone._tmpMats[0];
  76435. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  76436. var rotMatInv = Bone._tmpMats[1];
  76437. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  76438. rotMatInv.multiplyToRef(rotMat, rotMat);
  76439. this._rotateWithMatrix(rotMat, space, mesh);
  76440. };
  76441. /**
  76442. * Set the euler rotation of the bone in local of world space.
  76443. * @param rotation The euler rotation that the bone should be set to.
  76444. * @param space The space that the rotation is in.
  76445. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76446. */
  76447. Bone.prototype.setRotation = function (rotation, space, mesh) {
  76448. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76449. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  76450. };
  76451. /**
  76452. * Set the quaternion rotation of the bone in local of world space.
  76453. * @param quat The quaternion rotation that the bone should be set to.
  76454. * @param space The space that the rotation is in.
  76455. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76456. */
  76457. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  76458. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76459. var rotMatInv = Bone._tmpMats[0];
  76460. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  76461. var rotMat = Bone._tmpMats[1];
  76462. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  76463. rotMatInv.multiplyToRef(rotMat, rotMat);
  76464. this._rotateWithMatrix(rotMat, space, mesh);
  76465. };
  76466. /**
  76467. * Set the rotation matrix of the bone in local of world space.
  76468. * @param rotMat The rotation matrix that the bone should be set to.
  76469. * @param space The space that the rotation is in.
  76470. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76471. */
  76472. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  76473. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76474. var rotMatInv = Bone._tmpMats[0];
  76475. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  76476. var rotMat2 = Bone._tmpMats[1];
  76477. rotMat2.copyFrom(rotMat);
  76478. rotMatInv.multiplyToRef(rotMat, rotMat2);
  76479. this._rotateWithMatrix(rotMat2, space, mesh);
  76480. };
  76481. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  76482. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76483. var lmat = this.getLocalMatrix();
  76484. var lx = lmat.m[12];
  76485. var ly = lmat.m[13];
  76486. var lz = lmat.m[14];
  76487. var parent = this.getParent();
  76488. var parentScale = Bone._tmpMats[3];
  76489. var parentScaleInv = Bone._tmpMats[4];
  76490. if (parent) {
  76491. if (space == BABYLON.Space.WORLD) {
  76492. if (mesh) {
  76493. parentScale.copyFrom(mesh.getWorldMatrix());
  76494. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  76495. }
  76496. else {
  76497. parentScale.copyFrom(parent.getAbsoluteTransform());
  76498. }
  76499. }
  76500. else {
  76501. parentScale = parent._scaleMatrix;
  76502. }
  76503. parentScaleInv.copyFrom(parentScale);
  76504. parentScaleInv.invert();
  76505. lmat.multiplyToRef(parentScale, lmat);
  76506. lmat.multiplyToRef(rmat, lmat);
  76507. lmat.multiplyToRef(parentScaleInv, lmat);
  76508. }
  76509. else {
  76510. if (space == BABYLON.Space.WORLD && mesh) {
  76511. parentScale.copyFrom(mesh.getWorldMatrix());
  76512. parentScaleInv.copyFrom(parentScale);
  76513. parentScaleInv.invert();
  76514. lmat.multiplyToRef(parentScale, lmat);
  76515. lmat.multiplyToRef(rmat, lmat);
  76516. lmat.multiplyToRef(parentScaleInv, lmat);
  76517. }
  76518. else {
  76519. lmat.multiplyToRef(rmat, lmat);
  76520. }
  76521. }
  76522. lmat.m[12] = lx;
  76523. lmat.m[13] = ly;
  76524. lmat.m[14] = lz;
  76525. this.computeAbsoluteTransforms();
  76526. this.markAsDirty();
  76527. };
  76528. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  76529. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76530. if (space == BABYLON.Space.WORLD) {
  76531. var scaleMatrix = Bone._tmpMats[2];
  76532. scaleMatrix.copyFrom(this._scaleMatrix);
  76533. rotMatInv.copyFrom(this.getAbsoluteTransform());
  76534. if (mesh) {
  76535. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  76536. var meshScale = Bone._tmpMats[3];
  76537. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  76538. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  76539. }
  76540. rotMatInv.invert();
  76541. scaleMatrix.m[0] *= this._scalingDeterminant;
  76542. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  76543. }
  76544. else {
  76545. rotMatInv.copyFrom(this.getLocalMatrix());
  76546. rotMatInv.invert();
  76547. var scaleMatrix = Bone._tmpMats[2];
  76548. scaleMatrix.copyFrom(this._scaleMatrix);
  76549. if (this._parent) {
  76550. var pscaleMatrix = Bone._tmpMats[3];
  76551. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  76552. pscaleMatrix.invert();
  76553. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  76554. }
  76555. else {
  76556. scaleMatrix.m[0] *= this._scalingDeterminant;
  76557. }
  76558. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  76559. }
  76560. };
  76561. /**
  76562. * Get the scale of the bone
  76563. * @returns the scale of the bone
  76564. */
  76565. Bone.prototype.getScale = function () {
  76566. return this._scaleVector.clone();
  76567. };
  76568. /**
  76569. * Copy the scale of the bone to a vector3.
  76570. * @param result The vector3 to copy the scale to
  76571. */
  76572. Bone.prototype.getScaleToRef = function (result) {
  76573. result.copyFrom(this._scaleVector);
  76574. };
  76575. /**
  76576. * Get the position of the bone in local or world space.
  76577. * @param space The space that the returned position is in.
  76578. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76579. * @returns The position of the bone
  76580. */
  76581. Bone.prototype.getPosition = function (space, mesh) {
  76582. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76583. if (mesh === void 0) { mesh = null; }
  76584. var pos = BABYLON.Vector3.Zero();
  76585. this.getPositionToRef(space, mesh, pos);
  76586. return pos;
  76587. };
  76588. /**
  76589. * Copy the position of the bone to a vector3 in local or world space.
  76590. * @param space The space that the returned position is in.
  76591. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76592. * @param result The vector3 to copy the position to.
  76593. */
  76594. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  76595. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76596. if (space == BABYLON.Space.LOCAL) {
  76597. var lm = this.getLocalMatrix();
  76598. result.x = lm.m[12];
  76599. result.y = lm.m[13];
  76600. result.z = lm.m[14];
  76601. }
  76602. else {
  76603. var wm = null;
  76604. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76605. if (mesh) {
  76606. wm = mesh.getWorldMatrix();
  76607. }
  76608. this._skeleton.computeAbsoluteTransforms();
  76609. var tmat = Bone._tmpMats[0];
  76610. if (mesh && wm) {
  76611. tmat.copyFrom(this.getAbsoluteTransform());
  76612. tmat.multiplyToRef(wm, tmat);
  76613. }
  76614. else {
  76615. tmat = this.getAbsoluteTransform();
  76616. }
  76617. result.x = tmat.m[12];
  76618. result.y = tmat.m[13];
  76619. result.z = tmat.m[14];
  76620. }
  76621. };
  76622. /**
  76623. * Get the absolute position of the bone (world space).
  76624. * @param mesh The mesh that this bone is attached to.
  76625. * @returns The absolute position of the bone
  76626. */
  76627. Bone.prototype.getAbsolutePosition = function (mesh) {
  76628. if (mesh === void 0) { mesh = null; }
  76629. var pos = BABYLON.Vector3.Zero();
  76630. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  76631. return pos;
  76632. };
  76633. /**
  76634. * Copy the absolute position of the bone (world space) to the result param.
  76635. * @param mesh The mesh that this bone is attached to.
  76636. * @param result The vector3 to copy the absolute position to.
  76637. */
  76638. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  76639. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  76640. };
  76641. /**
  76642. * Compute the absolute transforms of this bone and its children.
  76643. */
  76644. Bone.prototype.computeAbsoluteTransforms = function () {
  76645. if (this._parent) {
  76646. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  76647. }
  76648. else {
  76649. this._absoluteTransform.copyFrom(this._localMatrix);
  76650. var poseMatrix = this._skeleton.getPoseMatrix();
  76651. if (poseMatrix) {
  76652. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  76653. }
  76654. }
  76655. var children = this.children;
  76656. var len = children.length;
  76657. for (var i = 0; i < len; i++) {
  76658. children[i].computeAbsoluteTransforms();
  76659. }
  76660. };
  76661. Bone.prototype._syncScaleVector = function () {
  76662. var lm = this.getLocalMatrix();
  76663. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  76664. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  76665. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  76666. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  76667. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  76668. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  76669. this._scaleVector.x = xs * Math.sqrt(xsq);
  76670. this._scaleVector.y = ys * Math.sqrt(ysq);
  76671. this._scaleVector.z = zs * Math.sqrt(zsq);
  76672. if (this._parent) {
  76673. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  76674. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  76675. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  76676. }
  76677. 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);
  76678. };
  76679. /**
  76680. * Get the world direction from an axis that is in the local space of the bone.
  76681. * @param localAxis The local direction that is used to compute the world direction.
  76682. * @param mesh The mesh that this bone is attached to.
  76683. * @returns The world direction
  76684. */
  76685. Bone.prototype.getDirection = function (localAxis, mesh) {
  76686. if (mesh === void 0) { mesh = null; }
  76687. var result = BABYLON.Vector3.Zero();
  76688. this.getDirectionToRef(localAxis, mesh, result);
  76689. return result;
  76690. };
  76691. /**
  76692. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  76693. * @param localAxis The local direction that is used to compute the world direction.
  76694. * @param mesh The mesh that this bone is attached to.
  76695. * @param result The vector3 that the world direction will be copied to.
  76696. */
  76697. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  76698. if (mesh === void 0) { mesh = null; }
  76699. var wm = null;
  76700. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76701. if (mesh) {
  76702. wm = mesh.getWorldMatrix();
  76703. }
  76704. this._skeleton.computeAbsoluteTransforms();
  76705. var mat = Bone._tmpMats[0];
  76706. mat.copyFrom(this.getAbsoluteTransform());
  76707. if (mesh && wm) {
  76708. mat.multiplyToRef(wm, mat);
  76709. }
  76710. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  76711. result.normalize();
  76712. };
  76713. /**
  76714. * Get the euler rotation of the bone in local or world space.
  76715. * @param space The space that the rotation should be in.
  76716. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76717. * @returns The euler rotation
  76718. */
  76719. Bone.prototype.getRotation = function (space, mesh) {
  76720. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76721. if (mesh === void 0) { mesh = null; }
  76722. var result = BABYLON.Vector3.Zero();
  76723. this.getRotationToRef(space, mesh, result);
  76724. return result;
  76725. };
  76726. /**
  76727. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  76728. * @param space The space that the rotation should be in.
  76729. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76730. * @param result The vector3 that the rotation should be copied to.
  76731. */
  76732. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  76733. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76734. if (mesh === void 0) { mesh = null; }
  76735. var quat = Bone._tmpQuat;
  76736. this.getRotationQuaternionToRef(space, mesh, quat);
  76737. quat.toEulerAnglesToRef(result);
  76738. };
  76739. /**
  76740. * Get the quaternion rotation of the bone in either local or world space.
  76741. * @param space The space that the rotation should be in.
  76742. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76743. * @returns The quaternion rotation
  76744. */
  76745. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  76746. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76747. if (mesh === void 0) { mesh = null; }
  76748. var result = BABYLON.Quaternion.Identity();
  76749. this.getRotationQuaternionToRef(space, mesh, result);
  76750. return result;
  76751. };
  76752. /**
  76753. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  76754. * @param space The space that the rotation should be in.
  76755. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76756. * @param result The quaternion that the rotation should be copied to.
  76757. */
  76758. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  76759. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76760. if (mesh === void 0) { mesh = null; }
  76761. if (space == BABYLON.Space.LOCAL) {
  76762. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  76763. }
  76764. else {
  76765. var mat = Bone._tmpMats[0];
  76766. var amat = this.getAbsoluteTransform();
  76767. if (mesh) {
  76768. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  76769. }
  76770. else {
  76771. mat.copyFrom(amat);
  76772. }
  76773. mat.m[0] *= this._scalingDeterminant;
  76774. mat.m[1] *= this._scalingDeterminant;
  76775. mat.m[2] *= this._scalingDeterminant;
  76776. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  76777. }
  76778. };
  76779. /**
  76780. * Get the rotation matrix of the bone in local or world space.
  76781. * @param space The space that the rotation should be in.
  76782. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76783. * @returns The rotation matrix
  76784. */
  76785. Bone.prototype.getRotationMatrix = function (space, mesh) {
  76786. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76787. var result = BABYLON.Matrix.Identity();
  76788. this.getRotationMatrixToRef(space, mesh, result);
  76789. return result;
  76790. };
  76791. /**
  76792. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  76793. * @param space The space that the rotation should be in.
  76794. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76795. * @param result The quaternion that the rotation should be copied to.
  76796. */
  76797. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  76798. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76799. if (space == BABYLON.Space.LOCAL) {
  76800. this.getLocalMatrix().getRotationMatrixToRef(result);
  76801. }
  76802. else {
  76803. var mat = Bone._tmpMats[0];
  76804. var amat = this.getAbsoluteTransform();
  76805. if (mesh) {
  76806. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  76807. }
  76808. else {
  76809. mat.copyFrom(amat);
  76810. }
  76811. mat.m[0] *= this._scalingDeterminant;
  76812. mat.m[1] *= this._scalingDeterminant;
  76813. mat.m[2] *= this._scalingDeterminant;
  76814. mat.getRotationMatrixToRef(result);
  76815. }
  76816. };
  76817. /**
  76818. * Get the world position of a point that is in the local space of the bone.
  76819. * @param position The local position
  76820. * @param mesh The mesh that this bone is attached to.
  76821. * @returns The world position
  76822. */
  76823. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  76824. if (mesh === void 0) { mesh = null; }
  76825. var result = BABYLON.Vector3.Zero();
  76826. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  76827. return result;
  76828. };
  76829. /**
  76830. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  76831. * @param position The local position
  76832. * @param mesh The mesh that this bone is attached to.
  76833. * @param result The vector3 that the world position should be copied to.
  76834. */
  76835. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  76836. if (mesh === void 0) { mesh = null; }
  76837. var wm = null;
  76838. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76839. if (mesh) {
  76840. wm = mesh.getWorldMatrix();
  76841. }
  76842. this._skeleton.computeAbsoluteTransforms();
  76843. var tmat = Bone._tmpMats[0];
  76844. if (mesh && wm) {
  76845. tmat.copyFrom(this.getAbsoluteTransform());
  76846. tmat.multiplyToRef(wm, tmat);
  76847. }
  76848. else {
  76849. tmat = this.getAbsoluteTransform();
  76850. }
  76851. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  76852. };
  76853. /**
  76854. * Get the local position of a point that is in world space.
  76855. * @param position The world position
  76856. * @param mesh The mesh that this bone is attached to.
  76857. * @returns The local position
  76858. */
  76859. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  76860. if (mesh === void 0) { mesh = null; }
  76861. var result = BABYLON.Vector3.Zero();
  76862. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  76863. return result;
  76864. };
  76865. /**
  76866. * Get the local position of a point that is in world space and copy it to the result param.
  76867. * @param position The world position
  76868. * @param mesh The mesh that this bone is attached to.
  76869. * @param result The vector3 that the local position should be copied to.
  76870. */
  76871. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  76872. if (mesh === void 0) { mesh = null; }
  76873. var wm = null;
  76874. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76875. if (mesh) {
  76876. wm = mesh.getWorldMatrix();
  76877. }
  76878. this._skeleton.computeAbsoluteTransforms();
  76879. var tmat = Bone._tmpMats[0];
  76880. tmat.copyFrom(this.getAbsoluteTransform());
  76881. if (mesh && wm) {
  76882. tmat.multiplyToRef(wm, tmat);
  76883. }
  76884. tmat.invert();
  76885. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  76886. };
  76887. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76888. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  76889. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  76890. return Bone;
  76891. }(BABYLON.Node));
  76892. BABYLON.Bone = Bone;
  76893. })(BABYLON || (BABYLON = {}));
  76894. //# sourceMappingURL=babylon.bone.js.map
  76895. "use strict";
  76896. var BABYLON;
  76897. (function (BABYLON) {
  76898. var BoneIKController = /** @class */ (function () {
  76899. function BoneIKController(mesh, bone, options) {
  76900. this.targetPosition = BABYLON.Vector3.Zero();
  76901. this.poleTargetPosition = BABYLON.Vector3.Zero();
  76902. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  76903. this.poleAngle = 0;
  76904. this.slerpAmount = 1;
  76905. this._bone1Quat = BABYLON.Quaternion.Identity();
  76906. this._bone1Mat = BABYLON.Matrix.Identity();
  76907. this._bone2Ang = Math.PI;
  76908. this._maxAngle = Math.PI;
  76909. this._rightHandedSystem = false;
  76910. this._bendAxis = BABYLON.Vector3.Right();
  76911. this._slerping = false;
  76912. this._adjustRoll = 0;
  76913. this._bone2 = bone;
  76914. this._bone1 = bone.getParent();
  76915. if (!this._bone1) {
  76916. return;
  76917. }
  76918. this.mesh = mesh;
  76919. var bonePos = bone.getPosition();
  76920. if (bone.getAbsoluteTransform().determinant() > 0) {
  76921. this._rightHandedSystem = true;
  76922. this._bendAxis.x = 0;
  76923. this._bendAxis.y = 0;
  76924. this._bendAxis.z = -1;
  76925. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  76926. this._adjustRoll = Math.PI * .5;
  76927. this._bendAxis.z = 1;
  76928. }
  76929. }
  76930. if (this._bone1.length) {
  76931. var boneScale1 = this._bone1.getScale();
  76932. var boneScale2 = this._bone2.getScale();
  76933. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  76934. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  76935. }
  76936. else if (this._bone1.children[0]) {
  76937. mesh.computeWorldMatrix(true);
  76938. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  76939. var pos2 = this._bone2.getAbsolutePosition(mesh);
  76940. var pos3 = this._bone1.getAbsolutePosition(mesh);
  76941. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  76942. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  76943. }
  76944. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  76945. this.maxAngle = Math.PI;
  76946. if (options) {
  76947. if (options.targetMesh) {
  76948. this.targetMesh = options.targetMesh;
  76949. this.targetMesh.computeWorldMatrix(true);
  76950. }
  76951. if (options.poleTargetMesh) {
  76952. this.poleTargetMesh = options.poleTargetMesh;
  76953. this.poleTargetMesh.computeWorldMatrix(true);
  76954. }
  76955. else if (options.poleTargetBone) {
  76956. this.poleTargetBone = options.poleTargetBone;
  76957. }
  76958. else if (this._bone1.getParent()) {
  76959. this.poleTargetBone = this._bone1.getParent();
  76960. }
  76961. if (options.poleTargetLocalOffset) {
  76962. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  76963. }
  76964. if (options.poleAngle) {
  76965. this.poleAngle = options.poleAngle;
  76966. }
  76967. if (options.bendAxis) {
  76968. this._bendAxis.copyFrom(options.bendAxis);
  76969. }
  76970. if (options.maxAngle) {
  76971. this.maxAngle = options.maxAngle;
  76972. }
  76973. if (options.slerpAmount) {
  76974. this.slerpAmount = options.slerpAmount;
  76975. }
  76976. }
  76977. }
  76978. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  76979. get: function () {
  76980. return this._maxAngle;
  76981. },
  76982. set: function (value) {
  76983. this._setMaxAngle(value);
  76984. },
  76985. enumerable: true,
  76986. configurable: true
  76987. });
  76988. BoneIKController.prototype._setMaxAngle = function (ang) {
  76989. if (ang < 0) {
  76990. ang = 0;
  76991. }
  76992. if (ang > Math.PI || ang == undefined) {
  76993. ang = Math.PI;
  76994. }
  76995. this._maxAngle = ang;
  76996. var a = this._bone1Length;
  76997. var b = this._bone2Length;
  76998. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  76999. };
  77000. BoneIKController.prototype.update = function () {
  77001. var bone1 = this._bone1;
  77002. if (!bone1) {
  77003. return;
  77004. }
  77005. var target = this.targetPosition;
  77006. var poleTarget = this.poleTargetPosition;
  77007. var mat1 = BoneIKController._tmpMats[0];
  77008. var mat2 = BoneIKController._tmpMats[1];
  77009. if (this.targetMesh) {
  77010. target.copyFrom(this.targetMesh.getAbsolutePosition());
  77011. }
  77012. if (this.poleTargetBone) {
  77013. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  77014. }
  77015. else if (this.poleTargetMesh) {
  77016. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  77017. }
  77018. var bonePos = BoneIKController._tmpVecs[0];
  77019. var zaxis = BoneIKController._tmpVecs[1];
  77020. var xaxis = BoneIKController._tmpVecs[2];
  77021. var yaxis = BoneIKController._tmpVecs[3];
  77022. var upAxis = BoneIKController._tmpVecs[4];
  77023. var _tmpQuat = BoneIKController._tmpQuat;
  77024. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  77025. poleTarget.subtractToRef(bonePos, upAxis);
  77026. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  77027. upAxis.y = 1;
  77028. }
  77029. else {
  77030. upAxis.normalize();
  77031. }
  77032. target.subtractToRef(bonePos, yaxis);
  77033. yaxis.normalize();
  77034. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  77035. zaxis.normalize();
  77036. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  77037. xaxis.normalize();
  77038. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  77039. var a = this._bone1Length;
  77040. var b = this._bone2Length;
  77041. var c = BABYLON.Vector3.Distance(bonePos, target);
  77042. if (this._maxReach > 0) {
  77043. c = Math.min(this._maxReach, c);
  77044. }
  77045. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  77046. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  77047. if (acosa > 1) {
  77048. acosa = 1;
  77049. }
  77050. if (acosb > 1) {
  77051. acosb = 1;
  77052. }
  77053. if (acosa < -1) {
  77054. acosa = -1;
  77055. }
  77056. if (acosb < -1) {
  77057. acosb = -1;
  77058. }
  77059. var angA = Math.acos(acosa);
  77060. var angB = Math.acos(acosb);
  77061. var angC = -angA - angB;
  77062. if (this._rightHandedSystem) {
  77063. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  77064. mat2.multiplyToRef(mat1, mat1);
  77065. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  77066. mat2.multiplyToRef(mat1, mat1);
  77067. }
  77068. else {
  77069. var _tmpVec = BoneIKController._tmpVecs[5];
  77070. _tmpVec.copyFrom(this._bendAxis);
  77071. _tmpVec.x *= -1;
  77072. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  77073. mat2.multiplyToRef(mat1, mat1);
  77074. }
  77075. if (this.poleAngle) {
  77076. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  77077. mat1.multiplyToRef(mat2, mat1);
  77078. }
  77079. if (this._bone1) {
  77080. if (this.slerpAmount < 1) {
  77081. if (!this._slerping) {
  77082. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  77083. }
  77084. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  77085. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  77086. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  77087. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  77088. this._slerping = true;
  77089. }
  77090. else {
  77091. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  77092. this._bone1Mat.copyFrom(mat1);
  77093. this._slerping = false;
  77094. }
  77095. }
  77096. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  77097. this._bone2Ang = angC;
  77098. };
  77099. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77100. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  77101. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77102. return BoneIKController;
  77103. }());
  77104. BABYLON.BoneIKController = BoneIKController;
  77105. })(BABYLON || (BABYLON = {}));
  77106. //# sourceMappingURL=babylon.boneIKController.js.map
  77107. "use strict";
  77108. var BABYLON;
  77109. (function (BABYLON) {
  77110. var BoneLookController = /** @class */ (function () {
  77111. /**
  77112. * Create a BoneLookController
  77113. * @param mesh the mesh that the bone belongs to
  77114. * @param bone the bone that will be looking to the target
  77115. * @param target the target Vector3 to look at
  77116. * @param settings optional settings:
  77117. * - maxYaw: the maximum angle the bone will yaw to
  77118. * - minYaw: the minimum angle the bone will yaw to
  77119. * - maxPitch: the maximum angle the bone will pitch to
  77120. * - minPitch: the minimum angle the bone will yaw to
  77121. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  77122. * - upAxis: the up axis of the coordinate system
  77123. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  77124. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  77125. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  77126. * - adjustYaw: used to make an adjustment to the yaw of the bone
  77127. * - adjustPitch: used to make an adjustment to the pitch of the bone
  77128. * - adjustRoll: used to make an adjustment to the roll of the bone
  77129. **/
  77130. function BoneLookController(mesh, bone, target, options) {
  77131. /**
  77132. * The up axis of the coordinate system that is used when the bone is rotated.
  77133. */
  77134. this.upAxis = BABYLON.Vector3.Up();
  77135. /**
  77136. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  77137. */
  77138. this.upAxisSpace = BABYLON.Space.LOCAL;
  77139. /**
  77140. * Used to make an adjustment to the yaw of the bone.
  77141. */
  77142. this.adjustYaw = 0;
  77143. /**
  77144. * Used to make an adjustment to the pitch of the bone.
  77145. */
  77146. this.adjustPitch = 0;
  77147. /**
  77148. * Used to make an adjustment to the roll of the bone.
  77149. */
  77150. this.adjustRoll = 0;
  77151. /**
  77152. * 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).
  77153. */
  77154. this.slerpAmount = 1;
  77155. this._boneQuat = BABYLON.Quaternion.Identity();
  77156. this._slerping = false;
  77157. this._firstFrameSkipped = false;
  77158. this._fowardAxis = BABYLON.Vector3.Forward();
  77159. this.mesh = mesh;
  77160. this.bone = bone;
  77161. this.target = target;
  77162. if (options) {
  77163. if (options.adjustYaw) {
  77164. this.adjustYaw = options.adjustYaw;
  77165. }
  77166. if (options.adjustPitch) {
  77167. this.adjustPitch = options.adjustPitch;
  77168. }
  77169. if (options.adjustRoll) {
  77170. this.adjustRoll = options.adjustRoll;
  77171. }
  77172. if (options.maxYaw != null) {
  77173. this.maxYaw = options.maxYaw;
  77174. }
  77175. else {
  77176. this.maxYaw = Math.PI;
  77177. }
  77178. if (options.minYaw != null) {
  77179. this.minYaw = options.minYaw;
  77180. }
  77181. else {
  77182. this.minYaw = -Math.PI;
  77183. }
  77184. if (options.maxPitch != null) {
  77185. this.maxPitch = options.maxPitch;
  77186. }
  77187. else {
  77188. this.maxPitch = Math.PI;
  77189. }
  77190. if (options.minPitch != null) {
  77191. this.minPitch = options.minPitch;
  77192. }
  77193. else {
  77194. this.minPitch = -Math.PI;
  77195. }
  77196. if (options.slerpAmount != null) {
  77197. this.slerpAmount = options.slerpAmount;
  77198. }
  77199. if (options.upAxis != null) {
  77200. this.upAxis = options.upAxis;
  77201. }
  77202. if (options.upAxisSpace != null) {
  77203. this.upAxisSpace = options.upAxisSpace;
  77204. }
  77205. if (options.yawAxis != null || options.pitchAxis != null) {
  77206. var newYawAxis = BABYLON.Axis.Y;
  77207. var newPitchAxis = BABYLON.Axis.X;
  77208. if (options.yawAxis != null) {
  77209. newYawAxis = options.yawAxis.clone();
  77210. newYawAxis.normalize();
  77211. }
  77212. if (options.pitchAxis != null) {
  77213. newPitchAxis = options.pitchAxis.clone();
  77214. newPitchAxis.normalize();
  77215. }
  77216. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  77217. this._transformYawPitch = BABYLON.Matrix.Identity();
  77218. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  77219. this._transformYawPitchInv = this._transformYawPitch.clone();
  77220. this._transformYawPitch.invert();
  77221. }
  77222. }
  77223. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  77224. this.upAxisSpace = BABYLON.Space.LOCAL;
  77225. }
  77226. }
  77227. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  77228. /**
  77229. * Get/set the minimum yaw angle that the bone can look to.
  77230. */
  77231. get: function () {
  77232. return this._minYaw;
  77233. },
  77234. set: function (value) {
  77235. this._minYaw = value;
  77236. this._minYawSin = Math.sin(value);
  77237. this._minYawCos = Math.cos(value);
  77238. if (this._maxYaw != null) {
  77239. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  77240. this._yawRange = this._maxYaw - this._minYaw;
  77241. }
  77242. },
  77243. enumerable: true,
  77244. configurable: true
  77245. });
  77246. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  77247. /**
  77248. * Get/set the maximum yaw angle that the bone can look to.
  77249. */
  77250. get: function () {
  77251. return this._maxYaw;
  77252. },
  77253. set: function (value) {
  77254. this._maxYaw = value;
  77255. this._maxYawSin = Math.sin(value);
  77256. this._maxYawCos = Math.cos(value);
  77257. if (this._minYaw != null) {
  77258. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  77259. this._yawRange = this._maxYaw - this._minYaw;
  77260. }
  77261. },
  77262. enumerable: true,
  77263. configurable: true
  77264. });
  77265. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  77266. /**
  77267. * Get/set the minimum pitch angle that the bone can look to.
  77268. */
  77269. get: function () {
  77270. return this._minPitch;
  77271. },
  77272. set: function (value) {
  77273. this._minPitch = value;
  77274. this._minPitchTan = Math.tan(value);
  77275. },
  77276. enumerable: true,
  77277. configurable: true
  77278. });
  77279. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  77280. /**
  77281. * Get/set the maximum pitch angle that the bone can look to.
  77282. */
  77283. get: function () {
  77284. return this._maxPitch;
  77285. },
  77286. set: function (value) {
  77287. this._maxPitch = value;
  77288. this._maxPitchTan = Math.tan(value);
  77289. },
  77290. enumerable: true,
  77291. configurable: true
  77292. });
  77293. /**
  77294. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  77295. */
  77296. BoneLookController.prototype.update = function () {
  77297. //skip the first frame when slerping so that the mesh rotation is correct
  77298. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  77299. this._firstFrameSkipped = true;
  77300. return;
  77301. }
  77302. var bone = this.bone;
  77303. var bonePos = BoneLookController._tmpVecs[0];
  77304. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  77305. var target = this.target;
  77306. var _tmpMat1 = BoneLookController._tmpMats[0];
  77307. var _tmpMat2 = BoneLookController._tmpMats[1];
  77308. var mesh = this.mesh;
  77309. var parentBone = bone.getParent();
  77310. var upAxis = BoneLookController._tmpVecs[1];
  77311. upAxis.copyFrom(this.upAxis);
  77312. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  77313. if (this._transformYawPitch) {
  77314. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  77315. }
  77316. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  77317. }
  77318. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  77319. mesh.getDirectionToRef(upAxis, upAxis);
  77320. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  77321. upAxis.normalize();
  77322. }
  77323. }
  77324. var checkYaw = false;
  77325. var checkPitch = false;
  77326. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  77327. checkYaw = true;
  77328. }
  77329. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  77330. checkPitch = true;
  77331. }
  77332. if (checkYaw || checkPitch) {
  77333. var spaceMat = BoneLookController._tmpMats[2];
  77334. var spaceMatInv = BoneLookController._tmpMats[3];
  77335. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  77336. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  77337. }
  77338. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  77339. spaceMat.copyFrom(mesh.getWorldMatrix());
  77340. }
  77341. else {
  77342. var forwardAxis = BoneLookController._tmpVecs[2];
  77343. forwardAxis.copyFrom(this._fowardAxis);
  77344. if (this._transformYawPitch) {
  77345. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  77346. }
  77347. if (parentBone) {
  77348. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  77349. }
  77350. else {
  77351. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  77352. }
  77353. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  77354. rightAxis.normalize();
  77355. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  77356. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  77357. }
  77358. spaceMat.invertToRef(spaceMatInv);
  77359. var xzlen = null;
  77360. if (checkPitch) {
  77361. var localTarget = BoneLookController._tmpVecs[3];
  77362. target.subtractToRef(bonePos, localTarget);
  77363. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  77364. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  77365. var pitch = Math.atan2(localTarget.y, xzlen);
  77366. var newPitch = pitch;
  77367. if (pitch > this._maxPitch) {
  77368. localTarget.y = this._maxPitchTan * xzlen;
  77369. newPitch = this._maxPitch;
  77370. }
  77371. else if (pitch < this._minPitch) {
  77372. localTarget.y = this._minPitchTan * xzlen;
  77373. newPitch = this._minPitch;
  77374. }
  77375. if (pitch != newPitch) {
  77376. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  77377. localTarget.addInPlace(bonePos);
  77378. target = localTarget;
  77379. }
  77380. }
  77381. if (checkYaw) {
  77382. var localTarget = BoneLookController._tmpVecs[4];
  77383. target.subtractToRef(bonePos, localTarget);
  77384. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  77385. var yaw = Math.atan2(localTarget.x, localTarget.z);
  77386. var newYaw = yaw;
  77387. if (yaw > this._maxYaw || yaw < this._minYaw) {
  77388. if (xzlen == null) {
  77389. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  77390. }
  77391. if (this._yawRange > Math.PI) {
  77392. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  77393. localTarget.z = this._maxYawCos * xzlen;
  77394. localTarget.x = this._maxYawSin * xzlen;
  77395. newYaw = this._maxYaw;
  77396. }
  77397. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  77398. localTarget.z = this._minYawCos * xzlen;
  77399. localTarget.x = this._minYawSin * xzlen;
  77400. newYaw = this._minYaw;
  77401. }
  77402. }
  77403. else {
  77404. if (yaw > this._maxYaw) {
  77405. localTarget.z = this._maxYawCos * xzlen;
  77406. localTarget.x = this._maxYawSin * xzlen;
  77407. newYaw = this._maxYaw;
  77408. }
  77409. else if (yaw < this._minYaw) {
  77410. localTarget.z = this._minYawCos * xzlen;
  77411. localTarget.x = this._minYawSin * xzlen;
  77412. newYaw = this._minYaw;
  77413. }
  77414. }
  77415. }
  77416. if (this._slerping && this._yawRange > Math.PI) {
  77417. //are we going to be crossing into the min/max region?
  77418. var boneFwd = BoneLookController._tmpVecs[8];
  77419. boneFwd.copyFrom(BABYLON.Axis.Z);
  77420. if (this._transformYawPitch) {
  77421. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  77422. }
  77423. var boneRotMat = BoneLookController._tmpMats[4];
  77424. this._boneQuat.toRotationMatrix(boneRotMat);
  77425. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  77426. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  77427. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  77428. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  77429. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  77430. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  77431. if (angBtwTar > angBtwMidYaw) {
  77432. if (xzlen == null) {
  77433. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  77434. }
  77435. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  77436. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  77437. if (angBtwMin < angBtwMax) {
  77438. newYaw = boneYaw + Math.PI * .75;
  77439. localTarget.z = Math.cos(newYaw) * xzlen;
  77440. localTarget.x = Math.sin(newYaw) * xzlen;
  77441. }
  77442. else {
  77443. newYaw = boneYaw - Math.PI * .75;
  77444. localTarget.z = Math.cos(newYaw) * xzlen;
  77445. localTarget.x = Math.sin(newYaw) * xzlen;
  77446. }
  77447. }
  77448. }
  77449. if (yaw != newYaw) {
  77450. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  77451. localTarget.addInPlace(bonePos);
  77452. target = localTarget;
  77453. }
  77454. }
  77455. }
  77456. var zaxis = BoneLookController._tmpVecs[5];
  77457. var xaxis = BoneLookController._tmpVecs[6];
  77458. var yaxis = BoneLookController._tmpVecs[7];
  77459. var _tmpQuat = BoneLookController._tmpQuat;
  77460. target.subtractToRef(bonePos, zaxis);
  77461. zaxis.normalize();
  77462. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  77463. xaxis.normalize();
  77464. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  77465. yaxis.normalize();
  77466. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  77467. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  77468. return;
  77469. }
  77470. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  77471. return;
  77472. }
  77473. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  77474. return;
  77475. }
  77476. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  77477. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  77478. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  77479. }
  77480. if (this.slerpAmount < 1) {
  77481. if (!this._slerping) {
  77482. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  77483. }
  77484. if (this._transformYawPitch) {
  77485. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  77486. }
  77487. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  77488. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  77489. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  77490. this._slerping = true;
  77491. }
  77492. else {
  77493. if (this._transformYawPitch) {
  77494. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  77495. }
  77496. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  77497. this._slerping = false;
  77498. }
  77499. };
  77500. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  77501. var angDiff = ang2 - ang1;
  77502. angDiff %= Math.PI * 2;
  77503. if (angDiff > Math.PI) {
  77504. angDiff -= Math.PI * 2;
  77505. }
  77506. else if (angDiff < -Math.PI) {
  77507. angDiff += Math.PI * 2;
  77508. }
  77509. return angDiff;
  77510. };
  77511. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  77512. ang1 %= (2 * Math.PI);
  77513. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  77514. ang2 %= (2 * Math.PI);
  77515. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  77516. var ab = 0;
  77517. if (ang1 < ang2) {
  77518. ab = ang2 - ang1;
  77519. }
  77520. else {
  77521. ab = ang1 - ang2;
  77522. }
  77523. if (ab > Math.PI) {
  77524. ab = Math.PI * 2 - ab;
  77525. }
  77526. return ab;
  77527. };
  77528. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  77529. ang %= (2 * Math.PI);
  77530. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  77531. ang1 %= (2 * Math.PI);
  77532. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  77533. ang2 %= (2 * Math.PI);
  77534. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  77535. if (ang1 < ang2) {
  77536. if (ang > ang1 && ang < ang2) {
  77537. return true;
  77538. }
  77539. }
  77540. else {
  77541. if (ang > ang2 && ang < ang1) {
  77542. return true;
  77543. }
  77544. }
  77545. return false;
  77546. };
  77547. 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()];
  77548. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  77549. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77550. return BoneLookController;
  77551. }());
  77552. BABYLON.BoneLookController = BoneLookController;
  77553. })(BABYLON || (BABYLON = {}));
  77554. //# sourceMappingURL=babylon.boneLookController.js.map
  77555. "use strict";
  77556. var BABYLON;
  77557. (function (BABYLON) {
  77558. var Skeleton = /** @class */ (function () {
  77559. function Skeleton(name, id, scene) {
  77560. this.name = name;
  77561. this.id = id;
  77562. this.bones = new Array();
  77563. this.needInitialSkinMatrix = false;
  77564. this._isDirty = true;
  77565. this._meshesWithPoseMatrix = new Array();
  77566. this._identity = BABYLON.Matrix.Identity();
  77567. this._ranges = {};
  77568. this._lastAbsoluteTransformsUpdateId = -1;
  77569. /**
  77570. * Specifies if the skeleton should be serialized.
  77571. */
  77572. this.doNotSerialize = false;
  77573. // Events
  77574. /**
  77575. * An event triggered before computing the skeleton's matrices
  77576. */
  77577. this.onBeforeComputeObservable = new BABYLON.Observable();
  77578. this.bones = [];
  77579. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77580. scene.skeletons.push(this);
  77581. //make sure it will recalculate the matrix next time prepare is called.
  77582. this._isDirty = true;
  77583. }
  77584. // Members
  77585. Skeleton.prototype.getTransformMatrices = function (mesh) {
  77586. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  77587. return mesh._bonesTransformMatrices;
  77588. }
  77589. if (!this._transformMatrices) {
  77590. this.prepare();
  77591. }
  77592. return this._transformMatrices;
  77593. };
  77594. Skeleton.prototype.getScene = function () {
  77595. return this._scene;
  77596. };
  77597. // Methods
  77598. /**
  77599. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  77600. */
  77601. Skeleton.prototype.toString = function (fullDetails) {
  77602. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  77603. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  77604. if (fullDetails) {
  77605. ret += ", Ranges: {";
  77606. var first = true;
  77607. for (var name_1 in this._ranges) {
  77608. if (first) {
  77609. ret += ", ";
  77610. first = false;
  77611. }
  77612. ret += name_1;
  77613. }
  77614. ret += "}";
  77615. }
  77616. return ret;
  77617. };
  77618. /**
  77619. * Get bone's index searching by name
  77620. * @param {string} name is bone's name to search for
  77621. * @return {number} Indice of the bone. Returns -1 if not found
  77622. */
  77623. Skeleton.prototype.getBoneIndexByName = function (name) {
  77624. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  77625. if (this.bones[boneIndex].name === name) {
  77626. return boneIndex;
  77627. }
  77628. }
  77629. return -1;
  77630. };
  77631. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  77632. // check name not already in use
  77633. if (!this._ranges[name]) {
  77634. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  77635. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  77636. if (this.bones[i].animations[0]) {
  77637. this.bones[i].animations[0].createRange(name, from, to);
  77638. }
  77639. }
  77640. }
  77641. };
  77642. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  77643. if (deleteFrames === void 0) { deleteFrames = true; }
  77644. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  77645. if (this.bones[i].animations[0]) {
  77646. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  77647. }
  77648. }
  77649. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  77650. };
  77651. Skeleton.prototype.getAnimationRange = function (name) {
  77652. return this._ranges[name];
  77653. };
  77654. /**
  77655. * Returns as an Array, all AnimationRanges defined on this skeleton
  77656. */
  77657. Skeleton.prototype.getAnimationRanges = function () {
  77658. var animationRanges = [];
  77659. var name;
  77660. var i = 0;
  77661. for (name in this._ranges) {
  77662. animationRanges[i] = this._ranges[name];
  77663. i++;
  77664. }
  77665. return animationRanges;
  77666. };
  77667. /**
  77668. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  77669. */
  77670. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  77671. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77672. if (this._ranges[name] || !source.getAnimationRange(name)) {
  77673. return false;
  77674. }
  77675. var ret = true;
  77676. var frameOffset = this._getHighestAnimationFrame() + 1;
  77677. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  77678. var boneDict = {};
  77679. var sourceBones = source.bones;
  77680. var nBones;
  77681. var i;
  77682. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  77683. boneDict[sourceBones[i].name] = sourceBones[i];
  77684. }
  77685. if (this.bones.length !== sourceBones.length) {
  77686. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  77687. ret = false;
  77688. }
  77689. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  77690. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  77691. var boneName = this.bones[i].name;
  77692. var sourceBone = boneDict[boneName];
  77693. if (sourceBone) {
  77694. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  77695. }
  77696. else {
  77697. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  77698. ret = false;
  77699. }
  77700. }
  77701. // do not call createAnimationRange(), since it also is done to bones, which was already done
  77702. var range = source.getAnimationRange(name);
  77703. if (range) {
  77704. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  77705. }
  77706. return ret;
  77707. };
  77708. Skeleton.prototype.returnToRest = function () {
  77709. for (var index = 0; index < this.bones.length; index++) {
  77710. this.bones[index].returnToRest();
  77711. }
  77712. };
  77713. Skeleton.prototype._getHighestAnimationFrame = function () {
  77714. var ret = 0;
  77715. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  77716. if (this.bones[i].animations[0]) {
  77717. var highest = this.bones[i].animations[0].getHighestFrame();
  77718. if (ret < highest) {
  77719. ret = highest;
  77720. }
  77721. }
  77722. }
  77723. return ret;
  77724. };
  77725. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  77726. var range = this.getAnimationRange(name);
  77727. if (!range) {
  77728. return null;
  77729. }
  77730. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  77731. };
  77732. Skeleton.prototype._markAsDirty = function () {
  77733. this._isDirty = true;
  77734. };
  77735. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  77736. this._meshesWithPoseMatrix.push(mesh);
  77737. };
  77738. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  77739. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  77740. if (index > -1) {
  77741. this._meshesWithPoseMatrix.splice(index, 1);
  77742. }
  77743. };
  77744. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  77745. this.onBeforeComputeObservable.notifyObservers(this);
  77746. for (var index = 0; index < this.bones.length; index++) {
  77747. var bone = this.bones[index];
  77748. var parentBone = bone.getParent();
  77749. if (parentBone) {
  77750. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  77751. }
  77752. else {
  77753. if (initialSkinMatrix) {
  77754. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  77755. }
  77756. else {
  77757. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  77758. }
  77759. }
  77760. if (bone._index !== -1) {
  77761. var mappedIndex = bone._index === null ? index : bone._index;
  77762. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  77763. }
  77764. }
  77765. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  77766. };
  77767. Skeleton.prototype.prepare = function () {
  77768. if (!this._isDirty) {
  77769. return;
  77770. }
  77771. if (this.needInitialSkinMatrix) {
  77772. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  77773. var mesh = this._meshesWithPoseMatrix[index];
  77774. var poseMatrix = mesh.getPoseMatrix();
  77775. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  77776. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  77777. }
  77778. if (this._synchronizedWithMesh !== mesh) {
  77779. this._synchronizedWithMesh = mesh;
  77780. // Prepare bones
  77781. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  77782. var bone = this.bones[boneIndex];
  77783. if (!bone.getParent()) {
  77784. var matrix = bone.getBaseMatrix();
  77785. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  77786. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  77787. }
  77788. }
  77789. }
  77790. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  77791. }
  77792. }
  77793. else {
  77794. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  77795. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  77796. }
  77797. this._computeTransformMatrices(this._transformMatrices, null);
  77798. }
  77799. this._isDirty = false;
  77800. this._scene._activeBones.addCount(this.bones.length, false);
  77801. };
  77802. Skeleton.prototype.getAnimatables = function () {
  77803. if (!this._animatables || this._animatables.length !== this.bones.length) {
  77804. this._animatables = [];
  77805. for (var index = 0; index < this.bones.length; index++) {
  77806. this._animatables.push(this.bones[index]);
  77807. }
  77808. }
  77809. return this._animatables;
  77810. };
  77811. Skeleton.prototype.clone = function (name, id) {
  77812. var result = new Skeleton(name, id || name, this._scene);
  77813. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  77814. for (var index = 0; index < this.bones.length; index++) {
  77815. var source = this.bones[index];
  77816. var parentBone = null;
  77817. var parent_1 = source.getParent();
  77818. if (parent_1) {
  77819. var parentIndex = this.bones.indexOf(parent_1);
  77820. parentBone = result.bones[parentIndex];
  77821. }
  77822. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  77823. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  77824. }
  77825. if (this._ranges) {
  77826. result._ranges = {};
  77827. for (var rangeName in this._ranges) {
  77828. var range = this._ranges[rangeName];
  77829. if (range) {
  77830. result._ranges[rangeName] = range.clone();
  77831. }
  77832. }
  77833. }
  77834. this._isDirty = true;
  77835. return result;
  77836. };
  77837. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  77838. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  77839. this.bones.forEach(function (bone) {
  77840. bone.animations.forEach(function (animation) {
  77841. animation.enableBlending = true;
  77842. animation.blendingSpeed = blendingSpeed;
  77843. });
  77844. });
  77845. };
  77846. Skeleton.prototype.dispose = function () {
  77847. this._meshesWithPoseMatrix = [];
  77848. // Animations
  77849. this.getScene().stopAnimation(this);
  77850. // Remove from scene
  77851. this.getScene().removeSkeleton(this);
  77852. };
  77853. Skeleton.prototype.serialize = function () {
  77854. var serializationObject = {};
  77855. serializationObject.name = this.name;
  77856. serializationObject.id = this.id;
  77857. if (this.dimensionsAtRest) {
  77858. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  77859. }
  77860. serializationObject.bones = [];
  77861. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  77862. for (var index = 0; index < this.bones.length; index++) {
  77863. var bone = this.bones[index];
  77864. var parent_2 = bone.getParent();
  77865. var serializedBone = {
  77866. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  77867. name: bone.name,
  77868. matrix: bone.getBaseMatrix().toArray(),
  77869. rest: bone.getRestPose().toArray()
  77870. };
  77871. serializationObject.bones.push(serializedBone);
  77872. if (bone.length) {
  77873. serializedBone.length = bone.length;
  77874. }
  77875. if (bone.animations && bone.animations.length > 0) {
  77876. serializedBone.animation = bone.animations[0].serialize();
  77877. }
  77878. serializationObject.ranges = [];
  77879. for (var name in this._ranges) {
  77880. var source = this._ranges[name];
  77881. if (!source) {
  77882. continue;
  77883. }
  77884. var range = {};
  77885. range.name = name;
  77886. range.from = source.from;
  77887. range.to = source.to;
  77888. serializationObject.ranges.push(range);
  77889. }
  77890. }
  77891. return serializationObject;
  77892. };
  77893. Skeleton.Parse = function (parsedSkeleton, scene) {
  77894. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  77895. if (parsedSkeleton.dimensionsAtRest) {
  77896. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  77897. }
  77898. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  77899. var index;
  77900. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  77901. var parsedBone = parsedSkeleton.bones[index];
  77902. var parentBone = null;
  77903. if (parsedBone.parentBoneIndex > -1) {
  77904. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  77905. }
  77906. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  77907. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  77908. if (parsedBone.length) {
  77909. bone.length = parsedBone.length;
  77910. }
  77911. if (parsedBone.animation) {
  77912. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  77913. }
  77914. }
  77915. // placed after bones, so createAnimationRange can cascade down
  77916. if (parsedSkeleton.ranges) {
  77917. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  77918. var data = parsedSkeleton.ranges[index];
  77919. skeleton.createAnimationRange(data.name, data.from, data.to);
  77920. }
  77921. }
  77922. return skeleton;
  77923. };
  77924. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  77925. if (forceUpdate === void 0) { forceUpdate = false; }
  77926. var renderId = this._scene.getRenderId();
  77927. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  77928. this.bones[0].computeAbsoluteTransforms();
  77929. this._lastAbsoluteTransformsUpdateId = renderId;
  77930. }
  77931. };
  77932. Skeleton.prototype.getPoseMatrix = function () {
  77933. var poseMatrix = null;
  77934. if (this._meshesWithPoseMatrix.length > 0) {
  77935. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  77936. }
  77937. return poseMatrix;
  77938. };
  77939. Skeleton.prototype.sortBones = function () {
  77940. var bones = new Array();
  77941. var visited = new Array(this.bones.length);
  77942. for (var index = 0; index < this.bones.length; index++) {
  77943. this._sortBones(index, bones, visited);
  77944. }
  77945. this.bones = bones;
  77946. };
  77947. Skeleton.prototype._sortBones = function (index, bones, visited) {
  77948. if (visited[index]) {
  77949. return;
  77950. }
  77951. visited[index] = true;
  77952. var bone = this.bones[index];
  77953. if (bone._index === undefined) {
  77954. bone._index = index;
  77955. }
  77956. var parentBone = bone.getParent();
  77957. if (parentBone) {
  77958. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  77959. }
  77960. bones.push(bone);
  77961. };
  77962. return Skeleton;
  77963. }());
  77964. BABYLON.Skeleton = Skeleton;
  77965. })(BABYLON || (BABYLON = {}));
  77966. //# sourceMappingURL=babylon.skeleton.js.map
  77967. "use strict";
  77968. var BABYLON;
  77969. (function (BABYLON) {
  77970. var SphericalPolynomial = /** @class */ (function () {
  77971. function SphericalPolynomial() {
  77972. this.x = BABYLON.Vector3.Zero();
  77973. this.y = BABYLON.Vector3.Zero();
  77974. this.z = BABYLON.Vector3.Zero();
  77975. this.xx = BABYLON.Vector3.Zero();
  77976. this.yy = BABYLON.Vector3.Zero();
  77977. this.zz = BABYLON.Vector3.Zero();
  77978. this.xy = BABYLON.Vector3.Zero();
  77979. this.yz = BABYLON.Vector3.Zero();
  77980. this.zx = BABYLON.Vector3.Zero();
  77981. }
  77982. SphericalPolynomial.prototype.addAmbient = function (color) {
  77983. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  77984. this.xx = this.xx.add(colorVector);
  77985. this.yy = this.yy.add(colorVector);
  77986. this.zz = this.zz.add(colorVector);
  77987. };
  77988. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  77989. var result = new SphericalPolynomial();
  77990. result.x = harmonics.L11.scale(1.02333);
  77991. result.y = harmonics.L1_1.scale(1.02333);
  77992. result.z = harmonics.L10.scale(1.02333);
  77993. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  77994. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  77995. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  77996. result.yz = harmonics.L2_1.scale(0.858086);
  77997. result.zx = harmonics.L21.scale(0.858086);
  77998. result.xy = harmonics.L2_2.scale(0.858086);
  77999. result.scale(1.0 / Math.PI);
  78000. return result;
  78001. };
  78002. SphericalPolynomial.prototype.scale = function (scale) {
  78003. this.x = this.x.scale(scale);
  78004. this.y = this.y.scale(scale);
  78005. this.z = this.z.scale(scale);
  78006. this.xx = this.xx.scale(scale);
  78007. this.yy = this.yy.scale(scale);
  78008. this.zz = this.zz.scale(scale);
  78009. this.yz = this.yz.scale(scale);
  78010. this.zx = this.zx.scale(scale);
  78011. this.xy = this.xy.scale(scale);
  78012. };
  78013. return SphericalPolynomial;
  78014. }());
  78015. BABYLON.SphericalPolynomial = SphericalPolynomial;
  78016. var SphericalHarmonics = /** @class */ (function () {
  78017. function SphericalHarmonics() {
  78018. this.L00 = BABYLON.Vector3.Zero();
  78019. this.L1_1 = BABYLON.Vector3.Zero();
  78020. this.L10 = BABYLON.Vector3.Zero();
  78021. this.L11 = BABYLON.Vector3.Zero();
  78022. this.L2_2 = BABYLON.Vector3.Zero();
  78023. this.L2_1 = BABYLON.Vector3.Zero();
  78024. this.L20 = BABYLON.Vector3.Zero();
  78025. this.L21 = BABYLON.Vector3.Zero();
  78026. this.L22 = BABYLON.Vector3.Zero();
  78027. }
  78028. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  78029. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  78030. var c = colorVector.scale(deltaSolidAngle);
  78031. this.L00 = this.L00.add(c.scale(0.282095));
  78032. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  78033. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  78034. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  78035. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  78036. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  78037. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  78038. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  78039. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  78040. };
  78041. SphericalHarmonics.prototype.scale = function (scale) {
  78042. this.L00 = this.L00.scale(scale);
  78043. this.L1_1 = this.L1_1.scale(scale);
  78044. this.L10 = this.L10.scale(scale);
  78045. this.L11 = this.L11.scale(scale);
  78046. this.L2_2 = this.L2_2.scale(scale);
  78047. this.L2_1 = this.L2_1.scale(scale);
  78048. this.L20 = this.L20.scale(scale);
  78049. this.L21 = this.L21.scale(scale);
  78050. this.L22 = this.L22.scale(scale);
  78051. };
  78052. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  78053. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  78054. //
  78055. // E_lm = A_l * L_lm
  78056. //
  78057. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  78058. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  78059. // the scaling factors are given in equation 9.
  78060. // Constant (Band 0)
  78061. this.L00 = this.L00.scale(3.141593);
  78062. // Linear (Band 1)
  78063. this.L1_1 = this.L1_1.scale(2.094395);
  78064. this.L10 = this.L10.scale(2.094395);
  78065. this.L11 = this.L11.scale(2.094395);
  78066. // Quadratic (Band 2)
  78067. this.L2_2 = this.L2_2.scale(0.785398);
  78068. this.L2_1 = this.L2_1.scale(0.785398);
  78069. this.L20 = this.L20.scale(0.785398);
  78070. this.L21 = this.L21.scale(0.785398);
  78071. this.L22 = this.L22.scale(0.785398);
  78072. };
  78073. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  78074. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  78075. // L = (1/pi) * E * rho
  78076. //
  78077. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  78078. this.scale(1.0 / Math.PI);
  78079. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  78080. // (The pixel shader must apply albedo after texture fetches, etc).
  78081. };
  78082. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  78083. var result = new SphericalHarmonics();
  78084. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  78085. result.L1_1 = polynomial.y.scale(0.977204);
  78086. result.L10 = polynomial.z.scale(0.977204);
  78087. result.L11 = polynomial.x.scale(0.977204);
  78088. result.L2_2 = polynomial.xy.scale(1.16538);
  78089. result.L2_1 = polynomial.yz.scale(1.16538);
  78090. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  78091. result.L21 = polynomial.zx.scale(1.16538);
  78092. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  78093. result.scale(Math.PI);
  78094. return result;
  78095. };
  78096. return SphericalHarmonics;
  78097. }());
  78098. BABYLON.SphericalHarmonics = SphericalHarmonics;
  78099. })(BABYLON || (BABYLON = {}));
  78100. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  78101. "use strict";
  78102. var BABYLON;
  78103. (function (BABYLON) {
  78104. var FileFaceOrientation = /** @class */ (function () {
  78105. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  78106. this.name = name;
  78107. this.worldAxisForNormal = worldAxisForNormal;
  78108. this.worldAxisForFileX = worldAxisForFileX;
  78109. this.worldAxisForFileY = worldAxisForFileY;
  78110. }
  78111. return FileFaceOrientation;
  78112. }());
  78113. ;
  78114. /**
  78115. * Helper class dealing with the extraction of spherical polynomial dataArray
  78116. * from a cube map.
  78117. */
  78118. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  78119. function CubeMapToSphericalPolynomialTools() {
  78120. }
  78121. /**
  78122. * Converts a texture to the according Spherical Polynomial data.
  78123. * This extracts the first 3 orders only as they are the only one used in the lighting.
  78124. *
  78125. * @param texture The texture to extract the information from.
  78126. * @return The Spherical Polynomial data.
  78127. */
  78128. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  78129. if (!texture.isCube) {
  78130. // Only supports cube Textures currently.
  78131. return null;
  78132. }
  78133. var size = texture.getSize().width;
  78134. var right = texture.readPixels(0);
  78135. var left = texture.readPixels(1);
  78136. var up;
  78137. var down;
  78138. if (texture.isRenderTarget) {
  78139. up = texture.readPixels(3);
  78140. down = texture.readPixels(2);
  78141. }
  78142. else {
  78143. up = texture.readPixels(2);
  78144. down = texture.readPixels(3);
  78145. }
  78146. var front = texture.readPixels(4);
  78147. var back = texture.readPixels(5);
  78148. var gammaSpace = texture.gammaSpace;
  78149. // Always read as RGBA.
  78150. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  78151. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78152. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  78153. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78154. }
  78155. var cubeInfo = {
  78156. size: size,
  78157. right: right,
  78158. left: left,
  78159. up: up,
  78160. down: down,
  78161. front: front,
  78162. back: back,
  78163. format: format,
  78164. type: type,
  78165. gammaSpace: gammaSpace,
  78166. };
  78167. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  78168. };
  78169. /**
  78170. * Converts a cubemap to the according Spherical Polynomial data.
  78171. * This extracts the first 3 orders only as they are the only one used in the lighting.
  78172. *
  78173. * @param cubeInfo The Cube map to extract the information from.
  78174. * @return The Spherical Polynomial data.
  78175. */
  78176. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  78177. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  78178. var totalSolidAngle = 0.0;
  78179. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  78180. var du = 2.0 / cubeInfo.size;
  78181. var dv = du;
  78182. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  78183. var minUV = du * 0.5 - 1.0;
  78184. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  78185. var fileFace = this.FileFaces[faceIndex];
  78186. var dataArray = cubeInfo[fileFace.name];
  78187. var v = minUV;
  78188. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  78189. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  78190. // Because SP is still linear, so summation is fine in that basis.
  78191. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  78192. for (var y = 0; y < cubeInfo.size; y++) {
  78193. var u = minUV;
  78194. for (var x = 0; x < cubeInfo.size; x++) {
  78195. // World direction (not normalised)
  78196. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  78197. worldDirection.normalize();
  78198. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  78199. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  78200. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  78201. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  78202. // Handle Integer types.
  78203. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  78204. r /= 255;
  78205. g /= 255;
  78206. b /= 255;
  78207. }
  78208. // Handle Gamma space textures.
  78209. if (cubeInfo.gammaSpace) {
  78210. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  78211. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  78212. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  78213. }
  78214. var color = new BABYLON.Color3(r, g, b);
  78215. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  78216. totalSolidAngle += deltaSolidAngle;
  78217. u += du;
  78218. }
  78219. v += dv;
  78220. }
  78221. }
  78222. // Solid angle for entire sphere is 4*pi
  78223. var sphereSolidAngle = 4.0 * Math.PI;
  78224. // Adjust the solid angle to allow for how many faces we processed.
  78225. var facesProcessed = 6.0;
  78226. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  78227. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  78228. // This is needed because the numerical integration over the cube uses a
  78229. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  78230. // and also to compensate for accumulative error due to float precision in the summation.
  78231. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  78232. sphericalHarmonics.scale(correctionFactor);
  78233. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  78234. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  78235. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  78236. };
  78237. CubeMapToSphericalPolynomialTools.FileFaces = [
  78238. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  78239. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  78240. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  78241. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  78242. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  78243. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  78244. ];
  78245. return CubeMapToSphericalPolynomialTools;
  78246. }());
  78247. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  78248. })(BABYLON || (BABYLON = {}));
  78249. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  78250. "use strict";
  78251. var BABYLON;
  78252. (function (BABYLON) {
  78253. /**
  78254. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  78255. */
  78256. var PanoramaToCubeMapTools = /** @class */ (function () {
  78257. function PanoramaToCubeMapTools() {
  78258. }
  78259. /**
  78260. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  78261. *
  78262. * @param float32Array The source data.
  78263. * @param inputWidth The width of the input panorama.
  78264. * @param inputhHeight The height of the input panorama.
  78265. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  78266. * @return The cubemap data
  78267. */
  78268. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  78269. if (!float32Array) {
  78270. throw "ConvertPanoramaToCubemap: input cannot be null";
  78271. }
  78272. if (float32Array.length != inputWidth * inputHeight * 3) {
  78273. throw "ConvertPanoramaToCubemap: input size is wrong";
  78274. }
  78275. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  78276. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  78277. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  78278. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  78279. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  78280. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  78281. return {
  78282. front: textureFront,
  78283. back: textureBack,
  78284. left: textureLeft,
  78285. right: textureRight,
  78286. up: textureUp,
  78287. down: textureDown,
  78288. size: size,
  78289. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  78290. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  78291. gammaSpace: false,
  78292. };
  78293. };
  78294. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  78295. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  78296. var textureArray = new Float32Array(buffer);
  78297. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  78298. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  78299. var dy = 1 / texSize;
  78300. var fy = 0;
  78301. for (var y = 0; y < texSize; y++) {
  78302. var xv1 = faceData[0];
  78303. var xv2 = faceData[2];
  78304. for (var x = 0; x < texSize; x++) {
  78305. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  78306. v.normalize();
  78307. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  78308. // 3 channels per pixels
  78309. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  78310. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  78311. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  78312. xv1 = xv1.add(rotDX1);
  78313. xv2 = xv2.add(rotDX2);
  78314. }
  78315. fy += dy;
  78316. }
  78317. return textureArray;
  78318. };
  78319. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  78320. var theta = Math.atan2(vDir.z, vDir.x);
  78321. var phi = Math.acos(vDir.y);
  78322. while (theta < -Math.PI)
  78323. theta += 2 * Math.PI;
  78324. while (theta > Math.PI)
  78325. theta -= 2 * Math.PI;
  78326. var dx = theta / Math.PI;
  78327. var dy = phi / Math.PI;
  78328. // recenter.
  78329. dx = dx * 0.5 + 0.5;
  78330. var px = Math.round(dx * inputWidth);
  78331. if (px < 0)
  78332. px = 0;
  78333. else if (px >= inputWidth)
  78334. px = inputWidth - 1;
  78335. var py = Math.round(dy * inputHeight);
  78336. if (py < 0)
  78337. py = 0;
  78338. else if (py >= inputHeight)
  78339. py = inputHeight - 1;
  78340. var inputY = (inputHeight - py - 1);
  78341. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  78342. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  78343. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  78344. return {
  78345. r: r,
  78346. g: g,
  78347. b: b
  78348. };
  78349. };
  78350. PanoramaToCubeMapTools.FACE_FRONT = [
  78351. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  78352. new BABYLON.Vector3(1.0, -1.0, -1.0),
  78353. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  78354. new BABYLON.Vector3(1.0, 1.0, -1.0)
  78355. ];
  78356. PanoramaToCubeMapTools.FACE_BACK = [
  78357. new BABYLON.Vector3(1.0, -1.0, 1.0),
  78358. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  78359. new BABYLON.Vector3(1.0, 1.0, 1.0),
  78360. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  78361. ];
  78362. PanoramaToCubeMapTools.FACE_RIGHT = [
  78363. new BABYLON.Vector3(1.0, -1.0, -1.0),
  78364. new BABYLON.Vector3(1.0, -1.0, 1.0),
  78365. new BABYLON.Vector3(1.0, 1.0, -1.0),
  78366. new BABYLON.Vector3(1.0, 1.0, 1.0)
  78367. ];
  78368. PanoramaToCubeMapTools.FACE_LEFT = [
  78369. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  78370. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  78371. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  78372. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  78373. ];
  78374. PanoramaToCubeMapTools.FACE_DOWN = [
  78375. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  78376. new BABYLON.Vector3(1.0, 1.0, -1.0),
  78377. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  78378. new BABYLON.Vector3(1.0, 1.0, 1.0)
  78379. ];
  78380. PanoramaToCubeMapTools.FACE_UP = [
  78381. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  78382. new BABYLON.Vector3(1.0, -1.0, 1.0),
  78383. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  78384. new BABYLON.Vector3(1.0, -1.0, -1.0)
  78385. ];
  78386. return PanoramaToCubeMapTools;
  78387. }());
  78388. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  78389. })(BABYLON || (BABYLON = {}));
  78390. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  78391. "use strict";
  78392. var BABYLON;
  78393. (function (BABYLON) {
  78394. ;
  78395. /**
  78396. * This groups tools to convert HDR texture to native colors array.
  78397. */
  78398. var HDRTools = /** @class */ (function () {
  78399. function HDRTools() {
  78400. }
  78401. HDRTools.Ldexp = function (mantissa, exponent) {
  78402. if (exponent > 1023) {
  78403. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  78404. }
  78405. if (exponent < -1074) {
  78406. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  78407. }
  78408. return mantissa * Math.pow(2, exponent);
  78409. };
  78410. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  78411. if (exponent > 0) {
  78412. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  78413. float32array[index + 0] = red * exponent;
  78414. float32array[index + 1] = green * exponent;
  78415. float32array[index + 2] = blue * exponent;
  78416. }
  78417. else {
  78418. float32array[index + 0] = 0;
  78419. float32array[index + 1] = 0;
  78420. float32array[index + 2] = 0;
  78421. }
  78422. };
  78423. HDRTools.readStringLine = function (uint8array, startIndex) {
  78424. var line = "";
  78425. var character = "";
  78426. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  78427. character = String.fromCharCode(uint8array[i]);
  78428. if (character == "\n") {
  78429. break;
  78430. }
  78431. line += character;
  78432. }
  78433. return line;
  78434. };
  78435. /**
  78436. * Reads header information from an RGBE texture stored in a native array.
  78437. * More information on this format are available here:
  78438. * https://en.wikipedia.org/wiki/RGBE_image_format
  78439. *
  78440. * @param uint8array The binary file stored in native array.
  78441. * @return The header information.
  78442. */
  78443. HDRTools.RGBE_ReadHeader = function (uint8array) {
  78444. var height = 0;
  78445. var width = 0;
  78446. var line = this.readStringLine(uint8array, 0);
  78447. if (line[0] != '#' || line[1] != '?') {
  78448. throw "Bad HDR Format.";
  78449. }
  78450. var endOfHeader = false;
  78451. var findFormat = false;
  78452. var lineIndex = 0;
  78453. do {
  78454. lineIndex += (line.length + 1);
  78455. line = this.readStringLine(uint8array, lineIndex);
  78456. if (line == "FORMAT=32-bit_rle_rgbe") {
  78457. findFormat = true;
  78458. }
  78459. else if (line.length == 0) {
  78460. endOfHeader = true;
  78461. }
  78462. } while (!endOfHeader);
  78463. if (!findFormat) {
  78464. throw "HDR Bad header format, unsupported FORMAT";
  78465. }
  78466. lineIndex += (line.length + 1);
  78467. line = this.readStringLine(uint8array, lineIndex);
  78468. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  78469. var match = sizeRegexp.exec(line);
  78470. // TODO. Support +Y and -X if needed.
  78471. if (!match || match.length < 3) {
  78472. throw "HDR Bad header format, no size";
  78473. }
  78474. width = parseInt(match[2]);
  78475. height = parseInt(match[1]);
  78476. if (width < 8 || width > 0x7fff) {
  78477. throw "HDR Bad header format, unsupported size";
  78478. }
  78479. lineIndex += (line.length + 1);
  78480. return {
  78481. height: height,
  78482. width: width,
  78483. dataPosition: lineIndex
  78484. };
  78485. };
  78486. /**
  78487. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  78488. * This RGBE texture needs to store the information as a panorama.
  78489. *
  78490. * More information on this format are available here:
  78491. * https://en.wikipedia.org/wiki/RGBE_image_format
  78492. *
  78493. * @param buffer The binary file stored in an array buffer.
  78494. * @param size The expected size of the extracted cubemap.
  78495. * @return The Cube Map information.
  78496. */
  78497. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  78498. var uint8array = new Uint8Array(buffer);
  78499. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  78500. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  78501. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  78502. return cubeMapData;
  78503. };
  78504. /**
  78505. * Returns the pixels data extracted from an RGBE texture.
  78506. * This pixels will be stored left to right up to down in the R G B order in one array.
  78507. *
  78508. * More information on this format are available here:
  78509. * https://en.wikipedia.org/wiki/RGBE_image_format
  78510. *
  78511. * @param uint8array The binary file stored in an array buffer.
  78512. * @param hdrInfo The header information of the file.
  78513. * @return The pixels data in RGB right to left up to down order.
  78514. */
  78515. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  78516. // Keep for multi format supports.
  78517. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  78518. };
  78519. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  78520. var num_scanlines = hdrInfo.height;
  78521. var scanline_width = hdrInfo.width;
  78522. var a, b, c, d, count;
  78523. var dataIndex = hdrInfo.dataPosition;
  78524. var index = 0, endIndex = 0, i = 0;
  78525. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  78526. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  78527. // 3 channels of 4 bytes per pixel in float.
  78528. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  78529. var resultArray = new Float32Array(resultBuffer);
  78530. // read in each successive scanline
  78531. while (num_scanlines > 0) {
  78532. a = uint8array[dataIndex++];
  78533. b = uint8array[dataIndex++];
  78534. c = uint8array[dataIndex++];
  78535. d = uint8array[dataIndex++];
  78536. if (a != 2 || b != 2 || (c & 0x80)) {
  78537. // this file is not run length encoded
  78538. throw "HDR Bad header format, not RLE";
  78539. }
  78540. if (((c << 8) | d) != scanline_width) {
  78541. throw "HDR Bad header format, wrong scan line width";
  78542. }
  78543. index = 0;
  78544. // read each of the four channels for the scanline into the buffer
  78545. for (i = 0; i < 4; i++) {
  78546. endIndex = (i + 1) * scanline_width;
  78547. while (index < endIndex) {
  78548. a = uint8array[dataIndex++];
  78549. b = uint8array[dataIndex++];
  78550. if (a > 128) {
  78551. // a run of the same value
  78552. count = a - 128;
  78553. if ((count == 0) || (count > endIndex - index)) {
  78554. throw "HDR Bad Format, bad scanline data (run)";
  78555. }
  78556. while (count-- > 0) {
  78557. scanLineArray[index++] = b;
  78558. }
  78559. }
  78560. else {
  78561. // a non-run
  78562. count = a;
  78563. if ((count == 0) || (count > endIndex - index)) {
  78564. throw "HDR Bad Format, bad scanline data (non-run)";
  78565. }
  78566. scanLineArray[index++] = b;
  78567. if (--count > 0) {
  78568. for (var j = 0; j < count; j++) {
  78569. scanLineArray[index++] = uint8array[dataIndex++];
  78570. }
  78571. }
  78572. }
  78573. }
  78574. }
  78575. // now convert data from buffer into floats
  78576. for (i = 0; i < scanline_width; i++) {
  78577. a = scanLineArray[i];
  78578. b = scanLineArray[i + scanline_width];
  78579. c = scanLineArray[i + 2 * scanline_width];
  78580. d = scanLineArray[i + 3 * scanline_width];
  78581. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  78582. }
  78583. num_scanlines--;
  78584. }
  78585. return resultArray;
  78586. };
  78587. return HDRTools;
  78588. }());
  78589. BABYLON.HDRTools = HDRTools;
  78590. })(BABYLON || (BABYLON = {}));
  78591. //# sourceMappingURL=babylon.hdr.js.map
  78592. "use strict";
  78593. var BABYLON;
  78594. (function (BABYLON) {
  78595. /**
  78596. * This represents a texture coming from an HDR input.
  78597. *
  78598. * The only supported format is currently panorama picture stored in RGBE format.
  78599. * Example of such files can be found on HDRLib: http://hdrlib.com/
  78600. */
  78601. var HDRCubeTexture = /** @class */ (function (_super) {
  78602. __extends(HDRCubeTexture, _super);
  78603. /**
  78604. * Instantiates an HDRTexture from the following parameters.
  78605. *
  78606. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  78607. * @param scene The scene the texture will be used in
  78608. * @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.
  78609. * @param noMipmap Forces to not generate the mipmap if true
  78610. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  78611. * @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)
  78612. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  78613. */
  78614. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  78615. if (noMipmap === void 0) { noMipmap = false; }
  78616. if (generateHarmonics === void 0) { generateHarmonics = true; }
  78617. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  78618. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  78619. if (onLoad === void 0) { onLoad = null; }
  78620. if (onError === void 0) { onError = null; }
  78621. var _this = _super.call(this, scene) || this;
  78622. _this._useInGammaSpace = false;
  78623. _this._generateHarmonics = true;
  78624. _this._isBABYLONPreprocessed = false;
  78625. _this._onLoad = null;
  78626. _this._onError = null;
  78627. /**
  78628. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  78629. */
  78630. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  78631. /**
  78632. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  78633. * This is usefull at run time to apply the good shader.
  78634. */
  78635. _this.isPMREM = false;
  78636. _this._isBlocking = true;
  78637. _this._rotationY = 0;
  78638. /**
  78639. * Gets or sets the center of the bounding box associated with the cube texture
  78640. * It must define where the camera used to render the texture was set
  78641. */
  78642. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  78643. if (!url) {
  78644. return _this;
  78645. }
  78646. _this.name = url;
  78647. _this.url = url;
  78648. _this.hasAlpha = false;
  78649. _this.isCube = true;
  78650. _this._textureMatrix = BABYLON.Matrix.Identity();
  78651. _this._onLoad = onLoad;
  78652. _this._onError = onError;
  78653. _this.gammaSpace = false;
  78654. var caps = scene.getEngine().getCaps();
  78655. if (size) {
  78656. _this._isBABYLONPreprocessed = false;
  78657. _this._noMipmap = noMipmap;
  78658. _this._size = size;
  78659. _this._useInGammaSpace = useInGammaSpace;
  78660. _this._usePMREMGenerator = usePMREMGenerator &&
  78661. caps.textureLOD &&
  78662. caps.textureFloat &&
  78663. !_this._useInGammaSpace;
  78664. }
  78665. else {
  78666. _this._isBABYLONPreprocessed = true;
  78667. _this._noMipmap = false;
  78668. _this._useInGammaSpace = false;
  78669. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  78670. !_this._useInGammaSpace;
  78671. }
  78672. _this.isPMREM = _this._usePMREMGenerator;
  78673. _this._texture = _this._getFromCache(url, _this._noMipmap);
  78674. if (!_this._texture) {
  78675. if (!scene.useDelayedTextureLoading) {
  78676. _this.loadTexture();
  78677. }
  78678. else {
  78679. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  78680. }
  78681. }
  78682. return _this;
  78683. }
  78684. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  78685. /**
  78686. * Gets wether or not the texture is blocking during loading.
  78687. */
  78688. get: function () {
  78689. return this._isBlocking;
  78690. },
  78691. /**
  78692. * Sets wether or not the texture is blocking during loading.
  78693. */
  78694. set: function (value) {
  78695. this._isBlocking = value;
  78696. },
  78697. enumerable: true,
  78698. configurable: true
  78699. });
  78700. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  78701. /**
  78702. * Gets texture matrix rotation angle around Y axis radians.
  78703. */
  78704. get: function () {
  78705. return this._rotationY;
  78706. },
  78707. /**
  78708. * Sets texture matrix rotation angle around Y axis in radians.
  78709. */
  78710. set: function (value) {
  78711. this._rotationY = value;
  78712. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  78713. },
  78714. enumerable: true,
  78715. configurable: true
  78716. });
  78717. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  78718. get: function () {
  78719. return this._boundingBoxSize;
  78720. },
  78721. /**
  78722. * Gets or sets the size of the bounding box associated with the cube texture
  78723. * When defined, the cubemap will switch to local mode
  78724. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  78725. * @example https://www.babylonjs-playground.com/#RNASML
  78726. */
  78727. set: function (value) {
  78728. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  78729. return;
  78730. }
  78731. this._boundingBoxSize = value;
  78732. var scene = this.getScene();
  78733. if (scene) {
  78734. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  78735. }
  78736. },
  78737. enumerable: true,
  78738. configurable: true
  78739. });
  78740. /**
  78741. * Occurs when the file is a preprocessed .babylon.hdr file.
  78742. */
  78743. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  78744. var _this = this;
  78745. var mipLevels = 0;
  78746. var floatArrayView = null;
  78747. var scene = this.getScene();
  78748. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  78749. var mips = new Array();
  78750. if (!floatArrayView) {
  78751. return mips;
  78752. }
  78753. var startIndex = 30;
  78754. for (var level = 0; level < mipLevels; level++) {
  78755. mips.push([]);
  78756. // Fill each pixel of the mip level.
  78757. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  78758. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  78759. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  78760. mips[level].push(faceData);
  78761. startIndex += faceSize;
  78762. }
  78763. }
  78764. return mips;
  78765. } : null;
  78766. var callback = function (buffer) {
  78767. var scene = _this.getScene();
  78768. if (!scene) {
  78769. return null;
  78770. }
  78771. // Create Native Array Views
  78772. var intArrayView = new Int32Array(buffer);
  78773. floatArrayView = new Float32Array(buffer);
  78774. // Fill header.
  78775. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  78776. _this._size = intArrayView[1]; // CubeMap max mip face size.
  78777. // Update Texture Information.
  78778. if (!_this._texture) {
  78779. return null;
  78780. }
  78781. _this._texture.updateSize(_this._size, _this._size);
  78782. // Fill polynomial information.
  78783. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  78784. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  78785. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  78786. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  78787. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  78788. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  78789. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  78790. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  78791. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  78792. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  78793. _this.sphericalPolynomial = sphericalPolynomial;
  78794. // Fill pixel data.
  78795. mipLevels = intArrayView[29]; // Number of mip levels.
  78796. var startIndex = 30;
  78797. var data = [];
  78798. var faceSize = Math.pow(_this._size, 2) * 3;
  78799. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  78800. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  78801. startIndex += faceSize;
  78802. }
  78803. var results = [];
  78804. var byteArray = null;
  78805. // Push each faces.
  78806. for (var k = 0; k < 6; k++) {
  78807. var dataFace = null;
  78808. // To be deprecated.
  78809. if (version === 1) {
  78810. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  78811. dataFace = data[j];
  78812. }
  78813. // If special cases.
  78814. if (!mipmapGenerator && dataFace) {
  78815. if (!scene.getEngine().getCaps().textureFloat) {
  78816. // 3 channels of 1 bytes per pixel in bytes.
  78817. var byteBuffer = new ArrayBuffer(faceSize);
  78818. byteArray = new Uint8Array(byteBuffer);
  78819. }
  78820. for (var i = 0; i < _this._size * _this._size; i++) {
  78821. // Put in gamma space if requested.
  78822. if (_this._useInGammaSpace) {
  78823. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  78824. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  78825. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  78826. }
  78827. // Convert to int texture for fallback.
  78828. if (byteArray) {
  78829. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  78830. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  78831. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  78832. // May use luminance instead if the result is not accurate.
  78833. var max = Math.max(Math.max(r, g), b);
  78834. if (max > 255) {
  78835. var scale = 255 / max;
  78836. r *= scale;
  78837. g *= scale;
  78838. b *= scale;
  78839. }
  78840. byteArray[(i * 3) + 0] = r;
  78841. byteArray[(i * 3) + 1] = g;
  78842. byteArray[(i * 3) + 2] = b;
  78843. }
  78844. }
  78845. }
  78846. // Fill the array accordingly.
  78847. if (byteArray) {
  78848. results.push(byteArray);
  78849. }
  78850. else {
  78851. results.push(dataFace);
  78852. }
  78853. }
  78854. return results;
  78855. };
  78856. if (scene) {
  78857. 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);
  78858. }
  78859. };
  78860. /**
  78861. * Occurs when the file is raw .hdr file.
  78862. */
  78863. HDRCubeTexture.prototype.loadHDRTexture = function () {
  78864. var _this = this;
  78865. var callback = function (buffer) {
  78866. var scene = _this.getScene();
  78867. if (!scene) {
  78868. return null;
  78869. }
  78870. // Extract the raw linear data.
  78871. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  78872. // Generate harmonics if needed.
  78873. if (_this._generateHarmonics) {
  78874. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  78875. _this.sphericalPolynomial = sphericalPolynomial;
  78876. }
  78877. var results = [];
  78878. var byteArray = null;
  78879. // Push each faces.
  78880. for (var j = 0; j < 6; j++) {
  78881. // Create uintarray fallback.
  78882. if (!scene.getEngine().getCaps().textureFloat) {
  78883. // 3 channels of 1 bytes per pixel in bytes.
  78884. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  78885. byteArray = new Uint8Array(byteBuffer);
  78886. }
  78887. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  78888. // If special cases.
  78889. if (_this._useInGammaSpace || byteArray) {
  78890. for (var i = 0; i < _this._size * _this._size; i++) {
  78891. // Put in gamma space if requested.
  78892. if (_this._useInGammaSpace) {
  78893. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  78894. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  78895. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  78896. }
  78897. // Convert to int texture for fallback.
  78898. if (byteArray) {
  78899. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  78900. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  78901. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  78902. // May use luminance instead if the result is not accurate.
  78903. var max = Math.max(Math.max(r, g), b);
  78904. if (max > 255) {
  78905. var scale = 255 / max;
  78906. r *= scale;
  78907. g *= scale;
  78908. b *= scale;
  78909. }
  78910. byteArray[(i * 3) + 0] = r;
  78911. byteArray[(i * 3) + 1] = g;
  78912. byteArray[(i * 3) + 2] = b;
  78913. }
  78914. }
  78915. }
  78916. if (byteArray) {
  78917. results.push(byteArray);
  78918. }
  78919. else {
  78920. results.push(dataFace);
  78921. }
  78922. }
  78923. return results;
  78924. };
  78925. var mipmapGenerator = null;
  78926. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  78927. // if (!this._noMipmap &&
  78928. // this._usePMREMGenerator) {
  78929. // mipmapGenerator = (data: ArrayBufferView[]) => {
  78930. // // Custom setup of the generator matching with the PBR shader values.
  78931. // var generator = new BABYLON.PMREMGenerator(data,
  78932. // this._size,
  78933. // this._size,
  78934. // 0,
  78935. // 3,
  78936. // this.getScene().getEngine().getCaps().textureFloat,
  78937. // 2048,
  78938. // 0.25,
  78939. // false,
  78940. // true);
  78941. // return generator.filterCubeMap();
  78942. // };
  78943. // }
  78944. var scene = this.getScene();
  78945. if (scene) {
  78946. 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);
  78947. }
  78948. };
  78949. /**
  78950. * Starts the loading process of the texture.
  78951. */
  78952. HDRCubeTexture.prototype.loadTexture = function () {
  78953. if (this._isBABYLONPreprocessed) {
  78954. this.loadBabylonTexture();
  78955. }
  78956. else {
  78957. this.loadHDRTexture();
  78958. }
  78959. };
  78960. HDRCubeTexture.prototype.clone = function () {
  78961. var scene = this.getScene();
  78962. if (!scene) {
  78963. return this;
  78964. }
  78965. var size = (this._isBABYLONPreprocessed ? null : this._size);
  78966. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  78967. // Base texture
  78968. newTexture.level = this.level;
  78969. newTexture.wrapU = this.wrapU;
  78970. newTexture.wrapV = this.wrapV;
  78971. newTexture.coordinatesIndex = this.coordinatesIndex;
  78972. newTexture.coordinatesMode = this.coordinatesMode;
  78973. return newTexture;
  78974. };
  78975. // Methods
  78976. HDRCubeTexture.prototype.delayLoad = function () {
  78977. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  78978. return;
  78979. }
  78980. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  78981. this._texture = this._getFromCache(this.url, this._noMipmap);
  78982. if (!this._texture) {
  78983. this.loadTexture();
  78984. }
  78985. };
  78986. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  78987. return this._textureMatrix;
  78988. };
  78989. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  78990. this._textureMatrix = value;
  78991. };
  78992. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  78993. var texture = null;
  78994. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  78995. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  78996. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  78997. texture.name = parsedTexture.name;
  78998. texture.hasAlpha = parsedTexture.hasAlpha;
  78999. texture.level = parsedTexture.level;
  79000. texture.coordinatesMode = parsedTexture.coordinatesMode;
  79001. texture.isBlocking = parsedTexture.isBlocking;
  79002. }
  79003. if (texture) {
  79004. if (parsedTexture.boundingBoxPosition) {
  79005. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  79006. }
  79007. if (parsedTexture.boundingBoxSize) {
  79008. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  79009. }
  79010. if (parsedTexture.rotationY) {
  79011. texture.rotationY = parsedTexture.rotationY;
  79012. }
  79013. }
  79014. return texture;
  79015. };
  79016. HDRCubeTexture.prototype.serialize = function () {
  79017. if (!this.name) {
  79018. return null;
  79019. }
  79020. var serializationObject = {};
  79021. serializationObject.name = this.name;
  79022. serializationObject.hasAlpha = this.hasAlpha;
  79023. serializationObject.isCube = true;
  79024. serializationObject.level = this.level;
  79025. serializationObject.size = this._size;
  79026. serializationObject.coordinatesMode = this.coordinatesMode;
  79027. serializationObject.useInGammaSpace = this._useInGammaSpace;
  79028. serializationObject.generateHarmonics = this._generateHarmonics;
  79029. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  79030. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  79031. serializationObject.customType = "BABYLON.HDRCubeTexture";
  79032. serializationObject.noMipmap = this._noMipmap;
  79033. serializationObject.isBlocking = this._isBlocking;
  79034. serializationObject.rotationY = this._rotationY;
  79035. return serializationObject;
  79036. };
  79037. /**
  79038. * Saves as a file the data contained in the texture in a binary format.
  79039. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  79040. * as the spherical used in the lighting.
  79041. * @param url The HDR file url.
  79042. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  79043. * @param onError Method called if any error happens during download.
  79044. * @return The packed binary data.
  79045. */
  79046. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  79047. if (onError === void 0) { onError = null; }
  79048. var callback = function (buffer) {
  79049. var data = new Blob([buffer], { type: 'application/octet-stream' });
  79050. // Returns a URL you can use as a href.
  79051. var objUrl = window.URL.createObjectURL(data);
  79052. // Simulates a link to it and click to dowload.
  79053. var a = document.createElement("a");
  79054. document.body.appendChild(a);
  79055. a.style.display = "none";
  79056. a.href = objUrl;
  79057. a.download = "envmap.babylon.hdr";
  79058. a.click();
  79059. };
  79060. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  79061. };
  79062. /**
  79063. * Serializes the data contained in the texture in a binary format.
  79064. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  79065. * as the spherical used in the lighting.
  79066. * @param url The HDR file url.
  79067. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  79068. * @param onError Method called if any error happens during download.
  79069. * @return The packed binary data.
  79070. */
  79071. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  79072. if (onError === void 0) { onError = null; }
  79073. // Needs the url tho create the texture.
  79074. if (!url) {
  79075. return;
  79076. }
  79077. // Check Power of two size.
  79078. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  79079. return;
  79080. }
  79081. // Coming Back in 3.x.
  79082. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  79083. };
  79084. HDRCubeTexture._facesMapping = [
  79085. "right",
  79086. "left",
  79087. "up",
  79088. "down",
  79089. "front",
  79090. "back"
  79091. ];
  79092. return HDRCubeTexture;
  79093. }(BABYLON.BaseTexture));
  79094. BABYLON.HDRCubeTexture = HDRCubeTexture;
  79095. })(BABYLON || (BABYLON = {}));
  79096. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  79097. "use strict";
  79098. var BABYLON;
  79099. (function (BABYLON) {
  79100. var IndexedVector2 = /** @class */ (function (_super) {
  79101. __extends(IndexedVector2, _super);
  79102. function IndexedVector2(original, index) {
  79103. var _this = _super.call(this, original.x, original.y) || this;
  79104. _this.index = index;
  79105. return _this;
  79106. }
  79107. return IndexedVector2;
  79108. }(BABYLON.Vector2));
  79109. var PolygonPoints = /** @class */ (function () {
  79110. function PolygonPoints() {
  79111. this.elements = new Array();
  79112. }
  79113. PolygonPoints.prototype.add = function (originalPoints) {
  79114. var _this = this;
  79115. var result = new Array();
  79116. originalPoints.forEach(function (point) {
  79117. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  79118. var newPoint = new IndexedVector2(point, _this.elements.length);
  79119. result.push(newPoint);
  79120. _this.elements.push(newPoint);
  79121. }
  79122. });
  79123. return result;
  79124. };
  79125. PolygonPoints.prototype.computeBounds = function () {
  79126. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  79127. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  79128. this.elements.forEach(function (point) {
  79129. // x
  79130. if (point.x < lmin.x) {
  79131. lmin.x = point.x;
  79132. }
  79133. else if (point.x > lmax.x) {
  79134. lmax.x = point.x;
  79135. }
  79136. // y
  79137. if (point.y < lmin.y) {
  79138. lmin.y = point.y;
  79139. }
  79140. else if (point.y > lmax.y) {
  79141. lmax.y = point.y;
  79142. }
  79143. });
  79144. return {
  79145. min: lmin,
  79146. max: lmax,
  79147. width: lmax.x - lmin.x,
  79148. height: lmax.y - lmin.y
  79149. };
  79150. };
  79151. return PolygonPoints;
  79152. }());
  79153. var Polygon = /** @class */ (function () {
  79154. function Polygon() {
  79155. }
  79156. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  79157. return [
  79158. new BABYLON.Vector2(xmin, ymin),
  79159. new BABYLON.Vector2(xmax, ymin),
  79160. new BABYLON.Vector2(xmax, ymax),
  79161. new BABYLON.Vector2(xmin, ymax)
  79162. ];
  79163. };
  79164. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  79165. if (cx === void 0) { cx = 0; }
  79166. if (cy === void 0) { cy = 0; }
  79167. if (numberOfSides === void 0) { numberOfSides = 32; }
  79168. var result = new Array();
  79169. var angle = 0;
  79170. var increment = (Math.PI * 2) / numberOfSides;
  79171. for (var i = 0; i < numberOfSides; i++) {
  79172. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  79173. angle -= increment;
  79174. }
  79175. return result;
  79176. };
  79177. Polygon.Parse = function (input) {
  79178. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  79179. var i, result = [];
  79180. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  79181. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  79182. }
  79183. return result;
  79184. };
  79185. Polygon.StartingAt = function (x, y) {
  79186. return BABYLON.Path2.StartingAt(x, y);
  79187. };
  79188. return Polygon;
  79189. }());
  79190. BABYLON.Polygon = Polygon;
  79191. var PolygonMeshBuilder = /** @class */ (function () {
  79192. function PolygonMeshBuilder(name, contours, scene) {
  79193. this._points = new PolygonPoints();
  79194. this._outlinepoints = new PolygonPoints();
  79195. this._holes = new Array();
  79196. this._epoints = new Array();
  79197. this._eholes = new Array();
  79198. this._name = name;
  79199. this._scene = scene;
  79200. var points;
  79201. if (contours instanceof BABYLON.Path2) {
  79202. points = contours.getPoints();
  79203. }
  79204. else {
  79205. points = contours;
  79206. }
  79207. this._addToepoint(points);
  79208. this._points.add(points);
  79209. this._outlinepoints.add(points);
  79210. if (typeof earcut === 'undefined') {
  79211. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  79212. }
  79213. }
  79214. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  79215. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  79216. var p = points_1[_i];
  79217. this._epoints.push(p.x, p.y);
  79218. }
  79219. };
  79220. PolygonMeshBuilder.prototype.addHole = function (hole) {
  79221. this._points.add(hole);
  79222. var holepoints = new PolygonPoints();
  79223. holepoints.add(hole);
  79224. this._holes.push(holepoints);
  79225. this._eholes.push(this._epoints.length / 2);
  79226. this._addToepoint(hole);
  79227. return this;
  79228. };
  79229. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  79230. var _this = this;
  79231. if (updatable === void 0) { updatable = false; }
  79232. if (depth === void 0) { depth = 0; }
  79233. var result = new BABYLON.Mesh(this._name, this._scene);
  79234. var normals = new Array();
  79235. var positions = new Array();
  79236. var uvs = new Array();
  79237. var bounds = this._points.computeBounds();
  79238. this._points.elements.forEach(function (p) {
  79239. normals.push(0, 1.0, 0);
  79240. positions.push(p.x, 0, p.y);
  79241. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  79242. });
  79243. var indices = new Array();
  79244. var res = earcut(this._epoints, this._eholes, 2);
  79245. for (var i = 0; i < res.length; i++) {
  79246. indices.push(res[i]);
  79247. }
  79248. if (depth > 0) {
  79249. var positionscount = (positions.length / 3); //get the current pointcount
  79250. this._points.elements.forEach(function (p) {
  79251. normals.push(0, -1.0, 0);
  79252. positions.push(p.x, -depth, p.y);
  79253. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  79254. });
  79255. var totalCount = indices.length;
  79256. for (var i = 0; i < totalCount; i += 3) {
  79257. var i0 = indices[i + 0];
  79258. var i1 = indices[i + 1];
  79259. var i2 = indices[i + 2];
  79260. indices.push(i2 + positionscount);
  79261. indices.push(i1 + positionscount);
  79262. indices.push(i0 + positionscount);
  79263. }
  79264. //Add the sides
  79265. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  79266. this._holes.forEach(function (hole) {
  79267. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  79268. });
  79269. }
  79270. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  79271. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  79272. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  79273. result.setIndices(indices);
  79274. return result;
  79275. };
  79276. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  79277. var StartIndex = positions.length / 3;
  79278. var ulength = 0;
  79279. for (var i = 0; i < points.elements.length; i++) {
  79280. var p = points.elements[i];
  79281. var p1;
  79282. if ((i + 1) > points.elements.length - 1) {
  79283. p1 = points.elements[0];
  79284. }
  79285. else {
  79286. p1 = points.elements[i + 1];
  79287. }
  79288. positions.push(p.x, 0, p.y);
  79289. positions.push(p.x, -depth, p.y);
  79290. positions.push(p1.x, 0, p1.y);
  79291. positions.push(p1.x, -depth, p1.y);
  79292. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  79293. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  79294. var v3 = v2.subtract(v1);
  79295. var v4 = new BABYLON.Vector3(0, 1, 0);
  79296. var vn = BABYLON.Vector3.Cross(v3, v4);
  79297. vn = vn.normalize();
  79298. uvs.push(ulength / bounds.width, 0);
  79299. uvs.push(ulength / bounds.width, 1);
  79300. ulength += v3.length();
  79301. uvs.push((ulength / bounds.width), 0);
  79302. uvs.push((ulength / bounds.width), 1);
  79303. if (!flip) {
  79304. normals.push(-vn.x, -vn.y, -vn.z);
  79305. normals.push(-vn.x, -vn.y, -vn.z);
  79306. normals.push(-vn.x, -vn.y, -vn.z);
  79307. normals.push(-vn.x, -vn.y, -vn.z);
  79308. indices.push(StartIndex);
  79309. indices.push(StartIndex + 1);
  79310. indices.push(StartIndex + 2);
  79311. indices.push(StartIndex + 1);
  79312. indices.push(StartIndex + 3);
  79313. indices.push(StartIndex + 2);
  79314. }
  79315. else {
  79316. normals.push(vn.x, vn.y, vn.z);
  79317. normals.push(vn.x, vn.y, vn.z);
  79318. normals.push(vn.x, vn.y, vn.z);
  79319. normals.push(vn.x, vn.y, vn.z);
  79320. indices.push(StartIndex);
  79321. indices.push(StartIndex + 2);
  79322. indices.push(StartIndex + 1);
  79323. indices.push(StartIndex + 1);
  79324. indices.push(StartIndex + 2);
  79325. indices.push(StartIndex + 3);
  79326. }
  79327. StartIndex += 4;
  79328. }
  79329. ;
  79330. };
  79331. return PolygonMeshBuilder;
  79332. }());
  79333. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  79334. })(BABYLON || (BABYLON = {}));
  79335. //# sourceMappingURL=babylon.polygonMesh.js.map
  79336. "use strict";
  79337. var BABYLON;
  79338. (function (BABYLON) {
  79339. // Unique ID when we import meshes from Babylon to CSG
  79340. var currentCSGMeshId = 0;
  79341. // # class Vertex
  79342. // Represents a vertex of a polygon. Use your own vertex class instead of this
  79343. // one to provide additional features like texture coordinates and vertex
  79344. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  79345. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  79346. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  79347. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  79348. // is not used anywhere else.
  79349. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  79350. var Vertex = /** @class */ (function () {
  79351. function Vertex(pos, normal, uv) {
  79352. this.pos = pos;
  79353. this.normal = normal;
  79354. this.uv = uv;
  79355. }
  79356. Vertex.prototype.clone = function () {
  79357. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  79358. };
  79359. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  79360. // orientation of a polygon is flipped.
  79361. Vertex.prototype.flip = function () {
  79362. this.normal = this.normal.scale(-1);
  79363. };
  79364. // Create a new vertex between this vertex and `other` by linearly
  79365. // interpolating all properties using a parameter of `t`. Subclasses should
  79366. // override this to interpolate additional properties.
  79367. Vertex.prototype.interpolate = function (other, t) {
  79368. 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));
  79369. };
  79370. return Vertex;
  79371. }());
  79372. // # class Plane
  79373. // Represents a plane in 3D space.
  79374. var Plane = /** @class */ (function () {
  79375. function Plane(normal, w) {
  79376. this.normal = normal;
  79377. this.w = w;
  79378. }
  79379. Plane.FromPoints = function (a, b, c) {
  79380. var v0 = c.subtract(a);
  79381. var v1 = b.subtract(a);
  79382. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  79383. return null;
  79384. }
  79385. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  79386. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  79387. };
  79388. Plane.prototype.clone = function () {
  79389. return new Plane(this.normal.clone(), this.w);
  79390. };
  79391. Plane.prototype.flip = function () {
  79392. this.normal.scaleInPlace(-1);
  79393. this.w = -this.w;
  79394. };
  79395. // Split `polygon` by this plane if needed, then put the polygon or polygon
  79396. // fragments in the appropriate lists. Coplanar polygons go into either
  79397. // `coplanarFront` or `coplanarBack` depending on their orientation with
  79398. // respect to this plane. Polygons in front or in back of this plane go into
  79399. // either `front` or `back`.
  79400. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  79401. var COPLANAR = 0;
  79402. var FRONT = 1;
  79403. var BACK = 2;
  79404. var SPANNING = 3;
  79405. // Classify each point as well as the entire polygon into one of the above
  79406. // four classes.
  79407. var polygonType = 0;
  79408. var types = [];
  79409. var i;
  79410. var t;
  79411. for (i = 0; i < polygon.vertices.length; i++) {
  79412. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  79413. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  79414. polygonType |= type;
  79415. types.push(type);
  79416. }
  79417. // Put the polygon in the correct list, splitting it when necessary.
  79418. switch (polygonType) {
  79419. case COPLANAR:
  79420. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  79421. break;
  79422. case FRONT:
  79423. front.push(polygon);
  79424. break;
  79425. case BACK:
  79426. back.push(polygon);
  79427. break;
  79428. case SPANNING:
  79429. var f = [], b = [];
  79430. for (i = 0; i < polygon.vertices.length; i++) {
  79431. var j = (i + 1) % polygon.vertices.length;
  79432. var ti = types[i], tj = types[j];
  79433. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  79434. if (ti !== BACK)
  79435. f.push(vi);
  79436. if (ti !== FRONT)
  79437. b.push(ti !== BACK ? vi.clone() : vi);
  79438. if ((ti | tj) === SPANNING) {
  79439. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  79440. var v = vi.interpolate(vj, t);
  79441. f.push(v);
  79442. b.push(v.clone());
  79443. }
  79444. }
  79445. var poly;
  79446. if (f.length >= 3) {
  79447. poly = new Polygon(f, polygon.shared);
  79448. if (poly.plane)
  79449. front.push(poly);
  79450. }
  79451. if (b.length >= 3) {
  79452. poly = new Polygon(b, polygon.shared);
  79453. if (poly.plane)
  79454. back.push(poly);
  79455. }
  79456. break;
  79457. }
  79458. };
  79459. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  79460. // point is on the plane.
  79461. Plane.EPSILON = 1e-5;
  79462. return Plane;
  79463. }());
  79464. // # class Polygon
  79465. // Represents a convex polygon. The vertices used to initialize a polygon must
  79466. // be coplanar and form a convex loop.
  79467. //
  79468. // Each convex polygon has a `shared` property, which is shared between all
  79469. // polygons that are clones of each other or were split from the same polygon.
  79470. // This can be used to define per-polygon properties (such as surface color).
  79471. var Polygon = /** @class */ (function () {
  79472. function Polygon(vertices, shared) {
  79473. this.vertices = vertices;
  79474. this.shared = shared;
  79475. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  79476. }
  79477. Polygon.prototype.clone = function () {
  79478. var vertices = this.vertices.map(function (v) { return v.clone(); });
  79479. return new Polygon(vertices, this.shared);
  79480. };
  79481. Polygon.prototype.flip = function () {
  79482. this.vertices.reverse().map(function (v) { v.flip(); });
  79483. this.plane.flip();
  79484. };
  79485. return Polygon;
  79486. }());
  79487. // # class Node
  79488. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  79489. // by picking a polygon to split along. That polygon (and all other coplanar
  79490. // polygons) are added directly to that node and the other polygons are added to
  79491. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  79492. // no distinction between internal and leaf nodes.
  79493. var Node = /** @class */ (function () {
  79494. function Node(polygons) {
  79495. this.plane = null;
  79496. this.front = null;
  79497. this.back = null;
  79498. this.polygons = new Array();
  79499. if (polygons) {
  79500. this.build(polygons);
  79501. }
  79502. }
  79503. Node.prototype.clone = function () {
  79504. var node = new Node();
  79505. node.plane = this.plane && this.plane.clone();
  79506. node.front = this.front && this.front.clone();
  79507. node.back = this.back && this.back.clone();
  79508. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  79509. return node;
  79510. };
  79511. // Convert solid space to empty space and empty space to solid space.
  79512. Node.prototype.invert = function () {
  79513. for (var i = 0; i < this.polygons.length; i++) {
  79514. this.polygons[i].flip();
  79515. }
  79516. if (this.plane) {
  79517. this.plane.flip();
  79518. }
  79519. if (this.front) {
  79520. this.front.invert();
  79521. }
  79522. if (this.back) {
  79523. this.back.invert();
  79524. }
  79525. var temp = this.front;
  79526. this.front = this.back;
  79527. this.back = temp;
  79528. };
  79529. // Recursively remove all polygons in `polygons` that are inside this BSP
  79530. // tree.
  79531. Node.prototype.clipPolygons = function (polygons) {
  79532. if (!this.plane)
  79533. return polygons.slice();
  79534. var front = new Array(), back = new Array();
  79535. for (var i = 0; i < polygons.length; i++) {
  79536. this.plane.splitPolygon(polygons[i], front, back, front, back);
  79537. }
  79538. if (this.front) {
  79539. front = this.front.clipPolygons(front);
  79540. }
  79541. if (this.back) {
  79542. back = this.back.clipPolygons(back);
  79543. }
  79544. else {
  79545. back = [];
  79546. }
  79547. return front.concat(back);
  79548. };
  79549. // Remove all polygons in this BSP tree that are inside the other BSP tree
  79550. // `bsp`.
  79551. Node.prototype.clipTo = function (bsp) {
  79552. this.polygons = bsp.clipPolygons(this.polygons);
  79553. if (this.front)
  79554. this.front.clipTo(bsp);
  79555. if (this.back)
  79556. this.back.clipTo(bsp);
  79557. };
  79558. // Return a list of all polygons in this BSP tree.
  79559. Node.prototype.allPolygons = function () {
  79560. var polygons = this.polygons.slice();
  79561. if (this.front)
  79562. polygons = polygons.concat(this.front.allPolygons());
  79563. if (this.back)
  79564. polygons = polygons.concat(this.back.allPolygons());
  79565. return polygons;
  79566. };
  79567. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  79568. // new polygons are filtered down to the bottom of the tree and become new
  79569. // nodes there. Each set of polygons is partitioned using the first polygon
  79570. // (no heuristic is used to pick a good split).
  79571. Node.prototype.build = function (polygons) {
  79572. if (!polygons.length)
  79573. return;
  79574. if (!this.plane)
  79575. this.plane = polygons[0].plane.clone();
  79576. var front = new Array(), back = new Array();
  79577. for (var i = 0; i < polygons.length; i++) {
  79578. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  79579. }
  79580. if (front.length) {
  79581. if (!this.front)
  79582. this.front = new Node();
  79583. this.front.build(front);
  79584. }
  79585. if (back.length) {
  79586. if (!this.back)
  79587. this.back = new Node();
  79588. this.back.build(back);
  79589. }
  79590. };
  79591. return Node;
  79592. }());
  79593. var CSG = /** @class */ (function () {
  79594. function CSG() {
  79595. this.polygons = new Array();
  79596. }
  79597. // Convert BABYLON.Mesh to BABYLON.CSG
  79598. CSG.FromMesh = function (mesh) {
  79599. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  79600. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  79601. if (mesh instanceof BABYLON.Mesh) {
  79602. mesh.computeWorldMatrix(true);
  79603. matrix = mesh.getWorldMatrix();
  79604. meshPosition = mesh.position.clone();
  79605. meshRotation = mesh.rotation.clone();
  79606. if (mesh.rotationQuaternion) {
  79607. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  79608. }
  79609. meshScaling = mesh.scaling.clone();
  79610. }
  79611. else {
  79612. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  79613. }
  79614. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  79615. var subMeshes = mesh.subMeshes;
  79616. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  79617. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  79618. vertices = [];
  79619. for (var j = 0; j < 3; j++) {
  79620. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  79621. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  79622. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  79623. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  79624. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  79625. vertex = new Vertex(position, normal, uv);
  79626. vertices.push(vertex);
  79627. }
  79628. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  79629. // To handle the case of degenerated triangle
  79630. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  79631. if (polygon.plane)
  79632. polygons.push(polygon);
  79633. }
  79634. }
  79635. var csg = CSG.FromPolygons(polygons);
  79636. csg.matrix = matrix;
  79637. csg.position = meshPosition;
  79638. csg.rotation = meshRotation;
  79639. csg.scaling = meshScaling;
  79640. csg.rotationQuaternion = meshRotationQuaternion;
  79641. currentCSGMeshId++;
  79642. return csg;
  79643. };
  79644. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  79645. CSG.FromPolygons = function (polygons) {
  79646. var csg = new CSG();
  79647. csg.polygons = polygons;
  79648. return csg;
  79649. };
  79650. CSG.prototype.clone = function () {
  79651. var csg = new CSG();
  79652. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  79653. csg.copyTransformAttributes(this);
  79654. return csg;
  79655. };
  79656. CSG.prototype.union = function (csg) {
  79657. var a = new Node(this.clone().polygons);
  79658. var b = new Node(csg.clone().polygons);
  79659. a.clipTo(b);
  79660. b.clipTo(a);
  79661. b.invert();
  79662. b.clipTo(a);
  79663. b.invert();
  79664. a.build(b.allPolygons());
  79665. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  79666. };
  79667. CSG.prototype.unionInPlace = function (csg) {
  79668. var a = new Node(this.polygons);
  79669. var b = new Node(csg.polygons);
  79670. a.clipTo(b);
  79671. b.clipTo(a);
  79672. b.invert();
  79673. b.clipTo(a);
  79674. b.invert();
  79675. a.build(b.allPolygons());
  79676. this.polygons = a.allPolygons();
  79677. };
  79678. CSG.prototype.subtract = function (csg) {
  79679. var a = new Node(this.clone().polygons);
  79680. var b = new Node(csg.clone().polygons);
  79681. a.invert();
  79682. a.clipTo(b);
  79683. b.clipTo(a);
  79684. b.invert();
  79685. b.clipTo(a);
  79686. b.invert();
  79687. a.build(b.allPolygons());
  79688. a.invert();
  79689. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  79690. };
  79691. CSG.prototype.subtractInPlace = function (csg) {
  79692. var a = new Node(this.polygons);
  79693. var b = new Node(csg.polygons);
  79694. a.invert();
  79695. a.clipTo(b);
  79696. b.clipTo(a);
  79697. b.invert();
  79698. b.clipTo(a);
  79699. b.invert();
  79700. a.build(b.allPolygons());
  79701. a.invert();
  79702. this.polygons = a.allPolygons();
  79703. };
  79704. CSG.prototype.intersect = function (csg) {
  79705. var a = new Node(this.clone().polygons);
  79706. var b = new Node(csg.clone().polygons);
  79707. a.invert();
  79708. b.clipTo(a);
  79709. b.invert();
  79710. a.clipTo(b);
  79711. b.clipTo(a);
  79712. a.build(b.allPolygons());
  79713. a.invert();
  79714. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  79715. };
  79716. CSG.prototype.intersectInPlace = function (csg) {
  79717. var a = new Node(this.polygons);
  79718. var b = new Node(csg.polygons);
  79719. a.invert();
  79720. b.clipTo(a);
  79721. b.invert();
  79722. a.clipTo(b);
  79723. b.clipTo(a);
  79724. a.build(b.allPolygons());
  79725. a.invert();
  79726. this.polygons = a.allPolygons();
  79727. };
  79728. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  79729. // not modified.
  79730. CSG.prototype.inverse = function () {
  79731. var csg = this.clone();
  79732. csg.inverseInPlace();
  79733. return csg;
  79734. };
  79735. CSG.prototype.inverseInPlace = function () {
  79736. this.polygons.map(function (p) { p.flip(); });
  79737. };
  79738. // This is used to keep meshes transformations so they can be restored
  79739. // when we build back a Babylon Mesh
  79740. // NB : All CSG operations are performed in world coordinates
  79741. CSG.prototype.copyTransformAttributes = function (csg) {
  79742. this.matrix = csg.matrix;
  79743. this.position = csg.position;
  79744. this.rotation = csg.rotation;
  79745. this.scaling = csg.scaling;
  79746. this.rotationQuaternion = csg.rotationQuaternion;
  79747. return this;
  79748. };
  79749. // Build Raw mesh from CSG
  79750. // Coordinates here are in world space
  79751. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  79752. var matrix = this.matrix.clone();
  79753. matrix.invert();
  79754. 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;
  79755. if (keepSubMeshes) {
  79756. // Sort Polygons, since subMeshes are indices range
  79757. polygons.sort(function (a, b) {
  79758. if (a.shared.meshId === b.shared.meshId) {
  79759. return a.shared.subMeshId - b.shared.subMeshId;
  79760. }
  79761. else {
  79762. return a.shared.meshId - b.shared.meshId;
  79763. }
  79764. });
  79765. }
  79766. for (var i = 0, il = polygons.length; i < il; i++) {
  79767. polygon = polygons[i];
  79768. // Building SubMeshes
  79769. if (!subMesh_dict[polygon.shared.meshId]) {
  79770. subMesh_dict[polygon.shared.meshId] = {};
  79771. }
  79772. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  79773. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  79774. indexStart: +Infinity,
  79775. indexEnd: -Infinity,
  79776. materialIndex: polygon.shared.materialIndex
  79777. };
  79778. }
  79779. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  79780. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  79781. polygonIndices[0] = 0;
  79782. polygonIndices[1] = j - 1;
  79783. polygonIndices[2] = j;
  79784. for (var k = 0; k < 3; k++) {
  79785. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  79786. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  79787. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  79788. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  79789. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  79790. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  79791. // Check if 2 points can be merged
  79792. if (!(typeof vertex_idx !== 'undefined' &&
  79793. normals[vertex_idx * 3] === localNormal.x &&
  79794. normals[vertex_idx * 3 + 1] === localNormal.y &&
  79795. normals[vertex_idx * 3 + 2] === localNormal.z &&
  79796. uvs[vertex_idx * 2] === uv.x &&
  79797. uvs[vertex_idx * 2 + 1] === uv.y)) {
  79798. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  79799. uvs.push(uv.x, uv.y);
  79800. normals.push(normal.x, normal.y, normal.z);
  79801. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  79802. }
  79803. indices.push(vertex_idx);
  79804. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  79805. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  79806. currentIndex++;
  79807. }
  79808. }
  79809. }
  79810. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  79811. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  79812. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  79813. mesh.setIndices(indices, null);
  79814. if (keepSubMeshes) {
  79815. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  79816. var materialIndexOffset = 0, materialMaxIndex;
  79817. mesh.subMeshes = new Array();
  79818. for (var m in subMesh_dict) {
  79819. materialMaxIndex = -1;
  79820. for (var sm in subMesh_dict[m]) {
  79821. subMesh_obj = subMesh_dict[m][sm];
  79822. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  79823. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  79824. }
  79825. materialIndexOffset += ++materialMaxIndex;
  79826. }
  79827. }
  79828. return mesh;
  79829. };
  79830. // Build Mesh from CSG taking material and transforms into account
  79831. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  79832. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  79833. mesh.material = material;
  79834. mesh.position.copyFrom(this.position);
  79835. mesh.rotation.copyFrom(this.rotation);
  79836. if (this.rotationQuaternion) {
  79837. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  79838. }
  79839. mesh.scaling.copyFrom(this.scaling);
  79840. mesh.computeWorldMatrix(true);
  79841. return mesh;
  79842. };
  79843. return CSG;
  79844. }());
  79845. BABYLON.CSG = CSG;
  79846. })(BABYLON || (BABYLON = {}));
  79847. //# sourceMappingURL=babylon.csg.js.map
  79848. "use strict";
  79849. var BABYLON;
  79850. (function (BABYLON) {
  79851. var LensFlare = /** @class */ (function () {
  79852. function LensFlare(size, position, color, imgUrl, system) {
  79853. this.size = size;
  79854. this.position = position;
  79855. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  79856. this.color = color || new BABYLON.Color3(1, 1, 1);
  79857. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  79858. this._system = system;
  79859. system.lensFlares.push(this);
  79860. }
  79861. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  79862. return new LensFlare(size, position, color, imgUrl, system);
  79863. };
  79864. LensFlare.prototype.dispose = function () {
  79865. if (this.texture) {
  79866. this.texture.dispose();
  79867. }
  79868. // Remove from scene
  79869. var index = this._system.lensFlares.indexOf(this);
  79870. this._system.lensFlares.splice(index, 1);
  79871. };
  79872. ;
  79873. return LensFlare;
  79874. }());
  79875. BABYLON.LensFlare = LensFlare;
  79876. })(BABYLON || (BABYLON = {}));
  79877. //# sourceMappingURL=babylon.lensFlare.js.map
  79878. "use strict";
  79879. var BABYLON;
  79880. (function (BABYLON) {
  79881. var LensFlareSystem = /** @class */ (function () {
  79882. function LensFlareSystem(name, emitter, scene) {
  79883. this.name = name;
  79884. this.lensFlares = new Array();
  79885. this.borderLimit = 300;
  79886. this.viewportBorder = 0;
  79887. this.layerMask = 0x0FFFFFFF;
  79888. this._vertexBuffers = {};
  79889. this._isEnabled = true;
  79890. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79891. this._emitter = emitter;
  79892. this.id = name;
  79893. scene.lensFlareSystems.push(this);
  79894. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  79895. var engine = scene.getEngine();
  79896. // VBO
  79897. var vertices = [];
  79898. vertices.push(1, 1);
  79899. vertices.push(-1, 1);
  79900. vertices.push(-1, -1);
  79901. vertices.push(1, -1);
  79902. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  79903. // Indices
  79904. var indices = [];
  79905. indices.push(0);
  79906. indices.push(1);
  79907. indices.push(2);
  79908. indices.push(0);
  79909. indices.push(2);
  79910. indices.push(3);
  79911. this._indexBuffer = engine.createIndexBuffer(indices);
  79912. // Effects
  79913. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  79914. }
  79915. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  79916. get: function () {
  79917. return this._isEnabled;
  79918. },
  79919. set: function (value) {
  79920. this._isEnabled = value;
  79921. },
  79922. enumerable: true,
  79923. configurable: true
  79924. });
  79925. LensFlareSystem.prototype.getScene = function () {
  79926. return this._scene;
  79927. };
  79928. LensFlareSystem.prototype.getEmitter = function () {
  79929. return this._emitter;
  79930. };
  79931. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  79932. this._emitter = newEmitter;
  79933. };
  79934. LensFlareSystem.prototype.getEmitterPosition = function () {
  79935. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  79936. };
  79937. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  79938. var position = this.getEmitterPosition();
  79939. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  79940. this._positionX = position.x;
  79941. this._positionY = position.y;
  79942. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  79943. if (this.viewportBorder > 0) {
  79944. globalViewport.x -= this.viewportBorder;
  79945. globalViewport.y -= this.viewportBorder;
  79946. globalViewport.width += this.viewportBorder * 2;
  79947. globalViewport.height += this.viewportBorder * 2;
  79948. position.x += this.viewportBorder;
  79949. position.y += this.viewportBorder;
  79950. this._positionX += this.viewportBorder;
  79951. this._positionY += this.viewportBorder;
  79952. }
  79953. if (position.z > 0) {
  79954. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  79955. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  79956. return true;
  79957. }
  79958. return true;
  79959. }
  79960. return false;
  79961. };
  79962. LensFlareSystem.prototype._isVisible = function () {
  79963. if (!this._isEnabled || !this._scene.activeCamera) {
  79964. return false;
  79965. }
  79966. var emitterPosition = this.getEmitterPosition();
  79967. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  79968. var distance = direction.length();
  79969. direction.normalize();
  79970. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  79971. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  79972. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  79973. };
  79974. LensFlareSystem.prototype.render = function () {
  79975. if (!this._effect.isReady() || !this._scene.activeCamera)
  79976. return false;
  79977. var engine = this._scene.getEngine();
  79978. var viewport = this._scene.activeCamera.viewport;
  79979. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  79980. // Position
  79981. if (!this.computeEffectivePosition(globalViewport)) {
  79982. return false;
  79983. }
  79984. // Visibility
  79985. if (!this._isVisible()) {
  79986. return false;
  79987. }
  79988. // Intensity
  79989. var awayX;
  79990. var awayY;
  79991. if (this._positionX < this.borderLimit + globalViewport.x) {
  79992. awayX = this.borderLimit + globalViewport.x - this._positionX;
  79993. }
  79994. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  79995. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  79996. }
  79997. else {
  79998. awayX = 0;
  79999. }
  80000. if (this._positionY < this.borderLimit + globalViewport.y) {
  80001. awayY = this.borderLimit + globalViewport.y - this._positionY;
  80002. }
  80003. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  80004. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  80005. }
  80006. else {
  80007. awayY = 0;
  80008. }
  80009. var away = (awayX > awayY) ? awayX : awayY;
  80010. away -= this.viewportBorder;
  80011. if (away > this.borderLimit) {
  80012. away = this.borderLimit;
  80013. }
  80014. var intensity = 1.0 - (away / this.borderLimit);
  80015. if (intensity < 0) {
  80016. return false;
  80017. }
  80018. if (intensity > 1.0) {
  80019. intensity = 1.0;
  80020. }
  80021. if (this.viewportBorder > 0) {
  80022. globalViewport.x += this.viewportBorder;
  80023. globalViewport.y += this.viewportBorder;
  80024. globalViewport.width -= this.viewportBorder * 2;
  80025. globalViewport.height -= this.viewportBorder * 2;
  80026. this._positionX -= this.viewportBorder;
  80027. this._positionY -= this.viewportBorder;
  80028. }
  80029. // Position
  80030. var centerX = globalViewport.x + globalViewport.width / 2;
  80031. var centerY = globalViewport.y + globalViewport.height / 2;
  80032. var distX = centerX - this._positionX;
  80033. var distY = centerY - this._positionY;
  80034. // Effects
  80035. engine.enableEffect(this._effect);
  80036. engine.setState(false);
  80037. engine.setDepthBuffer(false);
  80038. // VBOs
  80039. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  80040. // Flares
  80041. for (var index = 0; index < this.lensFlares.length; index++) {
  80042. var flare = this.lensFlares[index];
  80043. engine.setAlphaMode(flare.alphaMode);
  80044. var x = centerX - (distX * flare.position);
  80045. var y = centerY - (distY * flare.position);
  80046. var cw = flare.size;
  80047. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  80048. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  80049. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  80050. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  80051. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  80052. // Texture
  80053. this._effect.setTexture("textureSampler", flare.texture);
  80054. // Color
  80055. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  80056. // Draw order
  80057. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80058. }
  80059. engine.setDepthBuffer(true);
  80060. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  80061. return true;
  80062. };
  80063. LensFlareSystem.prototype.dispose = function () {
  80064. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80065. if (vertexBuffer) {
  80066. vertexBuffer.dispose();
  80067. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80068. }
  80069. if (this._indexBuffer) {
  80070. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80071. this._indexBuffer = null;
  80072. }
  80073. while (this.lensFlares.length) {
  80074. this.lensFlares[0].dispose();
  80075. }
  80076. // Remove from scene
  80077. var index = this._scene.lensFlareSystems.indexOf(this);
  80078. this._scene.lensFlareSystems.splice(index, 1);
  80079. };
  80080. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  80081. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  80082. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  80083. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  80084. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  80085. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  80086. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  80087. var parsedFlare = parsedLensFlareSystem.flares[index];
  80088. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  80089. }
  80090. return lensFlareSystem;
  80091. };
  80092. LensFlareSystem.prototype.serialize = function () {
  80093. var serializationObject = {};
  80094. serializationObject.id = this.id;
  80095. serializationObject.name = this.name;
  80096. serializationObject.emitterId = this.getEmitter().id;
  80097. serializationObject.borderLimit = this.borderLimit;
  80098. serializationObject.flares = [];
  80099. for (var index = 0; index < this.lensFlares.length; index++) {
  80100. var flare = this.lensFlares[index];
  80101. serializationObject.flares.push({
  80102. size: flare.size,
  80103. position: flare.position,
  80104. color: flare.color.asArray(),
  80105. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  80106. });
  80107. }
  80108. return serializationObject;
  80109. };
  80110. return LensFlareSystem;
  80111. }());
  80112. BABYLON.LensFlareSystem = LensFlareSystem;
  80113. })(BABYLON || (BABYLON = {}));
  80114. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  80115. "use strict";
  80116. var BABYLON;
  80117. (function (BABYLON) {
  80118. /**
  80119. * This is a holder class for the physics joint created by the physics plugin.
  80120. * It holds a set of functions to control the underlying joint.
  80121. */
  80122. var PhysicsJoint = /** @class */ (function () {
  80123. function PhysicsJoint(type, jointData) {
  80124. this.type = type;
  80125. this.jointData = jointData;
  80126. jointData.nativeParams = jointData.nativeParams || {};
  80127. }
  80128. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  80129. get: function () {
  80130. return this._physicsJoint;
  80131. },
  80132. set: function (newJoint) {
  80133. if (this._physicsJoint) {
  80134. //remove from the wolrd
  80135. }
  80136. this._physicsJoint = newJoint;
  80137. },
  80138. enumerable: true,
  80139. configurable: true
  80140. });
  80141. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  80142. set: function (physicsPlugin) {
  80143. this._physicsPlugin = physicsPlugin;
  80144. },
  80145. enumerable: true,
  80146. configurable: true
  80147. });
  80148. /**
  80149. * Execute a function that is physics-plugin specific.
  80150. * @param {Function} func the function that will be executed.
  80151. * It accepts two parameters: the physics world and the physics joint.
  80152. */
  80153. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  80154. func(this._physicsPlugin.world, this._physicsJoint);
  80155. };
  80156. //TODO check if the native joints are the same
  80157. //Joint Types
  80158. PhysicsJoint.DistanceJoint = 0;
  80159. PhysicsJoint.HingeJoint = 1;
  80160. PhysicsJoint.BallAndSocketJoint = 2;
  80161. PhysicsJoint.WheelJoint = 3;
  80162. PhysicsJoint.SliderJoint = 4;
  80163. //OIMO
  80164. PhysicsJoint.PrismaticJoint = 5;
  80165. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  80166. PhysicsJoint.UniversalJoint = 6;
  80167. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  80168. //Cannon
  80169. //Similar to a Ball-Joint. Different in params
  80170. PhysicsJoint.PointToPointJoint = 8;
  80171. //Cannon only at the moment
  80172. PhysicsJoint.SpringJoint = 9;
  80173. PhysicsJoint.LockJoint = 10;
  80174. return PhysicsJoint;
  80175. }());
  80176. BABYLON.PhysicsJoint = PhysicsJoint;
  80177. /**
  80178. * A class representing a physics distance joint.
  80179. */
  80180. var DistanceJoint = /** @class */ (function (_super) {
  80181. __extends(DistanceJoint, _super);
  80182. function DistanceJoint(jointData) {
  80183. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  80184. }
  80185. /**
  80186. * Update the predefined distance.
  80187. */
  80188. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  80189. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  80190. };
  80191. return DistanceJoint;
  80192. }(PhysicsJoint));
  80193. BABYLON.DistanceJoint = DistanceJoint;
  80194. var MotorEnabledJoint = /** @class */ (function (_super) {
  80195. __extends(MotorEnabledJoint, _super);
  80196. function MotorEnabledJoint(type, jointData) {
  80197. return _super.call(this, type, jointData) || this;
  80198. }
  80199. /**
  80200. * Set the motor values.
  80201. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80202. * @param {number} force the force to apply
  80203. * @param {number} maxForce max force for this motor.
  80204. */
  80205. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  80206. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  80207. };
  80208. /**
  80209. * Set the motor's limits.
  80210. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80211. */
  80212. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  80213. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  80214. };
  80215. return MotorEnabledJoint;
  80216. }(PhysicsJoint));
  80217. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  80218. /**
  80219. * This class represents a single hinge physics joint
  80220. */
  80221. var HingeJoint = /** @class */ (function (_super) {
  80222. __extends(HingeJoint, _super);
  80223. function HingeJoint(jointData) {
  80224. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  80225. }
  80226. /**
  80227. * Set the motor values.
  80228. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80229. * @param {number} force the force to apply
  80230. * @param {number} maxForce max force for this motor.
  80231. */
  80232. HingeJoint.prototype.setMotor = function (force, maxForce) {
  80233. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  80234. };
  80235. /**
  80236. * Set the motor's limits.
  80237. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80238. */
  80239. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  80240. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  80241. };
  80242. return HingeJoint;
  80243. }(MotorEnabledJoint));
  80244. BABYLON.HingeJoint = HingeJoint;
  80245. /**
  80246. * This class represents a dual hinge physics joint (same as wheel joint)
  80247. */
  80248. var Hinge2Joint = /** @class */ (function (_super) {
  80249. __extends(Hinge2Joint, _super);
  80250. function Hinge2Joint(jointData) {
  80251. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  80252. }
  80253. /**
  80254. * Set the motor values.
  80255. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80256. * @param {number} force the force to apply
  80257. * @param {number} maxForce max force for this motor.
  80258. * @param {motorIndex} the motor's index, 0 or 1.
  80259. */
  80260. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  80261. if (motorIndex === void 0) { motorIndex = 0; }
  80262. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  80263. };
  80264. /**
  80265. * Set the motor limits.
  80266. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80267. * @param {number} upperLimit the upper limit
  80268. * @param {number} lowerLimit lower limit
  80269. * @param {motorIndex} the motor's index, 0 or 1.
  80270. */
  80271. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  80272. if (motorIndex === void 0) { motorIndex = 0; }
  80273. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  80274. };
  80275. return Hinge2Joint;
  80276. }(MotorEnabledJoint));
  80277. BABYLON.Hinge2Joint = Hinge2Joint;
  80278. })(BABYLON || (BABYLON = {}));
  80279. //# sourceMappingURL=babylon.physicsJoint.js.map
  80280. "use strict";
  80281. var BABYLON;
  80282. (function (BABYLON) {
  80283. var PhysicsImpostor = /** @class */ (function () {
  80284. function PhysicsImpostor(object, type, _options, _scene) {
  80285. if (_options === void 0) { _options = { mass: 0 }; }
  80286. var _this = this;
  80287. this.object = object;
  80288. this.type = type;
  80289. this._options = _options;
  80290. this._scene = _scene;
  80291. this._bodyUpdateRequired = false;
  80292. this._onBeforePhysicsStepCallbacks = new Array();
  80293. this._onAfterPhysicsStepCallbacks = new Array();
  80294. this._onPhysicsCollideCallbacks = [];
  80295. this._deltaPosition = BABYLON.Vector3.Zero();
  80296. this._isDisposed = false;
  80297. //temp variables for parent rotation calculations
  80298. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  80299. this._tmpQuat = new BABYLON.Quaternion();
  80300. this._tmpQuat2 = new BABYLON.Quaternion();
  80301. /**
  80302. * this function is executed by the physics engine.
  80303. */
  80304. this.beforeStep = function () {
  80305. if (!_this._physicsEngine) {
  80306. return;
  80307. }
  80308. _this.object.translate(_this._deltaPosition, -1);
  80309. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  80310. _this.object.computeWorldMatrix(false);
  80311. if (_this.object.parent && _this.object.rotationQuaternion) {
  80312. _this.getParentsRotation();
  80313. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  80314. }
  80315. else {
  80316. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  80317. }
  80318. if (!_this._options.disableBidirectionalTransformation) {
  80319. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  80320. }
  80321. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  80322. func(_this);
  80323. });
  80324. };
  80325. /**
  80326. * this function is executed by the physics engine.
  80327. */
  80328. this.afterStep = function () {
  80329. if (!_this._physicsEngine) {
  80330. return;
  80331. }
  80332. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  80333. func(_this);
  80334. });
  80335. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  80336. // object has now its world rotation. needs to be converted to local.
  80337. if (_this.object.parent && _this.object.rotationQuaternion) {
  80338. _this.getParentsRotation();
  80339. _this._tmpQuat.conjugateInPlace();
  80340. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  80341. }
  80342. // take the position set and make it the absolute position of this object.
  80343. _this.object.setAbsolutePosition(_this.object.position);
  80344. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  80345. _this.object.translate(_this._deltaPosition, 1);
  80346. };
  80347. /**
  80348. * Legacy collision detection event support
  80349. */
  80350. this.onCollideEvent = null;
  80351. //event and body object due to cannon's event-based architecture.
  80352. this.onCollide = function (e) {
  80353. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  80354. return;
  80355. }
  80356. if (!_this._physicsEngine) {
  80357. return;
  80358. }
  80359. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  80360. if (otherImpostor) {
  80361. // Legacy collision detection event support
  80362. if (_this.onCollideEvent) {
  80363. _this.onCollideEvent(_this, otherImpostor);
  80364. }
  80365. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  80366. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  80367. }).forEach(function (obj) {
  80368. obj.callback(_this, otherImpostor);
  80369. });
  80370. }
  80371. };
  80372. //sanity check!
  80373. if (!this.object) {
  80374. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  80375. return;
  80376. }
  80377. //legacy support for old syntax.
  80378. if (!this._scene && object.getScene) {
  80379. this._scene = object.getScene();
  80380. }
  80381. if (!this._scene) {
  80382. return;
  80383. }
  80384. this._physicsEngine = this._scene.getPhysicsEngine();
  80385. if (!this._physicsEngine) {
  80386. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  80387. }
  80388. else {
  80389. //set the object's quaternion, if not set
  80390. if (!this.object.rotationQuaternion) {
  80391. if (this.object.rotation) {
  80392. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  80393. }
  80394. else {
  80395. this.object.rotationQuaternion = new BABYLON.Quaternion();
  80396. }
  80397. }
  80398. //default options params
  80399. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  80400. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  80401. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  80402. this._joints = [];
  80403. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  80404. if (!this.object.parent || this._options.ignoreParent) {
  80405. this._init();
  80406. }
  80407. else if (this.object.parent.physicsImpostor) {
  80408. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  80409. }
  80410. }
  80411. }
  80412. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  80413. get: function () {
  80414. return this._isDisposed;
  80415. },
  80416. enumerable: true,
  80417. configurable: true
  80418. });
  80419. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  80420. get: function () {
  80421. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  80422. },
  80423. set: function (value) {
  80424. this.setMass(value);
  80425. },
  80426. enumerable: true,
  80427. configurable: true
  80428. });
  80429. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  80430. get: function () {
  80431. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  80432. },
  80433. set: function (value) {
  80434. if (!this._physicsEngine) {
  80435. return;
  80436. }
  80437. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  80438. },
  80439. enumerable: true,
  80440. configurable: true
  80441. });
  80442. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  80443. get: function () {
  80444. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  80445. },
  80446. set: function (value) {
  80447. if (!this._physicsEngine) {
  80448. return;
  80449. }
  80450. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  80451. },
  80452. enumerable: true,
  80453. configurable: true
  80454. });
  80455. /**
  80456. * This function will completly initialize this impostor.
  80457. * It will create a new body - but only if this mesh has no parent.
  80458. * If it has, this impostor will not be used other than to define the impostor
  80459. * of the child mesh.
  80460. */
  80461. PhysicsImpostor.prototype._init = function () {
  80462. if (!this._physicsEngine) {
  80463. return;
  80464. }
  80465. this._physicsEngine.removeImpostor(this);
  80466. this.physicsBody = null;
  80467. this._parent = this._parent || this._getPhysicsParent();
  80468. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  80469. this._physicsEngine.addImpostor(this);
  80470. }
  80471. };
  80472. PhysicsImpostor.prototype._getPhysicsParent = function () {
  80473. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  80474. var parentMesh = this.object.parent;
  80475. return parentMesh.physicsImpostor;
  80476. }
  80477. return null;
  80478. };
  80479. /**
  80480. * Should a new body be generated.
  80481. */
  80482. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  80483. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  80484. };
  80485. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  80486. this.forceUpdate();
  80487. };
  80488. /**
  80489. * Force a regeneration of this or the parent's impostor's body.
  80490. * Use under cautious - This will remove all joints already implemented.
  80491. */
  80492. PhysicsImpostor.prototype.forceUpdate = function () {
  80493. this._init();
  80494. if (this.parent && !this._options.ignoreParent) {
  80495. this.parent.forceUpdate();
  80496. }
  80497. };
  80498. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  80499. /*public get mesh(): AbstractMesh {
  80500. return this._mesh;
  80501. }*/
  80502. /**
  80503. * Gets the body that holds this impostor. Either its own, or its parent.
  80504. */
  80505. get: function () {
  80506. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  80507. },
  80508. /**
  80509. * Set the physics body. Used mainly by the physics engine/plugin
  80510. */
  80511. set: function (physicsBody) {
  80512. if (this._physicsBody && this._physicsEngine) {
  80513. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  80514. }
  80515. this._physicsBody = physicsBody;
  80516. this.resetUpdateFlags();
  80517. },
  80518. enumerable: true,
  80519. configurable: true
  80520. });
  80521. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  80522. get: function () {
  80523. return !this._options.ignoreParent && this._parent ? this._parent : null;
  80524. },
  80525. set: function (value) {
  80526. this._parent = value;
  80527. },
  80528. enumerable: true,
  80529. configurable: true
  80530. });
  80531. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  80532. this._bodyUpdateRequired = false;
  80533. };
  80534. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  80535. if (this.object.getBoundingInfo) {
  80536. var q = this.object.rotationQuaternion;
  80537. //reset rotation
  80538. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  80539. //calculate the world matrix with no rotation
  80540. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  80541. var boundingInfo = this.object.getBoundingInfo();
  80542. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  80543. //bring back the rotation
  80544. this.object.rotationQuaternion = q;
  80545. //calculate the world matrix with the new rotation
  80546. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  80547. return size;
  80548. }
  80549. else {
  80550. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  80551. }
  80552. };
  80553. PhysicsImpostor.prototype.getObjectCenter = function () {
  80554. if (this.object.getBoundingInfo) {
  80555. var boundingInfo = this.object.getBoundingInfo();
  80556. return boundingInfo.boundingBox.centerWorld;
  80557. }
  80558. else {
  80559. return this.object.position;
  80560. }
  80561. };
  80562. /**
  80563. * Get a specific parametes from the options parameter.
  80564. */
  80565. PhysicsImpostor.prototype.getParam = function (paramName) {
  80566. return this._options[paramName];
  80567. };
  80568. /**
  80569. * Sets a specific parameter in the options given to the physics plugin
  80570. */
  80571. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  80572. this._options[paramName] = value;
  80573. this._bodyUpdateRequired = true;
  80574. };
  80575. /**
  80576. * Specifically change the body's mass option. Won't recreate the physics body object
  80577. */
  80578. PhysicsImpostor.prototype.setMass = function (mass) {
  80579. if (this.getParam("mass") !== mass) {
  80580. this.setParam("mass", mass);
  80581. }
  80582. if (this._physicsEngine) {
  80583. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  80584. }
  80585. };
  80586. PhysicsImpostor.prototype.getLinearVelocity = function () {
  80587. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  80588. };
  80589. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  80590. if (this._physicsEngine) {
  80591. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  80592. }
  80593. };
  80594. PhysicsImpostor.prototype.getAngularVelocity = function () {
  80595. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  80596. };
  80597. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  80598. if (this._physicsEngine) {
  80599. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  80600. }
  80601. };
  80602. /**
  80603. * Execute a function with the physics plugin native code.
  80604. * Provide a function the will have two variables - the world object and the physics body object.
  80605. */
  80606. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  80607. if (this._physicsEngine) {
  80608. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  80609. }
  80610. };
  80611. /**
  80612. * Register a function that will be executed before the physics world is stepping forward.
  80613. */
  80614. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  80615. this._onBeforePhysicsStepCallbacks.push(func);
  80616. };
  80617. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  80618. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  80619. if (index > -1) {
  80620. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  80621. }
  80622. else {
  80623. BABYLON.Tools.Warn("Function to remove was not found");
  80624. }
  80625. };
  80626. /**
  80627. * Register a function that will be executed after the physics step
  80628. */
  80629. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  80630. this._onAfterPhysicsStepCallbacks.push(func);
  80631. };
  80632. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  80633. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  80634. if (index > -1) {
  80635. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  80636. }
  80637. else {
  80638. BABYLON.Tools.Warn("Function to remove was not found");
  80639. }
  80640. };
  80641. /**
  80642. * register a function that will be executed when this impostor collides against a different body.
  80643. */
  80644. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  80645. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  80646. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  80647. };
  80648. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  80649. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  80650. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  80651. if (index > -1) {
  80652. this._onPhysicsCollideCallbacks.splice(index, 1);
  80653. }
  80654. else {
  80655. BABYLON.Tools.Warn("Function to remove was not found");
  80656. }
  80657. };
  80658. PhysicsImpostor.prototype.getParentsRotation = function () {
  80659. var parent = this.object.parent;
  80660. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  80661. while (parent) {
  80662. if (parent.rotationQuaternion) {
  80663. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  80664. }
  80665. else {
  80666. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  80667. }
  80668. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  80669. parent = parent.parent;
  80670. }
  80671. return this._tmpQuat;
  80672. };
  80673. /**
  80674. * Apply a force
  80675. */
  80676. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  80677. if (this._physicsEngine) {
  80678. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  80679. }
  80680. return this;
  80681. };
  80682. /**
  80683. * Apply an impulse
  80684. */
  80685. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  80686. if (this._physicsEngine) {
  80687. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  80688. }
  80689. return this;
  80690. };
  80691. /**
  80692. * A help function to create a joint.
  80693. */
  80694. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  80695. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  80696. this.addJoint(otherImpostor, joint);
  80697. return this;
  80698. };
  80699. /**
  80700. * Add a joint to this impostor with a different impostor.
  80701. */
  80702. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  80703. this._joints.push({
  80704. otherImpostor: otherImpostor,
  80705. joint: joint
  80706. });
  80707. if (this._physicsEngine) {
  80708. this._physicsEngine.addJoint(this, otherImpostor, joint);
  80709. }
  80710. return this;
  80711. };
  80712. /**
  80713. * Will keep this body still, in a sleep mode.
  80714. */
  80715. PhysicsImpostor.prototype.sleep = function () {
  80716. if (this._physicsEngine) {
  80717. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  80718. }
  80719. return this;
  80720. };
  80721. /**
  80722. * Wake the body up.
  80723. */
  80724. PhysicsImpostor.prototype.wakeUp = function () {
  80725. if (this._physicsEngine) {
  80726. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  80727. }
  80728. return this;
  80729. };
  80730. PhysicsImpostor.prototype.clone = function (newObject) {
  80731. if (!newObject)
  80732. return null;
  80733. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  80734. };
  80735. PhysicsImpostor.prototype.dispose = function () {
  80736. var _this = this;
  80737. //no dispose if no physics engine is available.
  80738. if (!this._physicsEngine) {
  80739. return;
  80740. }
  80741. this._joints.forEach(function (j) {
  80742. if (_this._physicsEngine) {
  80743. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  80744. }
  80745. });
  80746. //dispose the physics body
  80747. this._physicsEngine.removeImpostor(this);
  80748. if (this.parent) {
  80749. this.parent.forceUpdate();
  80750. }
  80751. else {
  80752. /*this._object.getChildMeshes().forEach(function(mesh) {
  80753. if (mesh.physicsImpostor) {
  80754. if (disposeChildren) {
  80755. mesh.physicsImpostor.dispose();
  80756. mesh.physicsImpostor = null;
  80757. }
  80758. }
  80759. })*/
  80760. }
  80761. this._isDisposed = true;
  80762. };
  80763. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  80764. this._deltaPosition.copyFrom(position);
  80765. };
  80766. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  80767. if (!this._deltaRotation) {
  80768. this._deltaRotation = new BABYLON.Quaternion();
  80769. }
  80770. this._deltaRotation.copyFrom(rotation);
  80771. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  80772. };
  80773. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  80774. if (this._physicsEngine) {
  80775. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  80776. }
  80777. return this;
  80778. };
  80779. PhysicsImpostor.prototype.getRadius = function () {
  80780. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  80781. };
  80782. /**
  80783. * Sync a bone with this impostor
  80784. * @param bone The bone to sync to the impostor.
  80785. * @param boneMesh The mesh that the bone is influencing.
  80786. * @param jointPivot The pivot of the joint / bone in local space.
  80787. * @param distToJoint Optional distance from the impostor to the joint.
  80788. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  80789. */
  80790. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  80791. var tempVec = PhysicsImpostor._tmpVecs[0];
  80792. var mesh = this.object;
  80793. if (mesh.rotationQuaternion) {
  80794. if (adjustRotation) {
  80795. var tempQuat = PhysicsImpostor._tmpQuat;
  80796. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  80797. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  80798. }
  80799. else {
  80800. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  80801. }
  80802. }
  80803. tempVec.x = 0;
  80804. tempVec.y = 0;
  80805. tempVec.z = 0;
  80806. if (jointPivot) {
  80807. tempVec.x = jointPivot.x;
  80808. tempVec.y = jointPivot.y;
  80809. tempVec.z = jointPivot.z;
  80810. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  80811. if (distToJoint === undefined || distToJoint === null) {
  80812. distToJoint = jointPivot.length();
  80813. }
  80814. tempVec.x *= distToJoint;
  80815. tempVec.y *= distToJoint;
  80816. tempVec.z *= distToJoint;
  80817. }
  80818. if (bone.getParent()) {
  80819. tempVec.addInPlace(mesh.getAbsolutePosition());
  80820. bone.setAbsolutePosition(tempVec, boneMesh);
  80821. }
  80822. else {
  80823. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  80824. boneMesh.position.x -= tempVec.x;
  80825. boneMesh.position.y -= tempVec.y;
  80826. boneMesh.position.z -= tempVec.z;
  80827. }
  80828. };
  80829. /**
  80830. * Sync impostor to a bone
  80831. * @param bone The bone that the impostor will be synced to.
  80832. * @param boneMesh The mesh that the bone is influencing.
  80833. * @param jointPivot The pivot of the joint / bone in local space.
  80834. * @param distToJoint Optional distance from the impostor to the joint.
  80835. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  80836. * @param boneAxis Optional vector3 axis the bone is aligned with
  80837. */
  80838. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  80839. var mesh = this.object;
  80840. if (mesh.rotationQuaternion) {
  80841. if (adjustRotation) {
  80842. var tempQuat = PhysicsImpostor._tmpQuat;
  80843. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  80844. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  80845. }
  80846. else {
  80847. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  80848. }
  80849. }
  80850. var pos = PhysicsImpostor._tmpVecs[0];
  80851. var boneDir = PhysicsImpostor._tmpVecs[1];
  80852. if (!boneAxis) {
  80853. boneAxis = PhysicsImpostor._tmpVecs[2];
  80854. boneAxis.x = 0;
  80855. boneAxis.y = 1;
  80856. boneAxis.z = 0;
  80857. }
  80858. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  80859. bone.getAbsolutePositionToRef(boneMesh, pos);
  80860. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  80861. distToJoint = jointPivot.length();
  80862. }
  80863. if (distToJoint !== undefined && distToJoint !== null) {
  80864. pos.x += boneDir.x * distToJoint;
  80865. pos.y += boneDir.y * distToJoint;
  80866. pos.z += boneDir.z * distToJoint;
  80867. }
  80868. mesh.setAbsolutePosition(pos);
  80869. };
  80870. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  80871. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  80872. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80873. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  80874. //Impostor types
  80875. PhysicsImpostor.NoImpostor = 0;
  80876. PhysicsImpostor.SphereImpostor = 1;
  80877. PhysicsImpostor.BoxImpostor = 2;
  80878. PhysicsImpostor.PlaneImpostor = 3;
  80879. PhysicsImpostor.MeshImpostor = 4;
  80880. PhysicsImpostor.CylinderImpostor = 7;
  80881. PhysicsImpostor.ParticleImpostor = 8;
  80882. PhysicsImpostor.HeightmapImpostor = 9;
  80883. return PhysicsImpostor;
  80884. }());
  80885. BABYLON.PhysicsImpostor = PhysicsImpostor;
  80886. })(BABYLON || (BABYLON = {}));
  80887. //# sourceMappingURL=babylon.physicsImpostor.js.map
  80888. "use strict";
  80889. var BABYLON;
  80890. (function (BABYLON) {
  80891. var PhysicsEngine = /** @class */ (function () {
  80892. function PhysicsEngine(gravity, _physicsPlugin) {
  80893. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  80894. this._physicsPlugin = _physicsPlugin;
  80895. //new methods and parameters
  80896. this._impostors = [];
  80897. this._joints = [];
  80898. if (!this._physicsPlugin.isSupported()) {
  80899. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  80900. + "Please make sure it is included.");
  80901. }
  80902. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  80903. this.setGravity(gravity);
  80904. this.setTimeStep();
  80905. }
  80906. PhysicsEngine.prototype.setGravity = function (gravity) {
  80907. this.gravity = gravity;
  80908. this._physicsPlugin.setGravity(this.gravity);
  80909. };
  80910. /**
  80911. * Set the time step of the physics engine.
  80912. * default is 1/60.
  80913. * To slow it down, enter 1/600 for example.
  80914. * To speed it up, 1/30
  80915. * @param {number} newTimeStep the new timestep to apply to this world.
  80916. */
  80917. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  80918. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  80919. this._physicsPlugin.setTimeStep(newTimeStep);
  80920. };
  80921. /**
  80922. * Get the time step of the physics engine.
  80923. */
  80924. PhysicsEngine.prototype.getTimeStep = function () {
  80925. return this._physicsPlugin.getTimeStep();
  80926. };
  80927. PhysicsEngine.prototype.dispose = function () {
  80928. this._impostors.forEach(function (impostor) {
  80929. impostor.dispose();
  80930. });
  80931. this._physicsPlugin.dispose();
  80932. };
  80933. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  80934. return this._physicsPlugin.name;
  80935. };
  80936. /**
  80937. * Adding a new impostor for the impostor tracking.
  80938. * This will be done by the impostor itself.
  80939. * @param {PhysicsImpostor} impostor the impostor to add
  80940. */
  80941. PhysicsEngine.prototype.addImpostor = function (impostor) {
  80942. impostor.uniqueId = this._impostors.push(impostor);
  80943. //if no parent, generate the body
  80944. if (!impostor.parent) {
  80945. this._physicsPlugin.generatePhysicsBody(impostor);
  80946. }
  80947. };
  80948. /**
  80949. * Remove an impostor from the engine.
  80950. * This impostor and its mesh will not longer be updated by the physics engine.
  80951. * @param {PhysicsImpostor} impostor the impostor to remove
  80952. */
  80953. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  80954. var index = this._impostors.indexOf(impostor);
  80955. if (index > -1) {
  80956. var removed = this._impostors.splice(index, 1);
  80957. //Is it needed?
  80958. if (removed.length) {
  80959. //this will also remove it from the world.
  80960. removed[0].physicsBody = null;
  80961. }
  80962. }
  80963. };
  80964. /**
  80965. * Add a joint to the physics engine
  80966. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  80967. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  80968. * @param {PhysicsJoint} the joint that will connect both impostors.
  80969. */
  80970. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  80971. var impostorJoint = {
  80972. mainImpostor: mainImpostor,
  80973. connectedImpostor: connectedImpostor,
  80974. joint: joint
  80975. };
  80976. joint.physicsPlugin = this._physicsPlugin;
  80977. this._joints.push(impostorJoint);
  80978. this._physicsPlugin.generateJoint(impostorJoint);
  80979. };
  80980. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  80981. var matchingJoints = this._joints.filter(function (impostorJoint) {
  80982. return (impostorJoint.connectedImpostor === connectedImpostor
  80983. && impostorJoint.joint === joint
  80984. && impostorJoint.mainImpostor === mainImpostor);
  80985. });
  80986. if (matchingJoints.length) {
  80987. this._physicsPlugin.removeJoint(matchingJoints[0]);
  80988. //TODO remove it from the list as well
  80989. }
  80990. };
  80991. /**
  80992. * Called by the scene. no need to call it.
  80993. */
  80994. PhysicsEngine.prototype._step = function (delta) {
  80995. var _this = this;
  80996. //check if any mesh has no body / requires an update
  80997. this._impostors.forEach(function (impostor) {
  80998. if (impostor.isBodyInitRequired()) {
  80999. _this._physicsPlugin.generatePhysicsBody(impostor);
  81000. }
  81001. });
  81002. if (delta > 0.1) {
  81003. delta = 0.1;
  81004. }
  81005. else if (delta <= 0) {
  81006. delta = 1.0 / 60.0;
  81007. }
  81008. this._physicsPlugin.executeStep(delta, this._impostors);
  81009. };
  81010. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  81011. return this._physicsPlugin;
  81012. };
  81013. PhysicsEngine.prototype.getImpostors = function () {
  81014. return this._impostors;
  81015. };
  81016. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  81017. for (var i = 0; i < this._impostors.length; ++i) {
  81018. if (this._impostors[i].object === object) {
  81019. return this._impostors[i];
  81020. }
  81021. }
  81022. return null;
  81023. };
  81024. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  81025. for (var i = 0; i < this._impostors.length; ++i) {
  81026. if (this._impostors[i].physicsBody === body) {
  81027. return this._impostors[i];
  81028. }
  81029. }
  81030. return null;
  81031. };
  81032. // Statics
  81033. PhysicsEngine.Epsilon = 0.001;
  81034. return PhysicsEngine;
  81035. }());
  81036. BABYLON.PhysicsEngine = PhysicsEngine;
  81037. })(BABYLON || (BABYLON = {}));
  81038. //# sourceMappingURL=babylon.physicsEngine.js.map
  81039. "use strict";
  81040. var BABYLON;
  81041. (function (BABYLON) {
  81042. var PhysicsHelper = /** @class */ (function () {
  81043. function PhysicsHelper(scene) {
  81044. this._scene = scene;
  81045. this._physicsEngine = this._scene.getPhysicsEngine();
  81046. if (!this._physicsEngine) {
  81047. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  81048. }
  81049. }
  81050. /**
  81051. * @param {Vector3} origin the origin of the explosion
  81052. * @param {number} radius the explosion radius
  81053. * @param {number} strength the explosion strength
  81054. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  81055. */
  81056. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  81057. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81058. if (!this._physicsEngine) {
  81059. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  81060. return null;
  81061. }
  81062. var impostors = this._physicsEngine.getImpostors();
  81063. if (impostors.length === 0) {
  81064. return null;
  81065. }
  81066. var event = new PhysicsRadialExplosionEvent(this._scene);
  81067. impostors.forEach(function (impostor) {
  81068. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  81069. if (!impostorForceAndContactPoint) {
  81070. return;
  81071. }
  81072. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81073. });
  81074. event.dispose(false);
  81075. return event;
  81076. };
  81077. /**
  81078. * @param {Vector3} origin the origin of the explosion
  81079. * @param {number} radius the explosion radius
  81080. * @param {number} strength the explosion strength
  81081. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  81082. */
  81083. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  81084. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81085. if (!this._physicsEngine) {
  81086. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81087. return null;
  81088. }
  81089. var impostors = this._physicsEngine.getImpostors();
  81090. if (impostors.length === 0) {
  81091. return null;
  81092. }
  81093. var event = new PhysicsRadialExplosionEvent(this._scene);
  81094. impostors.forEach(function (impostor) {
  81095. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  81096. if (!impostorForceAndContactPoint) {
  81097. return;
  81098. }
  81099. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81100. });
  81101. event.dispose(false);
  81102. return event;
  81103. };
  81104. /**
  81105. * @param {Vector3} origin the origin of the explosion
  81106. * @param {number} radius the explosion radius
  81107. * @param {number} strength the explosion strength
  81108. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  81109. */
  81110. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  81111. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81112. if (!this._physicsEngine) {
  81113. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81114. return null;
  81115. }
  81116. var impostors = this._physicsEngine.getImpostors();
  81117. if (impostors.length === 0) {
  81118. return null;
  81119. }
  81120. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  81121. event.dispose(false);
  81122. return event;
  81123. };
  81124. /**
  81125. * @param {Vector3} origin the origin of the updraft
  81126. * @param {number} radius the radius of the updraft
  81127. * @param {number} strength the strength of the updraft
  81128. * @param {number} height the height of the updraft
  81129. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  81130. */
  81131. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  81132. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  81133. if (!this._physicsEngine) {
  81134. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81135. return null;
  81136. }
  81137. if (this._physicsEngine.getImpostors().length === 0) {
  81138. return null;
  81139. }
  81140. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  81141. event.dispose(false);
  81142. return event;
  81143. };
  81144. /**
  81145. * @param {Vector3} origin the of the vortex
  81146. * @param {number} radius the radius of the vortex
  81147. * @param {number} strength the strength of the vortex
  81148. * @param {number} height the height of the vortex
  81149. */
  81150. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  81151. if (!this._physicsEngine) {
  81152. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81153. return null;
  81154. }
  81155. if (this._physicsEngine.getImpostors().length === 0) {
  81156. return null;
  81157. }
  81158. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  81159. event.dispose(false);
  81160. return event;
  81161. };
  81162. return PhysicsHelper;
  81163. }());
  81164. BABYLON.PhysicsHelper = PhysicsHelper;
  81165. /***** Radial explosion *****/
  81166. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  81167. function PhysicsRadialExplosionEvent(scene) {
  81168. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  81169. this._rays = [];
  81170. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  81171. this._scene = scene;
  81172. }
  81173. /**
  81174. * Returns the data related to the radial explosion event (sphere & rays).
  81175. * @returns {PhysicsRadialExplosionEventData}
  81176. */
  81177. PhysicsRadialExplosionEvent.prototype.getData = function () {
  81178. this._dataFetched = true;
  81179. return {
  81180. sphere: this._sphere,
  81181. rays: this._rays,
  81182. };
  81183. };
  81184. /**
  81185. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  81186. * @param impostor
  81187. * @param {Vector3} origin the origin of the explosion
  81188. * @param {number} radius the explosion radius
  81189. * @param {number} strength the explosion strength
  81190. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  81191. * @returns {Nullable<PhysicsForceAndContactPoint>}
  81192. */
  81193. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  81194. if (impostor.mass === 0) {
  81195. return null;
  81196. }
  81197. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  81198. return null;
  81199. }
  81200. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  81201. return null;
  81202. }
  81203. var impostorObjectCenter = impostor.getObjectCenter();
  81204. var direction = impostorObjectCenter.subtract(origin);
  81205. var ray = new BABYLON.Ray(origin, direction, radius);
  81206. this._rays.push(ray);
  81207. var hit = ray.intersectsMesh(impostor.object);
  81208. var contactPoint = hit.pickedPoint;
  81209. if (!contactPoint) {
  81210. return null;
  81211. }
  81212. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  81213. if (distanceFromOrigin > radius) {
  81214. return null;
  81215. }
  81216. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  81217. ? strength
  81218. : strength * (1 - (distanceFromOrigin / radius));
  81219. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  81220. return { force: force, contactPoint: contactPoint };
  81221. };
  81222. /**
  81223. * Disposes the sphere.
  81224. * @param {bolean} force
  81225. */
  81226. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  81227. var _this = this;
  81228. if (force === void 0) { force = true; }
  81229. if (force) {
  81230. this._sphere.dispose();
  81231. }
  81232. else {
  81233. setTimeout(function () {
  81234. if (!_this._dataFetched) {
  81235. _this._sphere.dispose();
  81236. }
  81237. }, 0);
  81238. }
  81239. };
  81240. /*** Helpers ***/
  81241. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  81242. if (!this._sphere) {
  81243. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  81244. this._sphere.isVisible = false;
  81245. }
  81246. };
  81247. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  81248. var impostorObject = impostor.object;
  81249. this._prepareSphere();
  81250. this._sphere.position = origin;
  81251. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  81252. this._sphere._updateBoundingInfo();
  81253. this._sphere.computeWorldMatrix(true);
  81254. return this._sphere.intersectsMesh(impostorObject, true);
  81255. };
  81256. return PhysicsRadialExplosionEvent;
  81257. }());
  81258. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  81259. /***** Gravitational Field *****/
  81260. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  81261. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  81262. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81263. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  81264. this._physicsHelper = physicsHelper;
  81265. this._scene = scene;
  81266. this._origin = origin;
  81267. this._radius = radius;
  81268. this._strength = strength;
  81269. this._falloff = falloff;
  81270. this._tickCallback = this._tick.bind(this);
  81271. }
  81272. /**
  81273. * Returns the data related to the gravitational field event (sphere).
  81274. * @returns {PhysicsGravitationalFieldEventData}
  81275. */
  81276. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  81277. this._dataFetched = true;
  81278. return {
  81279. sphere: this._sphere,
  81280. };
  81281. };
  81282. /**
  81283. * Enables the gravitational field.
  81284. */
  81285. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  81286. this._tickCallback.call(this);
  81287. this._scene.registerBeforeRender(this._tickCallback);
  81288. };
  81289. /**
  81290. * Disables the gravitational field.
  81291. */
  81292. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  81293. this._scene.unregisterBeforeRender(this._tickCallback);
  81294. };
  81295. /**
  81296. * Disposes the sphere.
  81297. * @param {bolean} force
  81298. */
  81299. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  81300. var _this = this;
  81301. if (force === void 0) { force = true; }
  81302. if (force) {
  81303. this._sphere.dispose();
  81304. }
  81305. else {
  81306. setTimeout(function () {
  81307. if (!_this._dataFetched) {
  81308. _this._sphere.dispose();
  81309. }
  81310. }, 0);
  81311. }
  81312. };
  81313. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  81314. // Since the params won't change, we fetch the event only once
  81315. if (this._sphere) {
  81316. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  81317. }
  81318. else {
  81319. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  81320. if (radialExplosionEvent) {
  81321. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  81322. }
  81323. }
  81324. };
  81325. return PhysicsGravitationalFieldEvent;
  81326. }());
  81327. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  81328. /***** Updraft *****/
  81329. var PhysicsUpdraftEvent = /** @class */ (function () {
  81330. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  81331. this._scene = _scene;
  81332. this._origin = _origin;
  81333. this._radius = _radius;
  81334. this._strength = _strength;
  81335. this._height = _height;
  81336. this._updraftMode = _updraftMode;
  81337. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  81338. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  81339. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  81340. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  81341. this._physicsEngine = this._scene.getPhysicsEngine();
  81342. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  81343. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  81344. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  81345. this._originDirection = this._origin.subtract(this._originTop).normalize();
  81346. }
  81347. this._tickCallback = this._tick.bind(this);
  81348. }
  81349. /**
  81350. * Returns the data related to the updraft event (cylinder).
  81351. * @returns {PhysicsUpdraftEventData}
  81352. */
  81353. PhysicsUpdraftEvent.prototype.getData = function () {
  81354. this._dataFetched = true;
  81355. return {
  81356. cylinder: this._cylinder,
  81357. };
  81358. };
  81359. /**
  81360. * Enables the updraft.
  81361. */
  81362. PhysicsUpdraftEvent.prototype.enable = function () {
  81363. this._tickCallback.call(this);
  81364. this._scene.registerBeforeRender(this._tickCallback);
  81365. };
  81366. /**
  81367. * Disables the cortex.
  81368. */
  81369. PhysicsUpdraftEvent.prototype.disable = function () {
  81370. this._scene.unregisterBeforeRender(this._tickCallback);
  81371. };
  81372. /**
  81373. * Disposes the sphere.
  81374. * @param {bolean} force
  81375. */
  81376. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  81377. var _this = this;
  81378. if (force === void 0) { force = true; }
  81379. if (force) {
  81380. this._cylinder.dispose();
  81381. }
  81382. else {
  81383. setTimeout(function () {
  81384. if (!_this._dataFetched) {
  81385. _this._cylinder.dispose();
  81386. }
  81387. }, 0);
  81388. }
  81389. };
  81390. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  81391. if (impostor.mass === 0) {
  81392. return null;
  81393. }
  81394. if (!this._intersectsWithCylinder(impostor)) {
  81395. return null;
  81396. }
  81397. var impostorObjectCenter = impostor.getObjectCenter();
  81398. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  81399. var direction = this._originDirection;
  81400. }
  81401. else {
  81402. var direction = impostorObjectCenter.subtract(this._originTop);
  81403. }
  81404. var multiplier = this._strength * -1;
  81405. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  81406. return { force: force, contactPoint: impostorObjectCenter };
  81407. };
  81408. PhysicsUpdraftEvent.prototype._tick = function () {
  81409. var _this = this;
  81410. this._physicsEngine.getImpostors().forEach(function (impostor) {
  81411. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  81412. if (!impostorForceAndContactPoint) {
  81413. return;
  81414. }
  81415. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81416. });
  81417. };
  81418. /*** Helpers ***/
  81419. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  81420. if (!this._cylinder) {
  81421. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  81422. height: this._height,
  81423. diameter: this._radius * 2,
  81424. }, this._scene);
  81425. this._cylinder.isVisible = false;
  81426. }
  81427. };
  81428. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  81429. var impostorObject = impostor.object;
  81430. this._prepareCylinder();
  81431. this._cylinder.position = this._cylinderPosition;
  81432. return this._cylinder.intersectsMesh(impostorObject, true);
  81433. };
  81434. return PhysicsUpdraftEvent;
  81435. }());
  81436. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  81437. /***** Vortex *****/
  81438. var PhysicsVortexEvent = /** @class */ (function () {
  81439. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  81440. this._scene = _scene;
  81441. this._origin = _origin;
  81442. this._radius = _radius;
  81443. this._strength = _strength;
  81444. this._height = _height;
  81445. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  81446. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  81447. this._updraftMultiplier = 0.02;
  81448. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  81449. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  81450. this._physicsEngine = this._scene.getPhysicsEngine();
  81451. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  81452. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  81453. this._tickCallback = this._tick.bind(this);
  81454. }
  81455. /**
  81456. * Returns the data related to the vortex event (cylinder).
  81457. * @returns {PhysicsVortexEventData}
  81458. */
  81459. PhysicsVortexEvent.prototype.getData = function () {
  81460. this._dataFetched = true;
  81461. return {
  81462. cylinder: this._cylinder,
  81463. };
  81464. };
  81465. /**
  81466. * Enables the vortex.
  81467. */
  81468. PhysicsVortexEvent.prototype.enable = function () {
  81469. this._tickCallback.call(this);
  81470. this._scene.registerBeforeRender(this._tickCallback);
  81471. };
  81472. /**
  81473. * Disables the cortex.
  81474. */
  81475. PhysicsVortexEvent.prototype.disable = function () {
  81476. this._scene.unregisterBeforeRender(this._tickCallback);
  81477. };
  81478. /**
  81479. * Disposes the sphere.
  81480. * @param {bolean} force
  81481. */
  81482. PhysicsVortexEvent.prototype.dispose = function (force) {
  81483. var _this = this;
  81484. if (force === void 0) { force = true; }
  81485. if (force) {
  81486. this._cylinder.dispose();
  81487. }
  81488. else {
  81489. setTimeout(function () {
  81490. if (!_this._dataFetched) {
  81491. _this._cylinder.dispose();
  81492. }
  81493. }, 0);
  81494. }
  81495. };
  81496. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  81497. if (impostor.mass === 0) {
  81498. return null;
  81499. }
  81500. if (!this._intersectsWithCylinder(impostor)) {
  81501. return null;
  81502. }
  81503. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  81504. return null;
  81505. }
  81506. var impostorObjectCenter = impostor.getObjectCenter();
  81507. 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)
  81508. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  81509. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  81510. var hit = ray.intersectsMesh(impostor.object);
  81511. var contactPoint = hit.pickedPoint;
  81512. if (!contactPoint) {
  81513. return null;
  81514. }
  81515. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  81516. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  81517. var directionToOrigin = contactPoint.normalize();
  81518. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  81519. directionToOrigin = directionToOrigin.negate();
  81520. }
  81521. // TODO: find a more physically based solution
  81522. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  81523. var forceX = directionToOrigin.x * this._strength / 8;
  81524. var forceY = directionToOrigin.y * this._updraftMultiplier;
  81525. var forceZ = directionToOrigin.z * this._strength / 8;
  81526. }
  81527. else {
  81528. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  81529. var forceY = this._originTop.y * this._updraftMultiplier;
  81530. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  81531. }
  81532. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  81533. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  81534. return { force: force, contactPoint: impostorObjectCenter };
  81535. };
  81536. PhysicsVortexEvent.prototype._tick = function () {
  81537. var _this = this;
  81538. this._physicsEngine.getImpostors().forEach(function (impostor) {
  81539. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  81540. if (!impostorForceAndContactPoint) {
  81541. return;
  81542. }
  81543. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81544. });
  81545. };
  81546. /*** Helpers ***/
  81547. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  81548. if (!this._cylinder) {
  81549. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  81550. height: this._height,
  81551. diameter: this._radius * 2,
  81552. }, this._scene);
  81553. this._cylinder.isVisible = false;
  81554. }
  81555. };
  81556. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  81557. var impostorObject = impostor.object;
  81558. this._prepareCylinder();
  81559. this._cylinder.position = this._cylinderPosition;
  81560. return this._cylinder.intersectsMesh(impostorObject, true);
  81561. };
  81562. return PhysicsVortexEvent;
  81563. }());
  81564. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  81565. /***** Enums *****/
  81566. /**
  81567. * The strenght of the force in correspondence to the distance of the affected object
  81568. */
  81569. var PhysicsRadialImpulseFalloff;
  81570. (function (PhysicsRadialImpulseFalloff) {
  81571. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  81572. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  81573. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  81574. /**
  81575. * The strenght of the force in correspondence to the distance of the affected object
  81576. */
  81577. var PhysicsUpdraftMode;
  81578. (function (PhysicsUpdraftMode) {
  81579. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  81580. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  81581. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  81582. })(BABYLON || (BABYLON = {}));
  81583. //# sourceMappingURL=babylon.physicsHelper.js.map
  81584. "use strict";
  81585. var BABYLON;
  81586. (function (BABYLON) {
  81587. var CannonJSPlugin = /** @class */ (function () {
  81588. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  81589. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  81590. if (iterations === void 0) { iterations = 10; }
  81591. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  81592. this.name = "CannonJSPlugin";
  81593. this._physicsMaterials = new Array();
  81594. this._fixedTimeStep = 1 / 60;
  81595. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  81596. this.BJSCANNON = CANNON;
  81597. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  81598. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  81599. this._tmpPosition = BABYLON.Vector3.Zero();
  81600. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  81601. this._tmpUnityRotation = new BABYLON.Quaternion();
  81602. if (!this.isSupported()) {
  81603. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  81604. return;
  81605. }
  81606. this._extendNamespace();
  81607. this.world = new this.BJSCANNON.World();
  81608. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  81609. this.world.solver.iterations = iterations;
  81610. }
  81611. CannonJSPlugin.prototype.setGravity = function (gravity) {
  81612. this.world.gravity.copy(gravity);
  81613. };
  81614. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  81615. this._fixedTimeStep = timeStep;
  81616. };
  81617. CannonJSPlugin.prototype.getTimeStep = function () {
  81618. return this._fixedTimeStep;
  81619. };
  81620. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  81621. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  81622. };
  81623. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  81624. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  81625. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  81626. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  81627. };
  81628. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  81629. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  81630. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  81631. impostor.physicsBody.applyForce(impulse, worldPoint);
  81632. };
  81633. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  81634. //parent-child relationship. Does this impostor has a parent impostor?
  81635. if (impostor.parent) {
  81636. if (impostor.physicsBody) {
  81637. this.removePhysicsBody(impostor);
  81638. //TODO is that needed?
  81639. impostor.forceUpdate();
  81640. }
  81641. return;
  81642. }
  81643. //should a new body be created for this impostor?
  81644. if (impostor.isBodyInitRequired()) {
  81645. var shape = this._createShape(impostor);
  81646. //unregister events, if body is being changed
  81647. var oldBody = impostor.physicsBody;
  81648. if (oldBody) {
  81649. this.removePhysicsBody(impostor);
  81650. }
  81651. //create the body and material
  81652. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  81653. var bodyCreationObject = {
  81654. mass: impostor.getParam("mass"),
  81655. material: material
  81656. };
  81657. // A simple extend, in case native options were used.
  81658. var nativeOptions = impostor.getParam("nativeOptions");
  81659. for (var key in nativeOptions) {
  81660. if (nativeOptions.hasOwnProperty(key)) {
  81661. bodyCreationObject[key] = nativeOptions[key];
  81662. }
  81663. }
  81664. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  81665. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  81666. this.world.addEventListener("preStep", impostor.beforeStep);
  81667. this.world.addEventListener("postStep", impostor.afterStep);
  81668. impostor.physicsBody.addShape(shape);
  81669. this.world.add(impostor.physicsBody);
  81670. //try to keep the body moving in the right direction by taking old properties.
  81671. //Should be tested!
  81672. if (oldBody) {
  81673. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  81674. impostor.physicsBody[param].copy(oldBody[param]);
  81675. });
  81676. }
  81677. this._processChildMeshes(impostor);
  81678. }
  81679. //now update the body's transformation
  81680. this._updatePhysicsBodyTransformation(impostor);
  81681. };
  81682. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  81683. var _this = this;
  81684. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  81685. var currentRotation = mainImpostor.object.rotationQuaternion;
  81686. if (meshChildren.length) {
  81687. var processMesh = function (localPosition, mesh) {
  81688. if (!currentRotation || !mesh.rotationQuaternion) {
  81689. return;
  81690. }
  81691. var childImpostor = mesh.getPhysicsImpostor();
  81692. if (childImpostor) {
  81693. var parent = childImpostor.parent;
  81694. if (parent !== mainImpostor) {
  81695. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  81696. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  81697. if (childImpostor.physicsBody) {
  81698. _this.removePhysicsBody(childImpostor);
  81699. childImpostor.physicsBody = null;
  81700. }
  81701. childImpostor.parent = mainImpostor;
  81702. childImpostor.resetUpdateFlags();
  81703. 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));
  81704. //Add the mass of the children.
  81705. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  81706. }
  81707. }
  81708. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  81709. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  81710. };
  81711. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  81712. }
  81713. };
  81714. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  81715. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  81716. this.world.removeEventListener("preStep", impostor.beforeStep);
  81717. this.world.removeEventListener("postStep", impostor.afterStep);
  81718. this.world.remove(impostor.physicsBody);
  81719. };
  81720. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  81721. var mainBody = impostorJoint.mainImpostor.physicsBody;
  81722. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  81723. if (!mainBody || !connectedBody) {
  81724. return;
  81725. }
  81726. var constraint;
  81727. var jointData = impostorJoint.joint.jointData;
  81728. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  81729. var constraintData = {
  81730. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  81731. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  81732. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  81733. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  81734. maxForce: jointData.nativeParams.maxForce,
  81735. collideConnected: !!jointData.collision
  81736. };
  81737. switch (impostorJoint.joint.type) {
  81738. case BABYLON.PhysicsJoint.HingeJoint:
  81739. case BABYLON.PhysicsJoint.Hinge2Joint:
  81740. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  81741. break;
  81742. case BABYLON.PhysicsJoint.DistanceJoint:
  81743. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  81744. break;
  81745. case BABYLON.PhysicsJoint.SpringJoint:
  81746. var springData = jointData;
  81747. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  81748. restLength: springData.length,
  81749. stiffness: springData.stiffness,
  81750. damping: springData.damping,
  81751. localAnchorA: constraintData.pivotA,
  81752. localAnchorB: constraintData.pivotB
  81753. });
  81754. break;
  81755. case BABYLON.PhysicsJoint.LockJoint:
  81756. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  81757. break;
  81758. case BABYLON.PhysicsJoint.PointToPointJoint:
  81759. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  81760. default:
  81761. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  81762. break;
  81763. }
  81764. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  81765. constraint.collideConnected = !!jointData.collision;
  81766. impostorJoint.joint.physicsJoint = constraint;
  81767. //don't add spring as constraint, as it is not one.
  81768. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  81769. this.world.addConstraint(constraint);
  81770. }
  81771. else {
  81772. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  81773. constraint.applyForce();
  81774. });
  81775. }
  81776. };
  81777. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  81778. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  81779. };
  81780. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  81781. var index;
  81782. var mat;
  81783. for (index = 0; index < this._physicsMaterials.length; index++) {
  81784. mat = this._physicsMaterials[index];
  81785. if (mat.friction === friction && mat.restitution === restitution) {
  81786. return mat;
  81787. }
  81788. }
  81789. var currentMat = new this.BJSCANNON.Material(name);
  81790. currentMat.friction = friction;
  81791. currentMat.restitution = restitution;
  81792. this._physicsMaterials.push(currentMat);
  81793. return currentMat;
  81794. };
  81795. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  81796. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  81797. };
  81798. CannonJSPlugin.prototype._createShape = function (impostor) {
  81799. var object = impostor.object;
  81800. var returnValue;
  81801. var extendSize = impostor.getObjectExtendSize();
  81802. switch (impostor.type) {
  81803. case BABYLON.PhysicsImpostor.SphereImpostor:
  81804. var radiusX = extendSize.x;
  81805. var radiusY = extendSize.y;
  81806. var radiusZ = extendSize.z;
  81807. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  81808. break;
  81809. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  81810. case BABYLON.PhysicsImpostor.CylinderImpostor:
  81811. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  81812. break;
  81813. case BABYLON.PhysicsImpostor.BoxImpostor:
  81814. var box = extendSize.scale(0.5);
  81815. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  81816. break;
  81817. case BABYLON.PhysicsImpostor.PlaneImpostor:
  81818. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  81819. returnValue = new this.BJSCANNON.Plane();
  81820. break;
  81821. case BABYLON.PhysicsImpostor.MeshImpostor:
  81822. // should transform the vertex data to world coordinates!!
  81823. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  81824. var rawFaces = object.getIndices ? object.getIndices() : [];
  81825. if (!rawVerts)
  81826. return;
  81827. // get only scale! so the object could transform correctly.
  81828. var oldPosition = object.position.clone();
  81829. var oldRotation = object.rotation && object.rotation.clone();
  81830. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  81831. object.position.copyFromFloats(0, 0, 0);
  81832. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  81833. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  81834. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  81835. var transform = object.computeWorldMatrix(true);
  81836. // convert rawVerts to object space
  81837. var temp = new Array();
  81838. var index;
  81839. for (index = 0; index < rawVerts.length; index += 3) {
  81840. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  81841. }
  81842. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  81843. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  81844. //now set back the transformation!
  81845. object.position.copyFrom(oldPosition);
  81846. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  81847. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  81848. break;
  81849. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  81850. var oldPosition2 = object.position.clone();
  81851. var oldRotation2 = object.rotation && object.rotation.clone();
  81852. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  81853. object.position.copyFromFloats(0, 0, 0);
  81854. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  81855. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  81856. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  81857. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  81858. returnValue = this._createHeightmap(object);
  81859. object.position.copyFrom(oldPosition2);
  81860. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  81861. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  81862. object.computeWorldMatrix(true);
  81863. break;
  81864. case BABYLON.PhysicsImpostor.ParticleImpostor:
  81865. returnValue = new this.BJSCANNON.Particle();
  81866. break;
  81867. }
  81868. return returnValue;
  81869. };
  81870. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  81871. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  81872. var transform = object.computeWorldMatrix(true);
  81873. // convert rawVerts to object space
  81874. var temp = new Array();
  81875. var index;
  81876. for (index = 0; index < pos.length; index += 3) {
  81877. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  81878. }
  81879. pos = temp;
  81880. var matrix = new Array();
  81881. //For now pointDepth will not be used and will be automatically calculated.
  81882. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  81883. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  81884. var boundingInfo = object.getBoundingInfo();
  81885. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  81886. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  81887. var elementSize = dim * 2 / arraySize;
  81888. for (var i = 0; i < pos.length; i = i + 3) {
  81889. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  81890. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  81891. var y = -pos[i + 2] + minY;
  81892. if (!matrix[x]) {
  81893. matrix[x] = [];
  81894. }
  81895. if (!matrix[x][z]) {
  81896. matrix[x][z] = y;
  81897. }
  81898. matrix[x][z] = Math.max(y, matrix[x][z]);
  81899. }
  81900. for (var x = 0; x <= arraySize; ++x) {
  81901. if (!matrix[x]) {
  81902. var loc = 1;
  81903. while (!matrix[(x + loc) % arraySize]) {
  81904. loc++;
  81905. }
  81906. matrix[x] = matrix[(x + loc) % arraySize].slice();
  81907. //console.log("missing x", x);
  81908. }
  81909. for (var z = 0; z <= arraySize; ++z) {
  81910. if (!matrix[x][z]) {
  81911. var loc = 1;
  81912. var newValue;
  81913. while (newValue === undefined) {
  81914. newValue = matrix[x][(z + loc++) % arraySize];
  81915. }
  81916. matrix[x][z] = newValue;
  81917. }
  81918. }
  81919. }
  81920. var shape = new this.BJSCANNON.Heightfield(matrix, {
  81921. elementSize: elementSize
  81922. });
  81923. //For future reference, needed for body transformation
  81924. shape.minY = minY;
  81925. return shape;
  81926. };
  81927. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  81928. var object = impostor.object;
  81929. //make sure it is updated...
  81930. object.computeWorldMatrix && object.computeWorldMatrix(true);
  81931. // The delta between the mesh position and the mesh bounding box center
  81932. var bInfo = object.getBoundingInfo();
  81933. if (!bInfo)
  81934. return;
  81935. var center = impostor.getObjectCenter();
  81936. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  81937. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  81938. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  81939. this._tmpPosition.copyFrom(center);
  81940. var quaternion = object.rotationQuaternion;
  81941. if (!quaternion) {
  81942. return;
  81943. }
  81944. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  81945. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  81946. //-90 DEG in X, precalculated
  81947. quaternion = quaternion.multiply(this._minus90X);
  81948. //Invert! (Precalculated, 90 deg in X)
  81949. //No need to clone. this will never change.
  81950. impostor.setDeltaRotation(this._plus90X);
  81951. }
  81952. //If it is a heightfield, if should be centered.
  81953. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  81954. var mesh = object;
  81955. var boundingInfo = mesh.getBoundingInfo();
  81956. //calculate the correct body position:
  81957. var rotationQuaternion = mesh.rotationQuaternion;
  81958. mesh.rotationQuaternion = this._tmpUnityRotation;
  81959. mesh.computeWorldMatrix(true);
  81960. //get original center with no rotation
  81961. var c = center.clone();
  81962. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  81963. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  81964. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  81965. mesh.setPreTransformMatrix(p);
  81966. mesh.computeWorldMatrix(true);
  81967. //calculate the translation
  81968. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  81969. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  81970. //add it inverted to the delta
  81971. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  81972. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  81973. //rotation is back
  81974. mesh.rotationQuaternion = rotationQuaternion;
  81975. mesh.setPreTransformMatrix(oldPivot);
  81976. mesh.computeWorldMatrix(true);
  81977. }
  81978. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  81979. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  81980. //this._tmpPosition.copyFrom(object.position);
  81981. }
  81982. impostor.setDeltaPosition(this._tmpDeltaPosition);
  81983. //Now update the impostor object
  81984. impostor.physicsBody.position.copy(this._tmpPosition);
  81985. impostor.physicsBody.quaternion.copy(quaternion);
  81986. };
  81987. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  81988. impostor.object.position.copyFrom(impostor.physicsBody.position);
  81989. if (impostor.object.rotationQuaternion) {
  81990. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  81991. }
  81992. };
  81993. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  81994. impostor.physicsBody.position.copy(newPosition);
  81995. impostor.physicsBody.quaternion.copy(newRotation);
  81996. };
  81997. CannonJSPlugin.prototype.isSupported = function () {
  81998. return this.BJSCANNON !== undefined;
  81999. };
  82000. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  82001. impostor.physicsBody.velocity.copy(velocity);
  82002. };
  82003. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  82004. impostor.physicsBody.angularVelocity.copy(velocity);
  82005. };
  82006. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  82007. var v = impostor.physicsBody.velocity;
  82008. if (!v) {
  82009. return null;
  82010. }
  82011. return new BABYLON.Vector3(v.x, v.y, v.z);
  82012. };
  82013. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  82014. var v = impostor.physicsBody.angularVelocity;
  82015. if (!v) {
  82016. return null;
  82017. }
  82018. return new BABYLON.Vector3(v.x, v.y, v.z);
  82019. };
  82020. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  82021. impostor.physicsBody.mass = mass;
  82022. impostor.physicsBody.updateMassProperties();
  82023. };
  82024. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  82025. return impostor.physicsBody.mass;
  82026. };
  82027. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  82028. return impostor.physicsBody.material.friction;
  82029. };
  82030. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  82031. impostor.physicsBody.material.friction = friction;
  82032. };
  82033. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  82034. return impostor.physicsBody.material.restitution;
  82035. };
  82036. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  82037. impostor.physicsBody.material.restitution = restitution;
  82038. };
  82039. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  82040. impostor.physicsBody.sleep();
  82041. };
  82042. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  82043. impostor.physicsBody.wakeUp();
  82044. };
  82045. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  82046. joint.physicsJoint.distance = maxDistance;
  82047. };
  82048. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  82049. // if (!motorIndex) {
  82050. // joint.physicsJoint.enableMotor();
  82051. // }
  82052. // }
  82053. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  82054. // if (!motorIndex) {
  82055. // joint.physicsJoint.disableMotor();
  82056. // }
  82057. // }
  82058. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  82059. if (!motorIndex) {
  82060. joint.physicsJoint.enableMotor();
  82061. joint.physicsJoint.setMotorSpeed(speed);
  82062. if (maxForce) {
  82063. this.setLimit(joint, maxForce);
  82064. }
  82065. }
  82066. };
  82067. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  82068. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  82069. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  82070. };
  82071. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  82072. var body = impostor.physicsBody;
  82073. mesh.position.x = body.position.x;
  82074. mesh.position.y = body.position.y;
  82075. mesh.position.z = body.position.z;
  82076. if (mesh.rotationQuaternion) {
  82077. mesh.rotationQuaternion.x = body.quaternion.x;
  82078. mesh.rotationQuaternion.y = body.quaternion.y;
  82079. mesh.rotationQuaternion.z = body.quaternion.z;
  82080. mesh.rotationQuaternion.w = body.quaternion.w;
  82081. }
  82082. };
  82083. CannonJSPlugin.prototype.getRadius = function (impostor) {
  82084. var shape = impostor.physicsBody.shapes[0];
  82085. return shape.boundingSphereRadius;
  82086. };
  82087. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  82088. var shape = impostor.physicsBody.shapes[0];
  82089. result.x = shape.halfExtents.x * 2;
  82090. result.y = shape.halfExtents.y * 2;
  82091. result.z = shape.halfExtents.z * 2;
  82092. };
  82093. CannonJSPlugin.prototype.dispose = function () {
  82094. };
  82095. CannonJSPlugin.prototype._extendNamespace = function () {
  82096. //this will force cannon to execute at least one step when using interpolation
  82097. var step_tmp1 = new this.BJSCANNON.Vec3();
  82098. var Engine = this.BJSCANNON;
  82099. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  82100. maxSubSteps = maxSubSteps || 10;
  82101. timeSinceLastCalled = timeSinceLastCalled || 0;
  82102. if (timeSinceLastCalled === 0) {
  82103. this.internalStep(dt);
  82104. this.time += dt;
  82105. }
  82106. else {
  82107. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  82108. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  82109. var t0 = performance.now();
  82110. for (var i = 0; i !== internalSteps; i++) {
  82111. this.internalStep(dt);
  82112. if (performance.now() - t0 > dt * 1000) {
  82113. break;
  82114. }
  82115. }
  82116. this.time += timeSinceLastCalled;
  82117. var h = this.time % dt;
  82118. var h_div_dt = h / dt;
  82119. var interpvelo = step_tmp1;
  82120. var bodies = this.bodies;
  82121. for (var j = 0; j !== bodies.length; j++) {
  82122. var b = bodies[j];
  82123. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  82124. b.position.vsub(b.previousPosition, interpvelo);
  82125. interpvelo.scale(h_div_dt, interpvelo);
  82126. b.position.vadd(interpvelo, b.interpolatedPosition);
  82127. }
  82128. else {
  82129. b.interpolatedPosition.copy(b.position);
  82130. b.interpolatedQuaternion.copy(b.quaternion);
  82131. }
  82132. }
  82133. }
  82134. };
  82135. };
  82136. return CannonJSPlugin;
  82137. }());
  82138. BABYLON.CannonJSPlugin = CannonJSPlugin;
  82139. })(BABYLON || (BABYLON = {}));
  82140. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  82141. "use strict";
  82142. var BABYLON;
  82143. (function (BABYLON) {
  82144. var OimoJSPlugin = /** @class */ (function () {
  82145. function OimoJSPlugin(iterations) {
  82146. this.name = "OimoJSPlugin";
  82147. this._tmpImpostorsArray = [];
  82148. this._tmpPositionVector = BABYLON.Vector3.Zero();
  82149. this.BJSOIMO = OIMO;
  82150. this.world = new this.BJSOIMO.World({
  82151. iterations: iterations
  82152. });
  82153. this.world.clear();
  82154. }
  82155. OimoJSPlugin.prototype.setGravity = function (gravity) {
  82156. this.world.gravity.copy(gravity);
  82157. };
  82158. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  82159. this.world.timeStep = timeStep;
  82160. };
  82161. OimoJSPlugin.prototype.getTimeStep = function () {
  82162. return this.world.timeStep;
  82163. };
  82164. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  82165. var _this = this;
  82166. impostors.forEach(function (impostor) {
  82167. impostor.beforeStep();
  82168. });
  82169. this.world.step();
  82170. impostors.forEach(function (impostor) {
  82171. impostor.afterStep();
  82172. //update the ordered impostors array
  82173. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  82174. });
  82175. //check for collisions
  82176. var contact = this.world.contacts;
  82177. while (contact !== null) {
  82178. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  82179. contact = contact.next;
  82180. continue;
  82181. }
  82182. //is this body colliding with any other? get the impostor
  82183. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  82184. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  82185. if (!mainImpostor || !collidingImpostor) {
  82186. contact = contact.next;
  82187. continue;
  82188. }
  82189. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  82190. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  82191. contact = contact.next;
  82192. }
  82193. };
  82194. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  82195. var mass = impostor.physicsBody.mass;
  82196. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  82197. };
  82198. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  82199. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  82200. this.applyImpulse(impostor, force, contactPoint);
  82201. };
  82202. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  82203. var _this = this;
  82204. //parent-child relationship. Does this impostor has a parent impostor?
  82205. if (impostor.parent) {
  82206. if (impostor.physicsBody) {
  82207. this.removePhysicsBody(impostor);
  82208. //TODO is that needed?
  82209. impostor.forceUpdate();
  82210. }
  82211. return;
  82212. }
  82213. if (impostor.isBodyInitRequired()) {
  82214. var bodyConfig = {
  82215. name: impostor.uniqueId,
  82216. //Oimo must have mass, also for static objects.
  82217. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  82218. size: [],
  82219. type: [],
  82220. pos: [],
  82221. posShape: [],
  82222. rot: [],
  82223. rotShape: [],
  82224. move: impostor.getParam("mass") !== 0,
  82225. density: impostor.getParam("mass"),
  82226. friction: impostor.getParam("friction"),
  82227. restitution: impostor.getParam("restitution"),
  82228. //Supporting older versions of Oimo
  82229. world: this.world
  82230. };
  82231. var impostors = [impostor];
  82232. var addToArray = function (parent) {
  82233. if (!parent.getChildMeshes)
  82234. return;
  82235. parent.getChildMeshes().forEach(function (m) {
  82236. if (m.physicsImpostor) {
  82237. impostors.push(m.physicsImpostor);
  82238. //m.physicsImpostor._init();
  82239. }
  82240. });
  82241. };
  82242. addToArray(impostor.object);
  82243. var checkWithEpsilon_1 = function (value) {
  82244. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  82245. };
  82246. impostors.forEach(function (i) {
  82247. if (!i.object.rotationQuaternion) {
  82248. return;
  82249. }
  82250. //get the correct bounding box
  82251. var oldQuaternion = i.object.rotationQuaternion;
  82252. var rot = oldQuaternion.toEulerAngles();
  82253. var extendSize = i.getObjectExtendSize();
  82254. var radToDeg = 57.295779513082320876;
  82255. if (i === impostor) {
  82256. var center = impostor.getObjectCenter();
  82257. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  82258. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  82259. //Can also use Array.prototype.push.apply
  82260. bodyConfig.pos.push(center.x);
  82261. bodyConfig.pos.push(center.y);
  82262. bodyConfig.pos.push(center.z);
  82263. bodyConfig.posShape.push(0, 0, 0);
  82264. //tmp solution
  82265. bodyConfig.rot.push(rot.x * radToDeg);
  82266. bodyConfig.rot.push(rot.y * radToDeg);
  82267. bodyConfig.rot.push(rot.z * radToDeg);
  82268. bodyConfig.rotShape.push(0, 0, 0);
  82269. }
  82270. else {
  82271. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  82272. bodyConfig.posShape.push(localPosition.x);
  82273. bodyConfig.posShape.push(localPosition.y);
  82274. bodyConfig.posShape.push(localPosition.z);
  82275. bodyConfig.pos.push(0, 0, 0);
  82276. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  82277. bodyConfig.rot.push(0);
  82278. bodyConfig.rot.push(0);
  82279. bodyConfig.rot.push(0);
  82280. bodyConfig.rotShape.push(rot.x * radToDeg);
  82281. bodyConfig.rotShape.push(rot.y * radToDeg);
  82282. bodyConfig.rotShape.push(rot.z * radToDeg);
  82283. }
  82284. // register mesh
  82285. switch (i.type) {
  82286. case BABYLON.PhysicsImpostor.ParticleImpostor:
  82287. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  82288. case BABYLON.PhysicsImpostor.SphereImpostor:
  82289. var radiusX = extendSize.x;
  82290. var radiusY = extendSize.y;
  82291. var radiusZ = extendSize.z;
  82292. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  82293. bodyConfig.type.push('sphere');
  82294. //due to the way oimo works with compounds, add 3 times
  82295. bodyConfig.size.push(size);
  82296. bodyConfig.size.push(size);
  82297. bodyConfig.size.push(size);
  82298. break;
  82299. case BABYLON.PhysicsImpostor.CylinderImpostor:
  82300. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  82301. var sizeY = checkWithEpsilon_1(extendSize.y);
  82302. bodyConfig.type.push('cylinder');
  82303. bodyConfig.size.push(sizeX);
  82304. bodyConfig.size.push(sizeY);
  82305. //due to the way oimo works with compounds, add one more value.
  82306. bodyConfig.size.push(sizeY);
  82307. break;
  82308. case BABYLON.PhysicsImpostor.PlaneImpostor:
  82309. case BABYLON.PhysicsImpostor.BoxImpostor:
  82310. default:
  82311. var sizeX = checkWithEpsilon_1(extendSize.x);
  82312. var sizeY = checkWithEpsilon_1(extendSize.y);
  82313. var sizeZ = checkWithEpsilon_1(extendSize.z);
  82314. bodyConfig.type.push('box');
  82315. //if (i === impostor) {
  82316. bodyConfig.size.push(sizeX);
  82317. bodyConfig.size.push(sizeY);
  82318. bodyConfig.size.push(sizeZ);
  82319. //} else {
  82320. // bodyConfig.size.push(0,0,0);
  82321. //}
  82322. break;
  82323. }
  82324. //actually not needed, but hey...
  82325. i.object.rotationQuaternion = oldQuaternion;
  82326. });
  82327. impostor.physicsBody = this.world.add(bodyConfig);
  82328. }
  82329. else {
  82330. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  82331. }
  82332. impostor.setDeltaPosition(this._tmpPositionVector);
  82333. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  82334. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  82335. };
  82336. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  82337. //impostor.physicsBody.dispose();
  82338. //Same as : (older oimo versions)
  82339. this.world.removeRigidBody(impostor.physicsBody);
  82340. };
  82341. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  82342. var mainBody = impostorJoint.mainImpostor.physicsBody;
  82343. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  82344. if (!mainBody || !connectedBody) {
  82345. return;
  82346. }
  82347. var jointData = impostorJoint.joint.jointData;
  82348. var options = jointData.nativeParams || {};
  82349. var type;
  82350. var nativeJointData = {
  82351. body1: mainBody,
  82352. body2: connectedBody,
  82353. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  82354. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  82355. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  82356. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  82357. min: options.min,
  82358. max: options.max,
  82359. collision: options.collision || jointData.collision,
  82360. spring: options.spring,
  82361. //supporting older version of Oimo
  82362. world: this.world
  82363. };
  82364. switch (impostorJoint.joint.type) {
  82365. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  82366. type = "jointBall";
  82367. break;
  82368. case BABYLON.PhysicsJoint.SpringJoint:
  82369. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  82370. var springData = jointData;
  82371. nativeJointData.min = springData.length || nativeJointData.min;
  82372. //Max should also be set, just make sure it is at least min
  82373. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  82374. case BABYLON.PhysicsJoint.DistanceJoint:
  82375. type = "jointDistance";
  82376. nativeJointData.max = jointData.maxDistance;
  82377. break;
  82378. case BABYLON.PhysicsJoint.PrismaticJoint:
  82379. type = "jointPrisme";
  82380. break;
  82381. case BABYLON.PhysicsJoint.SliderJoint:
  82382. type = "jointSlide";
  82383. break;
  82384. case BABYLON.PhysicsJoint.WheelJoint:
  82385. type = "jointWheel";
  82386. break;
  82387. case BABYLON.PhysicsJoint.HingeJoint:
  82388. default:
  82389. type = "jointHinge";
  82390. break;
  82391. }
  82392. nativeJointData.type = type;
  82393. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  82394. };
  82395. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  82396. //Bug in Oimo prevents us from disposing a joint in the playground
  82397. //joint.joint.physicsJoint.dispose();
  82398. //So we will bruteforce it!
  82399. try {
  82400. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  82401. }
  82402. catch (e) {
  82403. BABYLON.Tools.Warn(e);
  82404. }
  82405. };
  82406. OimoJSPlugin.prototype.isSupported = function () {
  82407. return this.BJSOIMO !== undefined;
  82408. };
  82409. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  82410. if (!impostor.physicsBody.sleeping) {
  82411. //TODO check that
  82412. /*if (impostor.physicsBody.shapes.next) {
  82413. var parentShape = this._getLastShape(impostor.physicsBody);
  82414. impostor.object.position.copyFrom(parentShape.position);
  82415. console.log(parentShape.position);
  82416. } else {*/
  82417. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  82418. //}
  82419. if (impostor.object.rotationQuaternion) {
  82420. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  82421. }
  82422. }
  82423. };
  82424. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  82425. var body = impostor.physicsBody;
  82426. body.position.copy(newPosition);
  82427. body.orientation.copy(newRotation);
  82428. body.syncShapes();
  82429. body.awake();
  82430. };
  82431. /*private _getLastShape(body: any): any {
  82432. var lastShape = body.shapes;
  82433. while (lastShape.next) {
  82434. lastShape = lastShape.next;
  82435. }
  82436. return lastShape;
  82437. }*/
  82438. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  82439. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  82440. };
  82441. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  82442. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  82443. };
  82444. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  82445. var v = impostor.physicsBody.linearVelocity;
  82446. if (!v) {
  82447. return null;
  82448. }
  82449. return new BABYLON.Vector3(v.x, v.y, v.z);
  82450. };
  82451. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  82452. var v = impostor.physicsBody.angularVelocity;
  82453. if (!v) {
  82454. return null;
  82455. }
  82456. return new BABYLON.Vector3(v.x, v.y, v.z);
  82457. };
  82458. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  82459. var staticBody = mass === 0;
  82460. //this will actually set the body's density and not its mass.
  82461. //But this is how oimo treats the mass variable.
  82462. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  82463. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  82464. };
  82465. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  82466. return impostor.physicsBody.shapes.density;
  82467. };
  82468. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  82469. return impostor.physicsBody.shapes.friction;
  82470. };
  82471. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  82472. impostor.physicsBody.shapes.friction = friction;
  82473. };
  82474. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  82475. return impostor.physicsBody.shapes.restitution;
  82476. };
  82477. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  82478. impostor.physicsBody.shapes.restitution = restitution;
  82479. };
  82480. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  82481. impostor.physicsBody.sleep();
  82482. };
  82483. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  82484. impostor.physicsBody.awake();
  82485. };
  82486. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  82487. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  82488. if (minDistance !== void 0) {
  82489. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  82490. }
  82491. };
  82492. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  82493. //TODO separate rotational and transational motors.
  82494. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  82495. if (motor) {
  82496. motor.setMotor(speed, maxForce);
  82497. }
  82498. };
  82499. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  82500. //TODO separate rotational and transational motors.
  82501. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  82502. if (motor) {
  82503. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  82504. }
  82505. };
  82506. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  82507. var body = impostor.physicsBody;
  82508. mesh.position.x = body.position.x;
  82509. mesh.position.y = body.position.y;
  82510. mesh.position.z = body.position.z;
  82511. if (mesh.rotationQuaternion) {
  82512. mesh.rotationQuaternion.x = body.orientation.x;
  82513. mesh.rotationQuaternion.y = body.orientation.y;
  82514. mesh.rotationQuaternion.z = body.orientation.z;
  82515. mesh.rotationQuaternion.w = body.orientation.s;
  82516. }
  82517. };
  82518. OimoJSPlugin.prototype.getRadius = function (impostor) {
  82519. return impostor.physicsBody.shapes.radius;
  82520. };
  82521. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  82522. var shape = impostor.physicsBody.shapes;
  82523. result.x = shape.halfWidth * 2;
  82524. result.y = shape.halfHeight * 2;
  82525. result.z = shape.halfDepth * 2;
  82526. };
  82527. OimoJSPlugin.prototype.dispose = function () {
  82528. this.world.clear();
  82529. };
  82530. return OimoJSPlugin;
  82531. }());
  82532. BABYLON.OimoJSPlugin = OimoJSPlugin;
  82533. })(BABYLON || (BABYLON = {}));
  82534. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  82535. "use strict";
  82536. var BABYLON;
  82537. (function (BABYLON) {
  82538. /*
  82539. * Based on jsTGALoader - Javascript loader for TGA file
  82540. * By Vincent Thibault
  82541. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  82542. */
  82543. var TGATools = /** @class */ (function () {
  82544. function TGATools() {
  82545. }
  82546. TGATools.GetTGAHeader = function (data) {
  82547. var offset = 0;
  82548. var header = {
  82549. id_length: data[offset++],
  82550. colormap_type: data[offset++],
  82551. image_type: data[offset++],
  82552. colormap_index: data[offset++] | data[offset++] << 8,
  82553. colormap_length: data[offset++] | data[offset++] << 8,
  82554. colormap_size: data[offset++],
  82555. origin: [
  82556. data[offset++] | data[offset++] << 8,
  82557. data[offset++] | data[offset++] << 8
  82558. ],
  82559. width: data[offset++] | data[offset++] << 8,
  82560. height: data[offset++] | data[offset++] << 8,
  82561. pixel_size: data[offset++],
  82562. flags: data[offset++]
  82563. };
  82564. return header;
  82565. };
  82566. TGATools.UploadContent = function (gl, data) {
  82567. // Not enough data to contain header ?
  82568. if (data.length < 19) {
  82569. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  82570. return;
  82571. }
  82572. // Read Header
  82573. var offset = 18;
  82574. var header = TGATools.GetTGAHeader(data);
  82575. // Assume it's a valid Targa file.
  82576. if (header.id_length + offset > data.length) {
  82577. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  82578. return;
  82579. }
  82580. // Skip not needed data
  82581. offset += header.id_length;
  82582. var use_rle = false;
  82583. var use_pal = false;
  82584. var use_grey = false;
  82585. // Get some informations.
  82586. switch (header.image_type) {
  82587. case TGATools._TYPE_RLE_INDEXED:
  82588. use_rle = true;
  82589. case TGATools._TYPE_INDEXED:
  82590. use_pal = true;
  82591. break;
  82592. case TGATools._TYPE_RLE_RGB:
  82593. use_rle = true;
  82594. case TGATools._TYPE_RGB:
  82595. // use_rgb = true;
  82596. break;
  82597. case TGATools._TYPE_RLE_GREY:
  82598. use_rle = true;
  82599. case TGATools._TYPE_GREY:
  82600. use_grey = true;
  82601. break;
  82602. }
  82603. var pixel_data;
  82604. // var numAlphaBits = header.flags & 0xf;
  82605. var pixel_size = header.pixel_size >> 3;
  82606. var pixel_total = header.width * header.height * pixel_size;
  82607. // Read palettes
  82608. var palettes;
  82609. if (use_pal) {
  82610. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  82611. }
  82612. // Read LRE
  82613. if (use_rle) {
  82614. pixel_data = new Uint8Array(pixel_total);
  82615. var c, count, i;
  82616. var localOffset = 0;
  82617. var pixels = new Uint8Array(pixel_size);
  82618. while (offset < pixel_total && localOffset < pixel_total) {
  82619. c = data[offset++];
  82620. count = (c & 0x7f) + 1;
  82621. // RLE pixels
  82622. if (c & 0x80) {
  82623. // Bind pixel tmp array
  82624. for (i = 0; i < pixel_size; ++i) {
  82625. pixels[i] = data[offset++];
  82626. }
  82627. // Copy pixel array
  82628. for (i = 0; i < count; ++i) {
  82629. pixel_data.set(pixels, localOffset + i * pixel_size);
  82630. }
  82631. localOffset += pixel_size * count;
  82632. }
  82633. else {
  82634. count *= pixel_size;
  82635. for (i = 0; i < count; ++i) {
  82636. pixel_data[localOffset + i] = data[offset++];
  82637. }
  82638. localOffset += count;
  82639. }
  82640. }
  82641. }
  82642. else {
  82643. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  82644. }
  82645. // Load to texture
  82646. var x_start, y_start, x_step, y_step, y_end, x_end;
  82647. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  82648. default:
  82649. case TGATools._ORIGIN_UL:
  82650. x_start = 0;
  82651. x_step = 1;
  82652. x_end = header.width;
  82653. y_start = 0;
  82654. y_step = 1;
  82655. y_end = header.height;
  82656. break;
  82657. case TGATools._ORIGIN_BL:
  82658. x_start = 0;
  82659. x_step = 1;
  82660. x_end = header.width;
  82661. y_start = header.height - 1;
  82662. y_step = -1;
  82663. y_end = -1;
  82664. break;
  82665. case TGATools._ORIGIN_UR:
  82666. x_start = header.width - 1;
  82667. x_step = -1;
  82668. x_end = -1;
  82669. y_start = 0;
  82670. y_step = 1;
  82671. y_end = header.height;
  82672. break;
  82673. case TGATools._ORIGIN_BR:
  82674. x_start = header.width - 1;
  82675. x_step = -1;
  82676. x_end = -1;
  82677. y_start = header.height - 1;
  82678. y_step = -1;
  82679. y_end = -1;
  82680. break;
  82681. }
  82682. // Load the specify method
  82683. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  82684. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  82685. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  82686. };
  82687. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82688. var image = pixel_data, colormap = palettes;
  82689. var width = header.width, height = header.height;
  82690. var color, i = 0, x, y;
  82691. var imageData = new Uint8Array(width * height * 4);
  82692. for (y = y_start; y !== y_end; y += y_step) {
  82693. for (x = x_start; x !== x_end; x += x_step, i++) {
  82694. color = image[i];
  82695. imageData[(x + width * y) * 4 + 3] = 255;
  82696. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  82697. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  82698. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  82699. }
  82700. }
  82701. return imageData;
  82702. };
  82703. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82704. var image = pixel_data;
  82705. var width = header.width, height = header.height;
  82706. var color, i = 0, x, y;
  82707. var imageData = new Uint8Array(width * height * 4);
  82708. for (y = y_start; y !== y_end; y += y_step) {
  82709. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  82710. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  82711. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  82712. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  82713. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  82714. imageData[(x + width * y) * 4 + 0] = r;
  82715. imageData[(x + width * y) * 4 + 1] = g;
  82716. imageData[(x + width * y) * 4 + 2] = b;
  82717. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  82718. }
  82719. }
  82720. return imageData;
  82721. };
  82722. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82723. var image = pixel_data;
  82724. var width = header.width, height = header.height;
  82725. var i = 0, x, y;
  82726. var imageData = new Uint8Array(width * height * 4);
  82727. for (y = y_start; y !== y_end; y += y_step) {
  82728. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  82729. imageData[(x + width * y) * 4 + 3] = 255;
  82730. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  82731. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  82732. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  82733. }
  82734. }
  82735. return imageData;
  82736. };
  82737. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82738. var image = pixel_data;
  82739. var width = header.width, height = header.height;
  82740. var i = 0, x, y;
  82741. var imageData = new Uint8Array(width * height * 4);
  82742. for (y = y_start; y !== y_end; y += y_step) {
  82743. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  82744. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  82745. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  82746. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  82747. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  82748. }
  82749. }
  82750. return imageData;
  82751. };
  82752. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82753. var image = pixel_data;
  82754. var width = header.width, height = header.height;
  82755. var color, i = 0, x, y;
  82756. var imageData = new Uint8Array(width * height * 4);
  82757. for (y = y_start; y !== y_end; y += y_step) {
  82758. for (x = x_start; x !== x_end; x += x_step, i++) {
  82759. color = image[i];
  82760. imageData[(x + width * y) * 4 + 0] = color;
  82761. imageData[(x + width * y) * 4 + 1] = color;
  82762. imageData[(x + width * y) * 4 + 2] = color;
  82763. imageData[(x + width * y) * 4 + 3] = 255;
  82764. }
  82765. }
  82766. return imageData;
  82767. };
  82768. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82769. var image = pixel_data;
  82770. var width = header.width, height = header.height;
  82771. var i = 0, x, y;
  82772. var imageData = new Uint8Array(width * height * 4);
  82773. for (y = y_start; y !== y_end; y += y_step) {
  82774. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  82775. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  82776. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  82777. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  82778. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  82779. }
  82780. }
  82781. return imageData;
  82782. };
  82783. //private static _TYPE_NO_DATA = 0;
  82784. TGATools._TYPE_INDEXED = 1;
  82785. TGATools._TYPE_RGB = 2;
  82786. TGATools._TYPE_GREY = 3;
  82787. TGATools._TYPE_RLE_INDEXED = 9;
  82788. TGATools._TYPE_RLE_RGB = 10;
  82789. TGATools._TYPE_RLE_GREY = 11;
  82790. TGATools._ORIGIN_MASK = 0x30;
  82791. TGATools._ORIGIN_SHIFT = 0x04;
  82792. TGATools._ORIGIN_BL = 0x00;
  82793. TGATools._ORIGIN_BR = 0x01;
  82794. TGATools._ORIGIN_UL = 0x02;
  82795. TGATools._ORIGIN_UR = 0x03;
  82796. return TGATools;
  82797. }());
  82798. BABYLON.TGATools = TGATools;
  82799. })(BABYLON || (BABYLON = {}));
  82800. //# sourceMappingURL=babylon.tga.js.map
  82801. "use strict";
  82802. var BABYLON;
  82803. (function (BABYLON) {
  82804. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  82805. // All values and structures referenced from:
  82806. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  82807. var DDS_MAGIC = 0x20534444;
  82808. var
  82809. //DDSD_CAPS = 0x1,
  82810. //DDSD_HEIGHT = 0x2,
  82811. //DDSD_WIDTH = 0x4,
  82812. //DDSD_PITCH = 0x8,
  82813. //DDSD_PIXELFORMAT = 0x1000,
  82814. DDSD_MIPMAPCOUNT = 0x20000;
  82815. //DDSD_LINEARSIZE = 0x80000,
  82816. //DDSD_DEPTH = 0x800000;
  82817. // var DDSCAPS_COMPLEX = 0x8,
  82818. // DDSCAPS_MIPMAP = 0x400000,
  82819. // DDSCAPS_TEXTURE = 0x1000;
  82820. var DDSCAPS2_CUBEMAP = 0x200;
  82821. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  82822. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  82823. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  82824. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  82825. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  82826. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  82827. // DDSCAPS2_VOLUME = 0x200000;
  82828. var
  82829. //DDPF_ALPHAPIXELS = 0x1,
  82830. //DDPF_ALPHA = 0x2,
  82831. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  82832. //DDPF_YUV = 0x200,
  82833. DDPF_LUMINANCE = 0x20000;
  82834. function FourCCToInt32(value) {
  82835. return value.charCodeAt(0) +
  82836. (value.charCodeAt(1) << 8) +
  82837. (value.charCodeAt(2) << 16) +
  82838. (value.charCodeAt(3) << 24);
  82839. }
  82840. function Int32ToFourCC(value) {
  82841. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  82842. }
  82843. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  82844. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  82845. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  82846. var FOURCC_DX10 = FourCCToInt32("DX10");
  82847. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  82848. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  82849. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  82850. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  82851. var headerLengthInt = 31; // The header length in 32 bit ints
  82852. // Offsets into the header array
  82853. var off_magic = 0;
  82854. var off_size = 1;
  82855. var off_flags = 2;
  82856. var off_height = 3;
  82857. var off_width = 4;
  82858. var off_mipmapCount = 7;
  82859. var off_pfFlags = 20;
  82860. var off_pfFourCC = 21;
  82861. var off_RGBbpp = 22;
  82862. var off_RMask = 23;
  82863. var off_GMask = 24;
  82864. var off_BMask = 25;
  82865. var off_AMask = 26;
  82866. // var off_caps1 = 27;
  82867. var off_caps2 = 28;
  82868. // var off_caps3 = 29;
  82869. // var off_caps4 = 30;
  82870. var off_dxgiFormat = 32;
  82871. ;
  82872. var DDSTools = /** @class */ (function () {
  82873. function DDSTools() {
  82874. }
  82875. DDSTools.GetDDSInfo = function (arrayBuffer) {
  82876. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  82877. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  82878. var mipmapCount = 1;
  82879. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  82880. mipmapCount = Math.max(1, header[off_mipmapCount]);
  82881. }
  82882. var fourCC = header[off_pfFourCC];
  82883. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  82884. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82885. switch (fourCC) {
  82886. case FOURCC_D3DFMT_R16G16B16A16F:
  82887. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82888. break;
  82889. case FOURCC_D3DFMT_R32G32B32A32F:
  82890. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82891. break;
  82892. case FOURCC_DX10:
  82893. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  82894. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82895. break;
  82896. }
  82897. }
  82898. return {
  82899. width: header[off_width],
  82900. height: header[off_height],
  82901. mipmapCount: mipmapCount,
  82902. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  82903. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  82904. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  82905. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  82906. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  82907. dxgiFormat: dxgiFormat,
  82908. textureType: textureType
  82909. };
  82910. };
  82911. DDSTools._ToHalfFloat = function (value) {
  82912. if (!DDSTools._FloatView) {
  82913. DDSTools._FloatView = new Float32Array(1);
  82914. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  82915. }
  82916. DDSTools._FloatView[0] = value;
  82917. var x = DDSTools._Int32View[0];
  82918. var bits = (x >> 16) & 0x8000; /* Get the sign */
  82919. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  82920. var e = (x >> 23) & 0xff; /* Using int is faster here */
  82921. /* If zero, or denormal, or exponent underflows too much for a denormal
  82922. * half, return signed zero. */
  82923. if (e < 103) {
  82924. return bits;
  82925. }
  82926. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  82927. if (e > 142) {
  82928. bits |= 0x7c00;
  82929. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  82930. * not Inf, so make sure we set one mantissa bit too. */
  82931. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  82932. return bits;
  82933. }
  82934. /* If exponent underflows but not too much, return a denormal */
  82935. if (e < 113) {
  82936. m |= 0x0800;
  82937. /* Extra rounding may overflow and set mantissa to 0 and exponent
  82938. * to 1, which is OK. */
  82939. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  82940. return bits;
  82941. }
  82942. bits |= ((e - 112) << 10) | (m >> 1);
  82943. bits += m & 1;
  82944. return bits;
  82945. };
  82946. DDSTools._FromHalfFloat = function (value) {
  82947. var s = (value & 0x8000) >> 15;
  82948. var e = (value & 0x7C00) >> 10;
  82949. var f = value & 0x03FF;
  82950. if (e === 0) {
  82951. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  82952. }
  82953. else if (e == 0x1F) {
  82954. return f ? NaN : ((s ? -1 : 1) * Infinity);
  82955. }
  82956. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  82957. };
  82958. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82959. var destArray = new Float32Array(dataLength);
  82960. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  82961. var index = 0;
  82962. for (var y = 0; y < height; y++) {
  82963. for (var x = 0; x < width; x++) {
  82964. var srcPos = (x + y * width) * 4;
  82965. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  82966. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  82967. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  82968. if (DDSTools.StoreLODInAlphaChannel) {
  82969. destArray[index + 3] = lod;
  82970. }
  82971. else {
  82972. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  82973. }
  82974. index += 4;
  82975. }
  82976. }
  82977. return destArray;
  82978. };
  82979. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82980. if (DDSTools.StoreLODInAlphaChannel) {
  82981. var destArray = new Uint16Array(dataLength);
  82982. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  82983. var index = 0;
  82984. for (var y = 0; y < height; y++) {
  82985. for (var x = 0; x < width; x++) {
  82986. var srcPos = (x + y * width) * 4;
  82987. destArray[index] = srcData[srcPos];
  82988. destArray[index + 1] = srcData[srcPos + 1];
  82989. destArray[index + 2] = srcData[srcPos + 2];
  82990. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  82991. index += 4;
  82992. }
  82993. }
  82994. return destArray;
  82995. }
  82996. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  82997. };
  82998. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82999. if (DDSTools.StoreLODInAlphaChannel) {
  83000. var destArray = new Float32Array(dataLength);
  83001. var srcData = new Float32Array(arrayBuffer, dataOffset);
  83002. var index = 0;
  83003. for (var y = 0; y < height; y++) {
  83004. for (var x = 0; x < width; x++) {
  83005. var srcPos = (x + y * width) * 4;
  83006. destArray[index] = srcData[srcPos];
  83007. destArray[index + 1] = srcData[srcPos + 1];
  83008. destArray[index + 2] = srcData[srcPos + 2];
  83009. destArray[index + 3] = lod;
  83010. index += 4;
  83011. }
  83012. }
  83013. return destArray;
  83014. }
  83015. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  83016. };
  83017. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83018. var destArray = new Uint8Array(dataLength);
  83019. var srcData = new Float32Array(arrayBuffer, dataOffset);
  83020. var index = 0;
  83021. for (var y = 0; y < height; y++) {
  83022. for (var x = 0; x < width; x++) {
  83023. var srcPos = (x + y * width) * 4;
  83024. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  83025. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  83026. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  83027. if (DDSTools.StoreLODInAlphaChannel) {
  83028. destArray[index + 3] = lod;
  83029. }
  83030. else {
  83031. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  83032. }
  83033. index += 4;
  83034. }
  83035. }
  83036. return destArray;
  83037. };
  83038. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83039. var destArray = new Uint8Array(dataLength);
  83040. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83041. var index = 0;
  83042. for (var y = 0; y < height; y++) {
  83043. for (var x = 0; x < width; x++) {
  83044. var srcPos = (x + y * width) * 4;
  83045. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  83046. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  83047. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  83048. if (DDSTools.StoreLODInAlphaChannel) {
  83049. destArray[index + 3] = lod;
  83050. }
  83051. else {
  83052. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  83053. }
  83054. index += 4;
  83055. }
  83056. }
  83057. return destArray;
  83058. };
  83059. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  83060. var byteArray = new Uint8Array(dataLength);
  83061. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  83062. var index = 0;
  83063. for (var y = 0; y < height; y++) {
  83064. for (var x = 0; x < width; x++) {
  83065. var srcPos = (x + y * width) * 4;
  83066. byteArray[index] = srcData[srcPos + rOffset];
  83067. byteArray[index + 1] = srcData[srcPos + gOffset];
  83068. byteArray[index + 2] = srcData[srcPos + bOffset];
  83069. byteArray[index + 3] = srcData[srcPos + aOffset];
  83070. index += 4;
  83071. }
  83072. }
  83073. return byteArray;
  83074. };
  83075. DDSTools._ExtractLongWordOrder = function (value) {
  83076. if (value === 0 || value === 255 || value === -16777216) {
  83077. return 0;
  83078. }
  83079. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  83080. };
  83081. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  83082. var byteArray = new Uint8Array(dataLength);
  83083. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  83084. var index = 0;
  83085. for (var y = 0; y < height; y++) {
  83086. for (var x = 0; x < width; x++) {
  83087. var srcPos = (x + y * width) * 3;
  83088. byteArray[index] = srcData[srcPos + rOffset];
  83089. byteArray[index + 1] = srcData[srcPos + gOffset];
  83090. byteArray[index + 2] = srcData[srcPos + bOffset];
  83091. index += 3;
  83092. }
  83093. }
  83094. return byteArray;
  83095. };
  83096. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  83097. var byteArray = new Uint8Array(dataLength);
  83098. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  83099. var index = 0;
  83100. for (var y = 0; y < height; y++) {
  83101. for (var x = 0; x < width; x++) {
  83102. var srcPos = (x + y * width);
  83103. byteArray[index] = srcData[srcPos];
  83104. index++;
  83105. }
  83106. }
  83107. return byteArray;
  83108. };
  83109. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  83110. if (lodIndex === void 0) { lodIndex = -1; }
  83111. var ext = engine.getCaps().s3tc;
  83112. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  83113. var fourCC, width, height, dataLength = 0, dataOffset;
  83114. var byteArray, mipmapCount, mip;
  83115. var internalFormat = 0;
  83116. var format = 0;
  83117. var blockBytes = 1;
  83118. if (header[off_magic] !== DDS_MAGIC) {
  83119. BABYLON.Tools.Error("Invalid magic number in DDS header");
  83120. return;
  83121. }
  83122. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  83123. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  83124. return;
  83125. }
  83126. if (info.isCompressed && !ext) {
  83127. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  83128. return;
  83129. }
  83130. var bpp = header[off_RGBbpp];
  83131. dataOffset = header[off_size] + 4;
  83132. var computeFormats = false;
  83133. if (info.isFourCC) {
  83134. fourCC = header[off_pfFourCC];
  83135. switch (fourCC) {
  83136. case FOURCC_DXT1:
  83137. blockBytes = 8;
  83138. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  83139. break;
  83140. case FOURCC_DXT3:
  83141. blockBytes = 16;
  83142. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  83143. break;
  83144. case FOURCC_DXT5:
  83145. blockBytes = 16;
  83146. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  83147. break;
  83148. case FOURCC_D3DFMT_R16G16B16A16F:
  83149. computeFormats = true;
  83150. break;
  83151. case FOURCC_D3DFMT_R32G32B32A32F:
  83152. computeFormats = true;
  83153. break;
  83154. case FOURCC_DX10:
  83155. // There is an additionnal header so dataOffset need to be changed
  83156. dataOffset += 5 * 4; // 5 uints
  83157. var supported = false;
  83158. switch (info.dxgiFormat) {
  83159. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  83160. computeFormats = true;
  83161. supported = true;
  83162. break;
  83163. case DXGI_FORMAT_B8G8R8X8_UNORM:
  83164. info.isRGB = true;
  83165. info.isFourCC = false;
  83166. bpp = 32;
  83167. supported = true;
  83168. break;
  83169. }
  83170. if (supported) {
  83171. break;
  83172. }
  83173. default:
  83174. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  83175. return;
  83176. }
  83177. }
  83178. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  83179. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  83180. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  83181. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  83182. if (computeFormats) {
  83183. format = engine._getWebGLTextureType(info.textureType);
  83184. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  83185. }
  83186. mipmapCount = 1;
  83187. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  83188. mipmapCount = Math.max(1, header[off_mipmapCount]);
  83189. }
  83190. for (var face = 0; face < faces; face++) {
  83191. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  83192. width = header[off_width];
  83193. height = header[off_height];
  83194. for (mip = 0; mip < mipmapCount; ++mip) {
  83195. if (lodIndex === -1 || lodIndex === mip) {
  83196. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  83197. var i = (lodIndex === -1) ? mip : 0;
  83198. if (!info.isCompressed && info.isFourCC) {
  83199. dataLength = width * height * 4;
  83200. var floatArray = null;
  83201. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  83202. if (bpp === 128) {
  83203. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83204. }
  83205. else if (bpp === 64) {
  83206. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83207. }
  83208. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83209. format = engine._getWebGLTextureType(info.textureType);
  83210. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  83211. }
  83212. else {
  83213. if (bpp === 128) {
  83214. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83215. }
  83216. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  83217. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83218. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83219. format = engine._getWebGLTextureType(info.textureType);
  83220. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  83221. }
  83222. else {
  83223. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83224. }
  83225. }
  83226. if (floatArray) {
  83227. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  83228. }
  83229. }
  83230. else if (info.isRGB) {
  83231. if (bpp === 24) {
  83232. dataLength = width * height * 3;
  83233. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  83234. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  83235. }
  83236. else {
  83237. dataLength = width * height * 4;
  83238. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  83239. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  83240. }
  83241. }
  83242. else if (info.isLuminance) {
  83243. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  83244. var unpaddedRowSize = width;
  83245. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  83246. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  83247. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  83248. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  83249. }
  83250. else {
  83251. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  83252. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  83253. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  83254. }
  83255. }
  83256. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  83257. width *= 0.5;
  83258. height *= 0.5;
  83259. width = Math.max(1.0, width);
  83260. height = Math.max(1.0, height);
  83261. }
  83262. if (currentFace !== undefined) {
  83263. // Loading a single face
  83264. break;
  83265. }
  83266. }
  83267. };
  83268. DDSTools.StoreLODInAlphaChannel = false;
  83269. return DDSTools;
  83270. }());
  83271. BABYLON.DDSTools = DDSTools;
  83272. })(BABYLON || (BABYLON = {}));
  83273. //# sourceMappingURL=babylon.dds.js.map
  83274. "use strict";
  83275. var BABYLON;
  83276. (function (BABYLON) {
  83277. /**
  83278. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  83279. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  83280. */
  83281. var KhronosTextureContainer = /** @class */ (function () {
  83282. /**
  83283. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  83284. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  83285. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  83286. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  83287. */
  83288. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  83289. this.arrayBuffer = arrayBuffer;
  83290. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  83291. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  83292. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  83293. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  83294. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  83295. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  83296. BABYLON.Tools.Error("texture missing KTX identifier");
  83297. return;
  83298. }
  83299. // load the reset of the header in native 32 bit int
  83300. var header = new Int32Array(this.arrayBuffer, 12, 13);
  83301. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  83302. var oppositeEndianess = header[0] === 0x01020304;
  83303. // read all the header elements in order they exist in the file, without modification (sans endainness)
  83304. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  83305. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  83306. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  83307. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  83308. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  83309. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  83310. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  83311. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  83312. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  83313. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  83314. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  83315. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  83316. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  83317. if (this.glType !== 0) {
  83318. BABYLON.Tools.Error("only compressed formats currently supported");
  83319. return;
  83320. }
  83321. else {
  83322. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  83323. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  83324. }
  83325. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  83326. BABYLON.Tools.Error("only 2D textures currently supported");
  83327. return;
  83328. }
  83329. if (this.numberOfArrayElements !== 0) {
  83330. BABYLON.Tools.Error("texture arrays not currently supported");
  83331. return;
  83332. }
  83333. if (this.numberOfFaces !== facesExpected) {
  83334. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  83335. return;
  83336. }
  83337. // we now have a completely validated file, so could use existence of loadType as success
  83338. // would need to make this more elaborate & adjust checks above to support more than one load type
  83339. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  83340. }
  83341. // not as fast hardware based, but will probably never need to use
  83342. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  83343. return ((val & 0xFF) << 24)
  83344. | ((val & 0xFF00) << 8)
  83345. | ((val >> 8) & 0xFF00)
  83346. | ((val >> 24) & 0xFF);
  83347. };
  83348. /**
  83349. * It is assumed that the texture has already been created & is currently bound
  83350. */
  83351. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  83352. switch (this.loadType) {
  83353. case KhronosTextureContainer.COMPRESSED_2D:
  83354. this._upload2DCompressedLevels(gl, loadMipmaps);
  83355. break;
  83356. case KhronosTextureContainer.TEX_2D:
  83357. case KhronosTextureContainer.COMPRESSED_3D:
  83358. case KhronosTextureContainer.TEX_3D:
  83359. }
  83360. };
  83361. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  83362. // initialize width & height for level 1
  83363. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  83364. var width = this.pixelWidth;
  83365. var height = this.pixelHeight;
  83366. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  83367. for (var level = 0; level < mipmapCount; level++) {
  83368. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  83369. for (var face = 0; face < this.numberOfFaces; face++) {
  83370. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  83371. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  83372. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  83373. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  83374. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  83375. }
  83376. width = Math.max(1.0, width * 0.5);
  83377. height = Math.max(1.0, height * 0.5);
  83378. }
  83379. };
  83380. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  83381. // load types
  83382. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  83383. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  83384. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  83385. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  83386. return KhronosTextureContainer;
  83387. }());
  83388. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  83389. })(BABYLON || (BABYLON = {}));
  83390. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  83391. "use strict";
  83392. var BABYLON;
  83393. (function (BABYLON) {
  83394. var Debug;
  83395. (function (Debug) {
  83396. /**
  83397. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  83398. */
  83399. var SkeletonViewer = /** @class */ (function () {
  83400. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  83401. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  83402. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  83403. this.skeleton = skeleton;
  83404. this.mesh = mesh;
  83405. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  83406. this.renderingGroupId = renderingGroupId;
  83407. this.color = BABYLON.Color3.White();
  83408. this._debugLines = new Array();
  83409. this._isEnabled = false;
  83410. this._scene = scene;
  83411. this.update();
  83412. this._renderFunction = this.update.bind(this);
  83413. }
  83414. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  83415. get: function () {
  83416. return this._isEnabled;
  83417. },
  83418. set: function (value) {
  83419. if (this._isEnabled === value) {
  83420. return;
  83421. }
  83422. this._isEnabled = value;
  83423. if (value) {
  83424. this._scene.registerBeforeRender(this._renderFunction);
  83425. }
  83426. else {
  83427. this._scene.unregisterBeforeRender(this._renderFunction);
  83428. }
  83429. },
  83430. enumerable: true,
  83431. configurable: true
  83432. });
  83433. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  83434. if (x === void 0) { x = 0; }
  83435. if (y === void 0) { y = 0; }
  83436. if (z === void 0) { z = 0; }
  83437. var tmat = BABYLON.Tmp.Matrix[0];
  83438. var parentBone = bone.getParent();
  83439. tmat.copyFrom(bone.getLocalMatrix());
  83440. if (x !== 0 || y !== 0 || z !== 0) {
  83441. var tmat2 = BABYLON.Tmp.Matrix[1];
  83442. BABYLON.Matrix.IdentityToRef(tmat2);
  83443. tmat2.m[12] = x;
  83444. tmat2.m[13] = y;
  83445. tmat2.m[14] = z;
  83446. tmat2.multiplyToRef(tmat, tmat);
  83447. }
  83448. if (parentBone) {
  83449. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  83450. }
  83451. tmat.multiplyToRef(meshMat, tmat);
  83452. position.x = tmat.m[12];
  83453. position.y = tmat.m[13];
  83454. position.z = tmat.m[14];
  83455. };
  83456. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  83457. var len = bones.length;
  83458. var meshPos = this.mesh.position;
  83459. for (var i = 0; i < len; i++) {
  83460. var bone = bones[i];
  83461. var points = this._debugLines[i];
  83462. if (!points) {
  83463. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83464. this._debugLines[i] = points;
  83465. }
  83466. this._getBonePosition(points[0], bone, meshMat);
  83467. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  83468. points[0].subtractInPlace(meshPos);
  83469. points[1].subtractInPlace(meshPos);
  83470. }
  83471. };
  83472. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  83473. var len = bones.length;
  83474. var boneNum = 0;
  83475. var meshPos = this.mesh.position;
  83476. for (var i = len - 1; i >= 0; i--) {
  83477. var childBone = bones[i];
  83478. var parentBone = childBone.getParent();
  83479. if (!parentBone) {
  83480. continue;
  83481. }
  83482. var points = this._debugLines[boneNum];
  83483. if (!points) {
  83484. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83485. this._debugLines[boneNum] = points;
  83486. }
  83487. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  83488. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  83489. points[0].subtractInPlace(meshPos);
  83490. points[1].subtractInPlace(meshPos);
  83491. boneNum++;
  83492. }
  83493. };
  83494. SkeletonViewer.prototype.update = function () {
  83495. if (this.autoUpdateBonesMatrices) {
  83496. this.skeleton.computeAbsoluteTransforms();
  83497. }
  83498. if (this.skeleton.bones[0].length === undefined) {
  83499. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  83500. }
  83501. else {
  83502. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  83503. }
  83504. if (!this._debugMesh) {
  83505. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  83506. this._debugMesh.renderingGroupId = this.renderingGroupId;
  83507. }
  83508. else {
  83509. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  83510. }
  83511. this._debugMesh.position.copyFrom(this.mesh.position);
  83512. this._debugMesh.color = this.color;
  83513. };
  83514. SkeletonViewer.prototype.dispose = function () {
  83515. if (this._debugMesh) {
  83516. this.isEnabled = false;
  83517. this._debugMesh.dispose();
  83518. this._debugMesh = null;
  83519. }
  83520. };
  83521. return SkeletonViewer;
  83522. }());
  83523. Debug.SkeletonViewer = SkeletonViewer;
  83524. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83525. })(BABYLON || (BABYLON = {}));
  83526. //# sourceMappingURL=babylon.skeletonViewer.js.map
  83527. "use strict";
  83528. /**
  83529. * Module Debug contains the (visual) components to debug a scene correctly
  83530. */
  83531. var BABYLON;
  83532. (function (BABYLON) {
  83533. var Debug;
  83534. (function (Debug) {
  83535. /**
  83536. * The Axes viewer will show 3 axes in a specific point in space
  83537. */
  83538. var AxesViewer = /** @class */ (function () {
  83539. function AxesViewer(scene, scaleLines) {
  83540. if (scaleLines === void 0) { scaleLines = 1; }
  83541. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83542. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83543. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83544. this.scaleLines = 1;
  83545. this.scaleLines = scaleLines;
  83546. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  83547. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  83548. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  83549. this._xmesh.renderingGroupId = 2;
  83550. this._ymesh.renderingGroupId = 2;
  83551. this._zmesh.renderingGroupId = 2;
  83552. this._xmesh.material.checkReadyOnlyOnce = true;
  83553. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  83554. this._ymesh.material.checkReadyOnlyOnce = true;
  83555. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  83556. this._zmesh.material.checkReadyOnlyOnce = true;
  83557. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  83558. this.scene = scene;
  83559. }
  83560. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  83561. var scaleLines = this.scaleLines;
  83562. if (this._xmesh) {
  83563. this._xmesh.position.copyFrom(position);
  83564. }
  83565. if (this._ymesh) {
  83566. this._ymesh.position.copyFrom(position);
  83567. }
  83568. if (this._zmesh) {
  83569. this._zmesh.position.copyFrom(position);
  83570. }
  83571. var point2 = this._xline[1];
  83572. point2.x = xaxis.x * scaleLines;
  83573. point2.y = xaxis.y * scaleLines;
  83574. point2.z = xaxis.z * scaleLines;
  83575. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  83576. point2 = this._yline[1];
  83577. point2.x = yaxis.x * scaleLines;
  83578. point2.y = yaxis.y * scaleLines;
  83579. point2.z = yaxis.z * scaleLines;
  83580. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  83581. point2 = this._zline[1];
  83582. point2.x = zaxis.x * scaleLines;
  83583. point2.y = zaxis.y * scaleLines;
  83584. point2.z = zaxis.z * scaleLines;
  83585. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  83586. };
  83587. AxesViewer.prototype.dispose = function () {
  83588. if (this._xmesh) {
  83589. this._xmesh.dispose();
  83590. }
  83591. if (this._ymesh) {
  83592. this._ymesh.dispose();
  83593. }
  83594. if (this._zmesh) {
  83595. this._zmesh.dispose();
  83596. }
  83597. this._xmesh = null;
  83598. this._ymesh = null;
  83599. this._zmesh = null;
  83600. this.scene = null;
  83601. };
  83602. return AxesViewer;
  83603. }());
  83604. Debug.AxesViewer = AxesViewer;
  83605. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83606. })(BABYLON || (BABYLON = {}));
  83607. //# sourceMappingURL=babylon.axesViewer.js.map
  83608. "use strict";
  83609. var BABYLON;
  83610. (function (BABYLON) {
  83611. var Debug;
  83612. (function (Debug) {
  83613. /**
  83614. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  83615. */
  83616. var BoneAxesViewer = /** @class */ (function (_super) {
  83617. __extends(BoneAxesViewer, _super);
  83618. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  83619. if (scaleLines === void 0) { scaleLines = 1; }
  83620. var _this = _super.call(this, scene, scaleLines) || this;
  83621. _this.pos = BABYLON.Vector3.Zero();
  83622. _this.xaxis = BABYLON.Vector3.Zero();
  83623. _this.yaxis = BABYLON.Vector3.Zero();
  83624. _this.zaxis = BABYLON.Vector3.Zero();
  83625. _this.mesh = mesh;
  83626. _this.bone = bone;
  83627. return _this;
  83628. }
  83629. BoneAxesViewer.prototype.update = function () {
  83630. if (!this.mesh || !this.bone) {
  83631. return;
  83632. }
  83633. var bone = this.bone;
  83634. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  83635. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  83636. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  83637. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  83638. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  83639. };
  83640. BoneAxesViewer.prototype.dispose = function () {
  83641. if (this.mesh) {
  83642. this.mesh = null;
  83643. this.bone = null;
  83644. _super.prototype.dispose.call(this);
  83645. }
  83646. };
  83647. return BoneAxesViewer;
  83648. }(Debug.AxesViewer));
  83649. Debug.BoneAxesViewer = BoneAxesViewer;
  83650. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83651. })(BABYLON || (BABYLON = {}));
  83652. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  83653. "use strict";
  83654. var BABYLON;
  83655. (function (BABYLON) {
  83656. var RayHelper = /** @class */ (function () {
  83657. function RayHelper(ray) {
  83658. this.ray = ray;
  83659. }
  83660. RayHelper.CreateAndShow = function (ray, scene, color) {
  83661. var helper = new RayHelper(ray);
  83662. helper.show(scene, color);
  83663. return helper;
  83664. };
  83665. RayHelper.prototype.show = function (scene, color) {
  83666. if (!this._renderFunction && this.ray) {
  83667. var ray = this.ray;
  83668. this._renderFunction = this._render.bind(this);
  83669. this._scene = scene;
  83670. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  83671. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  83672. if (this._renderFunction) {
  83673. this._scene.registerBeforeRender(this._renderFunction);
  83674. }
  83675. }
  83676. if (color && this._renderLine) {
  83677. this._renderLine.color.copyFrom(color);
  83678. }
  83679. };
  83680. RayHelper.prototype.hide = function () {
  83681. if (this._renderFunction && this._scene) {
  83682. this._scene.unregisterBeforeRender(this._renderFunction);
  83683. this._scene = null;
  83684. this._renderFunction = null;
  83685. if (this._renderLine) {
  83686. this._renderLine.dispose();
  83687. this._renderLine = null;
  83688. }
  83689. this._renderPoints = [];
  83690. }
  83691. };
  83692. RayHelper.prototype._render = function () {
  83693. var ray = this.ray;
  83694. if (!ray) {
  83695. return;
  83696. }
  83697. var point = this._renderPoints[1];
  83698. var len = Math.min(ray.length, 1000000);
  83699. point.copyFrom(ray.direction);
  83700. point.scaleInPlace(len);
  83701. point.addInPlace(ray.origin);
  83702. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  83703. };
  83704. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  83705. this._attachedToMesh = mesh;
  83706. var ray = this.ray;
  83707. if (!ray) {
  83708. return;
  83709. }
  83710. if (!ray.direction) {
  83711. ray.direction = BABYLON.Vector3.Zero();
  83712. }
  83713. if (!ray.origin) {
  83714. ray.origin = BABYLON.Vector3.Zero();
  83715. }
  83716. if (length) {
  83717. ray.length = length;
  83718. }
  83719. if (!meshSpaceOrigin) {
  83720. meshSpaceOrigin = BABYLON.Vector3.Zero();
  83721. }
  83722. if (!meshSpaceDirection) {
  83723. // -1 so that this will work with Mesh.lookAt
  83724. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  83725. }
  83726. if (!this._meshSpaceDirection) {
  83727. this._meshSpaceDirection = meshSpaceDirection.clone();
  83728. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  83729. }
  83730. else {
  83731. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  83732. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  83733. }
  83734. if (!this._updateToMeshFunction) {
  83735. this._updateToMeshFunction = this._updateToMesh.bind(this);
  83736. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  83737. }
  83738. this._updateToMesh();
  83739. };
  83740. RayHelper.prototype.detachFromMesh = function () {
  83741. if (this._attachedToMesh) {
  83742. if (this._updateToMeshFunction) {
  83743. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  83744. }
  83745. this._attachedToMesh = null;
  83746. this._updateToMeshFunction = null;
  83747. }
  83748. };
  83749. RayHelper.prototype._updateToMesh = function () {
  83750. var ray = this.ray;
  83751. if (!this._attachedToMesh || !ray) {
  83752. return;
  83753. }
  83754. if (this._attachedToMesh._isDisposed) {
  83755. this.detachFromMesh();
  83756. return;
  83757. }
  83758. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  83759. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  83760. };
  83761. RayHelper.prototype.dispose = function () {
  83762. this.hide();
  83763. this.detachFromMesh();
  83764. this.ray = null;
  83765. };
  83766. return RayHelper;
  83767. }());
  83768. BABYLON.RayHelper = RayHelper;
  83769. })(BABYLON || (BABYLON = {}));
  83770. //# sourceMappingURL=babylon.rayHelper.js.map
  83771. "use strict";
  83772. var BABYLON;
  83773. (function (BABYLON) {
  83774. // load the inspector using require, if not present in the global namespace.
  83775. var DebugLayer = /** @class */ (function () {
  83776. function DebugLayer(scene) {
  83777. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  83778. this._scene = scene;
  83779. // load inspector using require, if it doesn't exist on the global namespace.
  83780. }
  83781. /** Creates the inspector window. */
  83782. DebugLayer.prototype._createInspector = function (config) {
  83783. if (config === void 0) { config = {}; }
  83784. var popup = config.popup || false;
  83785. var initialTab = config.initialTab || 0;
  83786. var parentElement = config.parentElement || null;
  83787. if (!this._inspector) {
  83788. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  83789. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  83790. } // else nothing to do,; instance is already existing
  83791. };
  83792. DebugLayer.prototype.isVisible = function () {
  83793. if (!this._inspector) {
  83794. return false;
  83795. }
  83796. return true;
  83797. };
  83798. DebugLayer.prototype.hide = function () {
  83799. if (this._inspector) {
  83800. try {
  83801. this._inspector.dispose();
  83802. }
  83803. catch (e) {
  83804. // If the inspector has been removed directly from the inspector tool
  83805. }
  83806. this._inspector = null;
  83807. }
  83808. };
  83809. DebugLayer.prototype.show = function (config) {
  83810. if (config === void 0) { config = {}; }
  83811. if (typeof this.BJSINSPECTOR == 'undefined') {
  83812. // Load inspector and add it to the DOM
  83813. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  83814. }
  83815. else {
  83816. // Otherwise creates the inspector
  83817. this._createInspector(config);
  83818. }
  83819. };
  83820. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  83821. return DebugLayer;
  83822. }());
  83823. BABYLON.DebugLayer = DebugLayer;
  83824. })(BABYLON || (BABYLON = {}));
  83825. //# sourceMappingURL=babylon.debugLayer.js.map
  83826. "use strict";
  83827. var BABYLON;
  83828. (function (BABYLON) {
  83829. var Debug;
  83830. (function (Debug) {
  83831. /**
  83832. * Used to show the physics impostor around the specific mesh.
  83833. */
  83834. var PhysicsViewer = /** @class */ (function () {
  83835. function PhysicsViewer(scene) {
  83836. this._impostors = [];
  83837. this._meshes = [];
  83838. this._numMeshes = 0;
  83839. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83840. var physicEngine = this._scene.getPhysicsEngine();
  83841. if (physicEngine) {
  83842. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  83843. }
  83844. }
  83845. PhysicsViewer.prototype._updateDebugMeshes = function () {
  83846. var plugin = this._physicsEnginePlugin;
  83847. for (var i = 0; i < this._numMeshes; i++) {
  83848. var impostor = this._impostors[i];
  83849. if (!impostor) {
  83850. continue;
  83851. }
  83852. if (impostor.isDisposed) {
  83853. this.hideImpostor(this._impostors[i--]);
  83854. }
  83855. else {
  83856. var mesh = this._meshes[i];
  83857. if (mesh && plugin) {
  83858. plugin.syncMeshWithImpostor(mesh, impostor);
  83859. }
  83860. }
  83861. }
  83862. };
  83863. PhysicsViewer.prototype.showImpostor = function (impostor) {
  83864. if (!this._scene) {
  83865. return;
  83866. }
  83867. for (var i = 0; i < this._numMeshes; i++) {
  83868. if (this._impostors[i] == impostor) {
  83869. return;
  83870. }
  83871. }
  83872. var debugMesh = this._getDebugMesh(impostor, this._scene);
  83873. if (debugMesh) {
  83874. this._impostors[this._numMeshes] = impostor;
  83875. this._meshes[this._numMeshes] = debugMesh;
  83876. if (this._numMeshes === 0) {
  83877. this._renderFunction = this._updateDebugMeshes.bind(this);
  83878. this._scene.registerBeforeRender(this._renderFunction);
  83879. }
  83880. this._numMeshes++;
  83881. }
  83882. };
  83883. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  83884. if (!impostor || !this._scene) {
  83885. return;
  83886. }
  83887. var removed = false;
  83888. for (var i = 0; i < this._numMeshes; i++) {
  83889. if (this._impostors[i] == impostor) {
  83890. var mesh = this._meshes[i];
  83891. if (!mesh) {
  83892. continue;
  83893. }
  83894. this._scene.removeMesh(mesh);
  83895. mesh.dispose();
  83896. this._numMeshes--;
  83897. if (this._numMeshes > 0) {
  83898. this._meshes[i] = this._meshes[this._numMeshes];
  83899. this._impostors[i] = this._impostors[this._numMeshes];
  83900. this._meshes[this._numMeshes] = null;
  83901. this._impostors[this._numMeshes] = null;
  83902. }
  83903. else {
  83904. this._meshes[0] = null;
  83905. this._impostors[0] = null;
  83906. }
  83907. removed = true;
  83908. break;
  83909. }
  83910. }
  83911. if (removed && this._numMeshes === 0) {
  83912. this._scene.unregisterBeforeRender(this._renderFunction);
  83913. }
  83914. };
  83915. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  83916. if (!this._debugMaterial) {
  83917. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  83918. this._debugMaterial.wireframe = true;
  83919. }
  83920. return this._debugMaterial;
  83921. };
  83922. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  83923. if (!this._debugBoxMesh) {
  83924. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  83925. this._debugBoxMesh.renderingGroupId = 1;
  83926. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  83927. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  83928. scene.removeMesh(this._debugBoxMesh);
  83929. }
  83930. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  83931. };
  83932. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  83933. if (!this._debugSphereMesh) {
  83934. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  83935. this._debugSphereMesh.renderingGroupId = 1;
  83936. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  83937. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  83938. scene.removeMesh(this._debugSphereMesh);
  83939. }
  83940. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  83941. };
  83942. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  83943. var mesh = null;
  83944. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  83945. mesh = this._getDebugBoxMesh(scene);
  83946. impostor.getBoxSizeToRef(mesh.scaling);
  83947. }
  83948. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  83949. mesh = this._getDebugSphereMesh(scene);
  83950. var radius = impostor.getRadius();
  83951. mesh.scaling.x = radius * 2;
  83952. mesh.scaling.y = radius * 2;
  83953. mesh.scaling.z = radius * 2;
  83954. }
  83955. return mesh;
  83956. };
  83957. PhysicsViewer.prototype.dispose = function () {
  83958. for (var i = 0; i < this._numMeshes; i++) {
  83959. this.hideImpostor(this._impostors[i]);
  83960. }
  83961. if (this._debugBoxMesh) {
  83962. this._debugBoxMesh.dispose();
  83963. }
  83964. if (this._debugSphereMesh) {
  83965. this._debugSphereMesh.dispose();
  83966. }
  83967. if (this._debugMaterial) {
  83968. this._debugMaterial.dispose();
  83969. }
  83970. this._impostors.length = 0;
  83971. this._scene = null;
  83972. this._physicsEnginePlugin = null;
  83973. };
  83974. return PhysicsViewer;
  83975. }());
  83976. Debug.PhysicsViewer = PhysicsViewer;
  83977. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83978. })(BABYLON || (BABYLON = {}));
  83979. //# sourceMappingURL=babylon.physicsViewer.js.map
  83980. "use strict";
  83981. var BABYLON;
  83982. (function (BABYLON) {
  83983. var BoundingBoxRenderer = /** @class */ (function () {
  83984. function BoundingBoxRenderer(scene) {
  83985. this.frontColor = new BABYLON.Color3(1, 1, 1);
  83986. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  83987. this.showBackLines = true;
  83988. this.renderList = new BABYLON.SmartArray(32);
  83989. this._vertexBuffers = {};
  83990. this._scene = scene;
  83991. }
  83992. BoundingBoxRenderer.prototype._prepareRessources = function () {
  83993. if (this._colorShader) {
  83994. return;
  83995. }
  83996. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  83997. attributes: [BABYLON.VertexBuffer.PositionKind],
  83998. uniforms: ["world", "viewProjection", "color"]
  83999. });
  84000. var engine = this._scene.getEngine();
  84001. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  84002. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  84003. this._createIndexBuffer();
  84004. };
  84005. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  84006. var engine = this._scene.getEngine();
  84007. 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]);
  84008. };
  84009. BoundingBoxRenderer.prototype._rebuild = function () {
  84010. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84011. if (vb) {
  84012. vb._rebuild();
  84013. }
  84014. this._createIndexBuffer();
  84015. };
  84016. BoundingBoxRenderer.prototype.reset = function () {
  84017. this.renderList.reset();
  84018. };
  84019. BoundingBoxRenderer.prototype.render = function () {
  84020. if (this.renderList.length === 0) {
  84021. return;
  84022. }
  84023. this._prepareRessources();
  84024. if (!this._colorShader.isReady()) {
  84025. return;
  84026. }
  84027. var engine = this._scene.getEngine();
  84028. engine.setDepthWrite(false);
  84029. this._colorShader._preBind();
  84030. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  84031. var boundingBox = this.renderList.data[boundingBoxIndex];
  84032. var min = boundingBox.minimum;
  84033. var max = boundingBox.maximum;
  84034. var diff = max.subtract(min);
  84035. var median = min.add(diff.scale(0.5));
  84036. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  84037. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  84038. .multiply(boundingBox.getWorldMatrix());
  84039. // VBOs
  84040. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  84041. if (this.showBackLines) {
  84042. // Back
  84043. engine.setDepthFunctionToGreaterOrEqual();
  84044. this._scene.resetCachedMaterial();
  84045. this._colorShader.setColor4("color", this.backColor.toColor4());
  84046. this._colorShader.bind(worldMatrix);
  84047. // Draw order
  84048. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84049. }
  84050. // Front
  84051. engine.setDepthFunctionToLess();
  84052. this._scene.resetCachedMaterial();
  84053. this._colorShader.setColor4("color", this.frontColor.toColor4());
  84054. this._colorShader.bind(worldMatrix);
  84055. // Draw order
  84056. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84057. }
  84058. this._colorShader.unbind();
  84059. engine.setDepthFunctionToLessOrEqual();
  84060. engine.setDepthWrite(true);
  84061. };
  84062. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  84063. this._prepareRessources();
  84064. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  84065. return;
  84066. }
  84067. var engine = this._scene.getEngine();
  84068. engine.setDepthWrite(false);
  84069. engine.setColorWrite(false);
  84070. this._colorShader._preBind();
  84071. var boundingBox = mesh._boundingInfo.boundingBox;
  84072. var min = boundingBox.minimum;
  84073. var max = boundingBox.maximum;
  84074. var diff = max.subtract(min);
  84075. var median = min.add(diff.scale(0.5));
  84076. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  84077. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  84078. .multiply(boundingBox.getWorldMatrix());
  84079. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  84080. engine.setDepthFunctionToLess();
  84081. this._scene.resetCachedMaterial();
  84082. this._colorShader.bind(worldMatrix);
  84083. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84084. this._colorShader.unbind();
  84085. engine.setDepthFunctionToLessOrEqual();
  84086. engine.setDepthWrite(true);
  84087. engine.setColorWrite(true);
  84088. };
  84089. BoundingBoxRenderer.prototype.dispose = function () {
  84090. if (!this._colorShader) {
  84091. return;
  84092. }
  84093. this.renderList.dispose();
  84094. this._colorShader.dispose();
  84095. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84096. if (buffer) {
  84097. buffer.dispose();
  84098. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84099. }
  84100. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84101. };
  84102. return BoundingBoxRenderer;
  84103. }());
  84104. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  84105. })(BABYLON || (BABYLON = {}));
  84106. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  84107. "use strict";
  84108. var BABYLON;
  84109. (function (BABYLON) {
  84110. /**
  84111. * Defines a target to use with MorphTargetManager
  84112. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  84113. */
  84114. var MorphTarget = /** @class */ (function () {
  84115. /**
  84116. * Creates a new MorphTarget
  84117. * @param name defines the name of the target
  84118. * @param influence defines the influence to use
  84119. */
  84120. function MorphTarget(
  84121. /** defines the name of the target */
  84122. name, influence) {
  84123. if (influence === void 0) { influence = 0; }
  84124. this.name = name;
  84125. /**
  84126. * Gets or sets the list of animations
  84127. */
  84128. this.animations = new Array();
  84129. this._positions = null;
  84130. this._normals = null;
  84131. this._tangents = null;
  84132. /**
  84133. * Observable raised when the influence changes
  84134. */
  84135. this.onInfluenceChanged = new BABYLON.Observable();
  84136. this.influence = influence;
  84137. }
  84138. Object.defineProperty(MorphTarget.prototype, "influence", {
  84139. /**
  84140. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  84141. */
  84142. get: function () {
  84143. return this._influence;
  84144. },
  84145. set: function (influence) {
  84146. if (this._influence === influence) {
  84147. return;
  84148. }
  84149. var previous = this._influence;
  84150. this._influence = influence;
  84151. if (this.onInfluenceChanged.hasObservers) {
  84152. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  84153. }
  84154. },
  84155. enumerable: true,
  84156. configurable: true
  84157. });
  84158. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  84159. /**
  84160. * Gets a boolean defining if the target contains position data
  84161. */
  84162. get: function () {
  84163. return !!this._positions;
  84164. },
  84165. enumerable: true,
  84166. configurable: true
  84167. });
  84168. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  84169. /**
  84170. * Gets a boolean defining if the target contains normal data
  84171. */
  84172. get: function () {
  84173. return !!this._normals;
  84174. },
  84175. enumerable: true,
  84176. configurable: true
  84177. });
  84178. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  84179. /**
  84180. * Gets a boolean defining if the target contains tangent data
  84181. */
  84182. get: function () {
  84183. return !!this._tangents;
  84184. },
  84185. enumerable: true,
  84186. configurable: true
  84187. });
  84188. /**
  84189. * Affects position data to this target
  84190. * @param data defines the position data to use
  84191. */
  84192. MorphTarget.prototype.setPositions = function (data) {
  84193. this._positions = data;
  84194. };
  84195. /**
  84196. * Gets the position data stored in this target
  84197. * @returns a FloatArray containing the position data (or null if not present)
  84198. */
  84199. MorphTarget.prototype.getPositions = function () {
  84200. return this._positions;
  84201. };
  84202. /**
  84203. * Affects normal data to this target
  84204. * @param data defines the normal data to use
  84205. */
  84206. MorphTarget.prototype.setNormals = function (data) {
  84207. this._normals = data;
  84208. };
  84209. /**
  84210. * Gets the normal data stored in this target
  84211. * @returns a FloatArray containing the normal data (or null if not present)
  84212. */
  84213. MorphTarget.prototype.getNormals = function () {
  84214. return this._normals;
  84215. };
  84216. /**
  84217. * Affects tangent data to this target
  84218. * @param data defines the tangent data to use
  84219. */
  84220. MorphTarget.prototype.setTangents = function (data) {
  84221. this._tangents = data;
  84222. };
  84223. /**
  84224. * Gets the tangent data stored in this target
  84225. * @returns a FloatArray containing the tangent data (or null if not present)
  84226. */
  84227. MorphTarget.prototype.getTangents = function () {
  84228. return this._tangents;
  84229. };
  84230. /**
  84231. * Serializes the current target into a Serialization object
  84232. * @returns the serialized object
  84233. */
  84234. MorphTarget.prototype.serialize = function () {
  84235. var serializationObject = {};
  84236. serializationObject.name = this.name;
  84237. serializationObject.influence = this.influence;
  84238. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  84239. if (this.hasNormals) {
  84240. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  84241. }
  84242. if (this.hasTangents) {
  84243. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  84244. }
  84245. // Animations
  84246. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  84247. return serializationObject;
  84248. };
  84249. // Statics
  84250. /**
  84251. * Creates a new target from serialized data
  84252. * @param serializationObject defines the serialized data to use
  84253. * @returns a new MorphTarget
  84254. */
  84255. MorphTarget.Parse = function (serializationObject) {
  84256. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  84257. result.setPositions(serializationObject.positions);
  84258. if (serializationObject.normals) {
  84259. result.setNormals(serializationObject.normals);
  84260. }
  84261. if (serializationObject.tangents) {
  84262. result.setTangents(serializationObject.tangents);
  84263. }
  84264. // Animations
  84265. if (serializationObject.animations) {
  84266. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  84267. var parsedAnimation = serializationObject.animations[animationIndex];
  84268. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  84269. }
  84270. }
  84271. return result;
  84272. };
  84273. /**
  84274. * Creates a MorphTarget from mesh data
  84275. * @param mesh defines the source mesh
  84276. * @param name defines the name to use for the new target
  84277. * @param influence defines the influence to attach to the target
  84278. * @returns a new MorphTarget
  84279. */
  84280. MorphTarget.FromMesh = function (mesh, name, influence) {
  84281. if (!name) {
  84282. name = mesh.name;
  84283. }
  84284. var result = new MorphTarget(name, influence);
  84285. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  84286. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  84287. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  84288. }
  84289. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  84290. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  84291. }
  84292. return result;
  84293. };
  84294. return MorphTarget;
  84295. }());
  84296. BABYLON.MorphTarget = MorphTarget;
  84297. })(BABYLON || (BABYLON = {}));
  84298. //# sourceMappingURL=babylon.morphTarget.js.map
  84299. "use strict";
  84300. var BABYLON;
  84301. (function (BABYLON) {
  84302. /**
  84303. * This class is used to deform meshes using morphing between different targets
  84304. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  84305. */
  84306. var MorphTargetManager = /** @class */ (function () {
  84307. /**
  84308. * Creates a new MorphTargetManager
  84309. * @param scene defines the current scene
  84310. */
  84311. function MorphTargetManager(scene) {
  84312. if (scene === void 0) { scene = null; }
  84313. this._targets = new Array();
  84314. this._targetObservable = new Array();
  84315. this._activeTargets = new BABYLON.SmartArray(16);
  84316. this._supportsNormals = false;
  84317. this._supportsTangents = false;
  84318. this._vertexCount = 0;
  84319. this._uniqueId = 0;
  84320. this._tempInfluences = new Array();
  84321. if (!scene) {
  84322. scene = BABYLON.Engine.LastCreatedScene;
  84323. }
  84324. this._scene = scene;
  84325. if (this._scene) {
  84326. this._scene.morphTargetManagers.push(this);
  84327. this._uniqueId = this._scene.getUniqueId();
  84328. }
  84329. }
  84330. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  84331. /**
  84332. * Gets the unique ID of this manager
  84333. */
  84334. get: function () {
  84335. return this._uniqueId;
  84336. },
  84337. enumerable: true,
  84338. configurable: true
  84339. });
  84340. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  84341. /**
  84342. * Gets the number of vertices handled by this manager
  84343. */
  84344. get: function () {
  84345. return this._vertexCount;
  84346. },
  84347. enumerable: true,
  84348. configurable: true
  84349. });
  84350. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  84351. /**
  84352. * Gets a boolean indicating if this manager supports morphing of normals
  84353. */
  84354. get: function () {
  84355. return this._supportsNormals;
  84356. },
  84357. enumerable: true,
  84358. configurable: true
  84359. });
  84360. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  84361. /**
  84362. * Gets a boolean indicating if this manager supports morphing of tangents
  84363. */
  84364. get: function () {
  84365. return this._supportsTangents;
  84366. },
  84367. enumerable: true,
  84368. configurable: true
  84369. });
  84370. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  84371. /**
  84372. * Gets the number of targets stored in this manager
  84373. */
  84374. get: function () {
  84375. return this._targets.length;
  84376. },
  84377. enumerable: true,
  84378. configurable: true
  84379. });
  84380. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  84381. /**
  84382. * Gets the number of influencers (ie. the number of targets with influences > 0)
  84383. */
  84384. get: function () {
  84385. return this._activeTargets.length;
  84386. },
  84387. enumerable: true,
  84388. configurable: true
  84389. });
  84390. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  84391. /**
  84392. * Gets the list of influences (one per target)
  84393. */
  84394. get: function () {
  84395. return this._influences;
  84396. },
  84397. enumerable: true,
  84398. configurable: true
  84399. });
  84400. /**
  84401. * Gets the active target at specified index. An active target is a target with an influence > 0
  84402. * @param index defines the index to check
  84403. * @returns the requested target
  84404. */
  84405. MorphTargetManager.prototype.getActiveTarget = function (index) {
  84406. return this._activeTargets.data[index];
  84407. };
  84408. /**
  84409. * Gets the target at specified index
  84410. * @param index defines the index to check
  84411. * @returns the requested target
  84412. */
  84413. MorphTargetManager.prototype.getTarget = function (index) {
  84414. return this._targets[index];
  84415. };
  84416. /**
  84417. * Add a new target to this manager
  84418. * @param target defines the target to add
  84419. */
  84420. MorphTargetManager.prototype.addTarget = function (target) {
  84421. var _this = this;
  84422. this._targets.push(target);
  84423. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  84424. _this._syncActiveTargets(needUpdate);
  84425. }));
  84426. this._syncActiveTargets(true);
  84427. };
  84428. /**
  84429. * Removes a target from the manager
  84430. * @param target defines the target to remove
  84431. */
  84432. MorphTargetManager.prototype.removeTarget = function (target) {
  84433. var index = this._targets.indexOf(target);
  84434. if (index >= 0) {
  84435. this._targets.splice(index, 1);
  84436. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  84437. this._syncActiveTargets(true);
  84438. }
  84439. };
  84440. /**
  84441. * Serializes the current manager into a Serialization object
  84442. * @returns the serialized object
  84443. */
  84444. MorphTargetManager.prototype.serialize = function () {
  84445. var serializationObject = {};
  84446. serializationObject.id = this.uniqueId;
  84447. serializationObject.targets = [];
  84448. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  84449. var target = _a[_i];
  84450. serializationObject.targets.push(target.serialize());
  84451. }
  84452. return serializationObject;
  84453. };
  84454. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  84455. var influenceCount = 0;
  84456. this._activeTargets.reset();
  84457. this._supportsNormals = true;
  84458. this._supportsTangents = true;
  84459. this._vertexCount = 0;
  84460. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  84461. var target = _a[_i];
  84462. this._activeTargets.push(target);
  84463. this._tempInfluences[influenceCount++] = target.influence;
  84464. var positions = target.getPositions();
  84465. if (positions) {
  84466. this._supportsNormals = this._supportsNormals && target.hasNormals;
  84467. this._supportsTangents = this._supportsTangents && target.hasTangents;
  84468. var vertexCount = positions.length / 3;
  84469. if (this._vertexCount === 0) {
  84470. this._vertexCount = vertexCount;
  84471. }
  84472. else if (this._vertexCount !== vertexCount) {
  84473. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  84474. return;
  84475. }
  84476. }
  84477. }
  84478. if (!this._influences || this._influences.length !== influenceCount) {
  84479. this._influences = new Float32Array(influenceCount);
  84480. }
  84481. for (var index = 0; index < influenceCount; index++) {
  84482. this._influences[index] = this._tempInfluences[index];
  84483. }
  84484. if (needUpdate) {
  84485. this.synchronize();
  84486. }
  84487. };
  84488. /**
  84489. * Syncrhonize the targets with all the meshes using this morph target manager
  84490. */
  84491. MorphTargetManager.prototype.synchronize = function () {
  84492. if (!this._scene) {
  84493. return;
  84494. }
  84495. // Flag meshes as dirty to resync with the active targets
  84496. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  84497. var mesh = _a[_i];
  84498. if (mesh.morphTargetManager === this) {
  84499. mesh._syncGeometryWithMorphTargetManager();
  84500. }
  84501. }
  84502. };
  84503. // Statics
  84504. /**
  84505. * Creates a new MorphTargetManager from serialized data
  84506. * @param serializationObject defines the serialized data
  84507. * @param scene defines the hosting scene
  84508. * @returns the new MorphTargetManager
  84509. */
  84510. MorphTargetManager.Parse = function (serializationObject, scene) {
  84511. var result = new MorphTargetManager(scene);
  84512. result._uniqueId = serializationObject.id;
  84513. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  84514. var targetData = _a[_i];
  84515. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  84516. }
  84517. return result;
  84518. };
  84519. return MorphTargetManager;
  84520. }());
  84521. BABYLON.MorphTargetManager = MorphTargetManager;
  84522. })(BABYLON || (BABYLON = {}));
  84523. //# sourceMappingURL=babylon.morphTargetManager.js.map
  84524. "use strict";
  84525. var BABYLON;
  84526. (function (BABYLON) {
  84527. var Octree = /** @class */ (function () {
  84528. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  84529. if (maxDepth === void 0) { maxDepth = 2; }
  84530. this.maxDepth = maxDepth;
  84531. this.dynamicContent = new Array();
  84532. this._maxBlockCapacity = maxBlockCapacity || 64;
  84533. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  84534. this._creationFunc = creationFunc;
  84535. }
  84536. // Methods
  84537. Octree.prototype.update = function (worldMin, worldMax, entries) {
  84538. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  84539. };
  84540. Octree.prototype.addMesh = function (entry) {
  84541. for (var index = 0; index < this.blocks.length; index++) {
  84542. var block = this.blocks[index];
  84543. block.addEntry(entry);
  84544. }
  84545. };
  84546. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  84547. this._selectionContent.reset();
  84548. for (var index = 0; index < this.blocks.length; index++) {
  84549. var block = this.blocks[index];
  84550. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  84551. }
  84552. if (allowDuplicate) {
  84553. this._selectionContent.concat(this.dynamicContent);
  84554. }
  84555. else {
  84556. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  84557. }
  84558. return this._selectionContent;
  84559. };
  84560. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  84561. this._selectionContent.reset();
  84562. for (var index = 0; index < this.blocks.length; index++) {
  84563. var block = this.blocks[index];
  84564. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  84565. }
  84566. if (allowDuplicate) {
  84567. this._selectionContent.concat(this.dynamicContent);
  84568. }
  84569. else {
  84570. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  84571. }
  84572. return this._selectionContent;
  84573. };
  84574. Octree.prototype.intersectsRay = function (ray) {
  84575. this._selectionContent.reset();
  84576. for (var index = 0; index < this.blocks.length; index++) {
  84577. var block = this.blocks[index];
  84578. block.intersectsRay(ray, this._selectionContent);
  84579. }
  84580. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  84581. return this._selectionContent;
  84582. };
  84583. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  84584. target.blocks = new Array();
  84585. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  84586. // Segmenting space
  84587. for (var x = 0; x < 2; x++) {
  84588. for (var y = 0; y < 2; y++) {
  84589. for (var z = 0; z < 2; z++) {
  84590. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  84591. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  84592. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  84593. block.addEntries(entries);
  84594. target.blocks.push(block);
  84595. }
  84596. }
  84597. }
  84598. };
  84599. Octree.CreationFuncForMeshes = function (entry, block) {
  84600. var boundingInfo = entry.getBoundingInfo();
  84601. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  84602. block.entries.push(entry);
  84603. }
  84604. };
  84605. Octree.CreationFuncForSubMeshes = function (entry, block) {
  84606. var boundingInfo = entry.getBoundingInfo();
  84607. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  84608. block.entries.push(entry);
  84609. }
  84610. };
  84611. return Octree;
  84612. }());
  84613. BABYLON.Octree = Octree;
  84614. })(BABYLON || (BABYLON = {}));
  84615. //# sourceMappingURL=babylon.octree.js.map
  84616. "use strict";
  84617. var BABYLON;
  84618. (function (BABYLON) {
  84619. var OctreeBlock = /** @class */ (function () {
  84620. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  84621. this.entries = new Array();
  84622. this._boundingVectors = new Array();
  84623. this._capacity = capacity;
  84624. this._depth = depth;
  84625. this._maxDepth = maxDepth;
  84626. this._creationFunc = creationFunc;
  84627. this._minPoint = minPoint;
  84628. this._maxPoint = maxPoint;
  84629. this._boundingVectors.push(minPoint.clone());
  84630. this._boundingVectors.push(maxPoint.clone());
  84631. this._boundingVectors.push(minPoint.clone());
  84632. this._boundingVectors[2].x = maxPoint.x;
  84633. this._boundingVectors.push(minPoint.clone());
  84634. this._boundingVectors[3].y = maxPoint.y;
  84635. this._boundingVectors.push(minPoint.clone());
  84636. this._boundingVectors[4].z = maxPoint.z;
  84637. this._boundingVectors.push(maxPoint.clone());
  84638. this._boundingVectors[5].z = minPoint.z;
  84639. this._boundingVectors.push(maxPoint.clone());
  84640. this._boundingVectors[6].x = minPoint.x;
  84641. this._boundingVectors.push(maxPoint.clone());
  84642. this._boundingVectors[7].y = minPoint.y;
  84643. }
  84644. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  84645. // Property
  84646. get: function () {
  84647. return this._capacity;
  84648. },
  84649. enumerable: true,
  84650. configurable: true
  84651. });
  84652. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  84653. get: function () {
  84654. return this._minPoint;
  84655. },
  84656. enumerable: true,
  84657. configurable: true
  84658. });
  84659. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  84660. get: function () {
  84661. return this._maxPoint;
  84662. },
  84663. enumerable: true,
  84664. configurable: true
  84665. });
  84666. // Methods
  84667. OctreeBlock.prototype.addEntry = function (entry) {
  84668. if (this.blocks) {
  84669. for (var index = 0; index < this.blocks.length; index++) {
  84670. var block = this.blocks[index];
  84671. block.addEntry(entry);
  84672. }
  84673. return;
  84674. }
  84675. this._creationFunc(entry, this);
  84676. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  84677. this.createInnerBlocks();
  84678. }
  84679. };
  84680. OctreeBlock.prototype.addEntries = function (entries) {
  84681. for (var index = 0; index < entries.length; index++) {
  84682. var mesh = entries[index];
  84683. this.addEntry(mesh);
  84684. }
  84685. };
  84686. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  84687. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  84688. if (this.blocks) {
  84689. for (var index = 0; index < this.blocks.length; index++) {
  84690. var block = this.blocks[index];
  84691. block.select(frustumPlanes, selection, allowDuplicate);
  84692. }
  84693. return;
  84694. }
  84695. if (allowDuplicate) {
  84696. selection.concat(this.entries);
  84697. }
  84698. else {
  84699. selection.concatWithNoDuplicate(this.entries);
  84700. }
  84701. }
  84702. };
  84703. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  84704. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  84705. if (this.blocks) {
  84706. for (var index = 0; index < this.blocks.length; index++) {
  84707. var block = this.blocks[index];
  84708. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  84709. }
  84710. return;
  84711. }
  84712. if (allowDuplicate) {
  84713. selection.concat(this.entries);
  84714. }
  84715. else {
  84716. selection.concatWithNoDuplicate(this.entries);
  84717. }
  84718. }
  84719. };
  84720. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  84721. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  84722. if (this.blocks) {
  84723. for (var index = 0; index < this.blocks.length; index++) {
  84724. var block = this.blocks[index];
  84725. block.intersectsRay(ray, selection);
  84726. }
  84727. return;
  84728. }
  84729. selection.concatWithNoDuplicate(this.entries);
  84730. }
  84731. };
  84732. OctreeBlock.prototype.createInnerBlocks = function () {
  84733. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  84734. };
  84735. return OctreeBlock;
  84736. }());
  84737. BABYLON.OctreeBlock = OctreeBlock;
  84738. })(BABYLON || (BABYLON = {}));
  84739. //# sourceMappingURL=babylon.octreeBlock.js.map
  84740. "use strict";
  84741. var BABYLON;
  84742. (function (BABYLON) {
  84743. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  84744. __extends(VRDistortionCorrectionPostProcess, _super);
  84745. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  84746. var _this = _super.call(this, name, "vrDistortionCorrection", [
  84747. 'LensCenter',
  84748. 'Scale',
  84749. 'ScaleIn',
  84750. 'HmdWarpParam'
  84751. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  84752. _this._isRightEye = isRightEye;
  84753. _this._distortionFactors = vrMetrics.distortionK;
  84754. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  84755. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  84756. _this.adaptScaleToCurrentViewport = true;
  84757. _this.onSizeChangedObservable.add(function () {
  84758. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  84759. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  84760. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  84761. });
  84762. _this.onApplyObservable.add(function (effect) {
  84763. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  84764. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  84765. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  84766. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  84767. });
  84768. return _this;
  84769. }
  84770. return VRDistortionCorrectionPostProcess;
  84771. }(BABYLON.PostProcess));
  84772. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  84773. })(BABYLON || (BABYLON = {}));
  84774. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  84775. "use strict";
  84776. var BABYLON;
  84777. (function (BABYLON) {
  84778. var AnaglyphPostProcess = /** @class */ (function (_super) {
  84779. __extends(AnaglyphPostProcess, _super);
  84780. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  84781. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  84782. _this._passedProcess = rigCameras[0]._rigPostProcess;
  84783. _this.onApplyObservable.add(function (effect) {
  84784. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  84785. });
  84786. return _this;
  84787. }
  84788. return AnaglyphPostProcess;
  84789. }(BABYLON.PostProcess));
  84790. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  84791. })(BABYLON || (BABYLON = {}));
  84792. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  84793. "use strict";
  84794. var BABYLON;
  84795. (function (BABYLON) {
  84796. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  84797. __extends(StereoscopicInterlacePostProcess, _super);
  84798. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  84799. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  84800. _this._passedProcess = rigCameras[0]._rigPostProcess;
  84801. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  84802. _this.onSizeChangedObservable.add(function () {
  84803. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  84804. });
  84805. _this.onApplyObservable.add(function (effect) {
  84806. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  84807. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  84808. });
  84809. return _this;
  84810. }
  84811. return StereoscopicInterlacePostProcess;
  84812. }(BABYLON.PostProcess));
  84813. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  84814. })(BABYLON || (BABYLON = {}));
  84815. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  84816. "use strict";
  84817. var BABYLON;
  84818. (function (BABYLON) {
  84819. /**
  84820. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  84821. * Screen rotation is taken into account.
  84822. */
  84823. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  84824. function FreeCameraDeviceOrientationInput() {
  84825. var _this = this;
  84826. this._screenOrientationAngle = 0;
  84827. this._screenQuaternion = new BABYLON.Quaternion();
  84828. this._alpha = 0;
  84829. this._beta = 0;
  84830. this._gamma = 0;
  84831. this._orientationChanged = function () {
  84832. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  84833. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  84834. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  84835. };
  84836. this._deviceOrientation = function (evt) {
  84837. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  84838. _this._beta = evt.beta !== null ? evt.beta : 0;
  84839. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  84840. };
  84841. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  84842. this._orientationChanged();
  84843. }
  84844. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  84845. get: function () {
  84846. return this._camera;
  84847. },
  84848. set: function (camera) {
  84849. this._camera = camera;
  84850. if (this._camera != null && !this._camera.rotationQuaternion) {
  84851. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  84852. }
  84853. },
  84854. enumerable: true,
  84855. configurable: true
  84856. });
  84857. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  84858. window.addEventListener("orientationchange", this._orientationChanged);
  84859. window.addEventListener("deviceorientation", this._deviceOrientation);
  84860. //In certain cases, the attach control is called AFTER orientation was changed,
  84861. //So this is needed.
  84862. this._orientationChanged();
  84863. };
  84864. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  84865. window.removeEventListener("orientationchange", this._orientationChanged);
  84866. window.removeEventListener("deviceorientation", this._deviceOrientation);
  84867. };
  84868. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  84869. //if no device orientation provided, don't update the rotation.
  84870. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  84871. if (!this._alpha)
  84872. return;
  84873. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  84874. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  84875. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  84876. //Mirror on XY Plane
  84877. this._camera.rotationQuaternion.z *= -1;
  84878. this._camera.rotationQuaternion.w *= -1;
  84879. };
  84880. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  84881. return "FreeCameraDeviceOrientationInput";
  84882. };
  84883. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  84884. return "deviceOrientation";
  84885. };
  84886. return FreeCameraDeviceOrientationInput;
  84887. }());
  84888. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  84889. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  84890. })(BABYLON || (BABYLON = {}));
  84891. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  84892. "use strict";
  84893. var BABYLON;
  84894. (function (BABYLON) {
  84895. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  84896. function ArcRotateCameraVRDeviceOrientationInput() {
  84897. this.alphaCorrection = 1;
  84898. this.betaCorrection = 1;
  84899. this.gammaCorrection = 1;
  84900. this._alpha = 0;
  84901. this._gamma = 0;
  84902. this._dirty = false;
  84903. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  84904. }
  84905. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  84906. this.camera.attachControl(element, noPreventDefault);
  84907. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  84908. };
  84909. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  84910. if (evt.alpha !== null) {
  84911. this._alpha = +evt.alpha | 0;
  84912. }
  84913. if (evt.gamma !== null) {
  84914. this._gamma = +evt.gamma | 0;
  84915. }
  84916. this._dirty = true;
  84917. };
  84918. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  84919. if (this._dirty) {
  84920. this._dirty = false;
  84921. if (this._gamma < 0) {
  84922. this._gamma = 180 + this._gamma;
  84923. }
  84924. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  84925. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  84926. }
  84927. };
  84928. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  84929. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  84930. };
  84931. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  84932. return "ArcRotateCameraVRDeviceOrientationInput";
  84933. };
  84934. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  84935. return "VRDeviceOrientation";
  84936. };
  84937. return ArcRotateCameraVRDeviceOrientationInput;
  84938. }());
  84939. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  84940. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  84941. })(BABYLON || (BABYLON = {}));
  84942. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  84943. "use strict";
  84944. var BABYLON;
  84945. (function (BABYLON) {
  84946. var VRCameraMetrics = /** @class */ (function () {
  84947. function VRCameraMetrics() {
  84948. this.compensateDistortion = true;
  84949. }
  84950. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  84951. get: function () {
  84952. return this.hResolution / (2 * this.vResolution);
  84953. },
  84954. enumerable: true,
  84955. configurable: true
  84956. });
  84957. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  84958. get: function () {
  84959. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  84960. },
  84961. enumerable: true,
  84962. configurable: true
  84963. });
  84964. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  84965. get: function () {
  84966. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  84967. var h = (4 * meters) / this.hScreenSize;
  84968. return BABYLON.Matrix.Translation(h, 0, 0);
  84969. },
  84970. enumerable: true,
  84971. configurable: true
  84972. });
  84973. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  84974. get: function () {
  84975. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  84976. var h = (4 * meters) / this.hScreenSize;
  84977. return BABYLON.Matrix.Translation(-h, 0, 0);
  84978. },
  84979. enumerable: true,
  84980. configurable: true
  84981. });
  84982. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  84983. get: function () {
  84984. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  84985. },
  84986. enumerable: true,
  84987. configurable: true
  84988. });
  84989. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  84990. get: function () {
  84991. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  84992. },
  84993. enumerable: true,
  84994. configurable: true
  84995. });
  84996. VRCameraMetrics.GetDefault = function () {
  84997. var result = new VRCameraMetrics();
  84998. result.hResolution = 1280;
  84999. result.vResolution = 800;
  85000. result.hScreenSize = 0.149759993;
  85001. result.vScreenSize = 0.0935999975;
  85002. result.vScreenCenter = 0.0467999987;
  85003. result.eyeToScreenDistance = 0.0410000011;
  85004. result.lensSeparationDistance = 0.0635000020;
  85005. result.interpupillaryDistance = 0.0640000030;
  85006. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  85007. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  85008. result.postProcessScaleFactor = 1.714605507808412;
  85009. result.lensCenterOffset = 0.151976421;
  85010. return result;
  85011. };
  85012. return VRCameraMetrics;
  85013. }());
  85014. BABYLON.VRCameraMetrics = VRCameraMetrics;
  85015. })(BABYLON || (BABYLON = {}));
  85016. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  85017. "use strict";
  85018. var BABYLON;
  85019. (function (BABYLON) {
  85020. /**
  85021. * This represents a WebVR camera.
  85022. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  85023. * @example http://doc.babylonjs.com/how_to/webvr_camera
  85024. */
  85025. var WebVRFreeCamera = /** @class */ (function (_super) {
  85026. __extends(WebVRFreeCamera, _super);
  85027. /**
  85028. * Instantiates a WebVRFreeCamera.
  85029. * @param name The name of the WebVRFreeCamera
  85030. * @param position The starting anchor position for the camera
  85031. * @param scene The scene the camera belongs to
  85032. * @param webVROptions a set of customizable options for the webVRCamera
  85033. */
  85034. function WebVRFreeCamera(name, position, scene, webVROptions) {
  85035. if (webVROptions === void 0) { webVROptions = {}; }
  85036. var _this = _super.call(this, name, position, scene) || this;
  85037. _this.webVROptions = webVROptions;
  85038. /**
  85039. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  85040. */
  85041. _this._vrDevice = null;
  85042. /**
  85043. * The rawPose of the vrDevice.
  85044. */
  85045. _this.rawPose = null;
  85046. _this._specsVersion = "1.1";
  85047. _this._attached = false;
  85048. _this._descendants = [];
  85049. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  85050. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  85051. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  85052. _this._standingMatrix = null;
  85053. /**
  85054. * Represents device position in babylon space.
  85055. */
  85056. _this.devicePosition = BABYLON.Vector3.Zero();
  85057. /**
  85058. * Represents device rotation in babylon space.
  85059. */
  85060. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  85061. /**
  85062. * The scale of the device to be used when translating from device space to babylon space.
  85063. */
  85064. _this.deviceScaleFactor = 1;
  85065. _this._deviceToWorld = BABYLON.Matrix.Identity();
  85066. _this._worldToDevice = BABYLON.Matrix.Identity();
  85067. /**
  85068. * References to the webVR controllers for the vrDevice.
  85069. */
  85070. _this.controllers = [];
  85071. /**
  85072. * Emits an event when a controller is attached.
  85073. */
  85074. _this.onControllersAttachedObservable = new BABYLON.Observable();
  85075. /**
  85076. * Emits an event when a controller's mesh has been loaded;
  85077. */
  85078. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  85079. /**
  85080. * If the rig cameras be used as parent instead of this camera.
  85081. */
  85082. _this.rigParenting = true;
  85083. _this._defaultHeight = undefined;
  85084. _this._workingVector = BABYLON.Vector3.Zero();
  85085. _this._oneVector = BABYLON.Vector3.One();
  85086. _this._workingMatrix = BABYLON.Matrix.Identity();
  85087. _this._cache.position = BABYLON.Vector3.Zero();
  85088. if (webVROptions.defaultHeight) {
  85089. _this._defaultHeight = webVROptions.defaultHeight;
  85090. _this.position.y = _this._defaultHeight;
  85091. }
  85092. _this.minZ = 0.1;
  85093. //legacy support - the compensation boolean was removed.
  85094. if (arguments.length === 5) {
  85095. _this.webVROptions = arguments[4];
  85096. }
  85097. // default webVR options
  85098. if (_this.webVROptions.trackPosition == undefined) {
  85099. _this.webVROptions.trackPosition = true;
  85100. }
  85101. if (_this.webVROptions.controllerMeshes == undefined) {
  85102. _this.webVROptions.controllerMeshes = true;
  85103. }
  85104. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  85105. _this.webVROptions.defaultLightingOnControllers = true;
  85106. }
  85107. _this.rotationQuaternion = new BABYLON.Quaternion();
  85108. if (_this.webVROptions && _this.webVROptions.positionScale) {
  85109. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  85110. }
  85111. //enable VR
  85112. var engine = _this.getEngine();
  85113. _this._onVREnabled = function (success) { if (success) {
  85114. _this.initControllers();
  85115. } };
  85116. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  85117. engine.initWebVR().add(function (event) {
  85118. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  85119. return;
  85120. }
  85121. _this._vrDevice = event.vrDisplay;
  85122. //reset the rig parameters.
  85123. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  85124. if (_this._attached) {
  85125. _this.getEngine().enableVR();
  85126. }
  85127. });
  85128. if (typeof (VRFrameData) !== "undefined")
  85129. _this._frameData = new VRFrameData();
  85130. /**
  85131. * The idea behind the following lines:
  85132. * objects that have the camera as parent should actually have the rig cameras as a parent.
  85133. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  85134. * the second will not show it correctly.
  85135. *
  85136. * To solve this - each object that has the camera as parent will be added to a protected array.
  85137. * When the rig camera renders, it will take this array and set all of those to be its children.
  85138. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  85139. * Amazing!
  85140. */
  85141. scene.onBeforeCameraRenderObservable.add(function (camera) {
  85142. if (camera.parent === _this && _this.rigParenting) {
  85143. _this._descendants = _this.getDescendants(true, function (n) {
  85144. // don't take the cameras or the controllers!
  85145. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  85146. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  85147. return !isController && !isRigCamera;
  85148. });
  85149. _this._descendants.forEach(function (node) {
  85150. node.parent = camera;
  85151. });
  85152. }
  85153. });
  85154. scene.onAfterCameraRenderObservable.add(function (camera) {
  85155. if (camera.parent === _this && _this.rigParenting) {
  85156. _this._descendants.forEach(function (node) {
  85157. node.parent = _this;
  85158. });
  85159. }
  85160. });
  85161. return _this;
  85162. }
  85163. /**
  85164. * Gets the device distance from the ground in meters.
  85165. * @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.
  85166. */
  85167. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  85168. if (this._standingMatrix) {
  85169. // Add standing matrix offset to get real offset from ground in room
  85170. this._standingMatrix.getTranslationToRef(this._workingVector);
  85171. return this._deviceRoomPosition.y + this._workingVector.y;
  85172. }
  85173. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  85174. return this._defaultHeight || 0;
  85175. };
  85176. /**
  85177. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  85178. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  85179. */
  85180. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  85181. var _this = this;
  85182. if (callback === void 0) { callback = function (bool) { }; }
  85183. // Use standing matrix if available
  85184. this.getEngine().initWebVRAsync().then(function (result) {
  85185. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  85186. callback(false);
  85187. }
  85188. else {
  85189. _this._standingMatrix = new BABYLON.Matrix();
  85190. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  85191. if (!_this.getScene().useRightHandedSystem) {
  85192. [2, 6, 8, 9, 14].forEach(function (num) {
  85193. if (_this._standingMatrix) {
  85194. _this._standingMatrix.m[num] *= -1;
  85195. }
  85196. });
  85197. }
  85198. callback(true);
  85199. }
  85200. });
  85201. };
  85202. /**
  85203. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  85204. * @returns A promise with a boolean set to if the standing matrix is supported.
  85205. */
  85206. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  85207. var _this = this;
  85208. return new Promise(function (res, rej) {
  85209. _this.useStandingMatrix(function (supported) {
  85210. res(supported);
  85211. });
  85212. });
  85213. };
  85214. /**
  85215. * Disposes the camera
  85216. */
  85217. WebVRFreeCamera.prototype.dispose = function () {
  85218. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  85219. _super.prototype.dispose.call(this);
  85220. };
  85221. /**
  85222. * Gets a vrController by name.
  85223. * @param name The name of the controller to retreive
  85224. * @returns the controller matching the name specified or null if not found
  85225. */
  85226. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  85227. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  85228. var gp = _a[_i];
  85229. if (gp.hand === name) {
  85230. return gp;
  85231. }
  85232. }
  85233. return null;
  85234. };
  85235. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  85236. /**
  85237. * The controller corrisponding to the users left hand.
  85238. */
  85239. get: function () {
  85240. if (!this._leftController) {
  85241. this._leftController = this.getControllerByName("left");
  85242. }
  85243. return this._leftController;
  85244. },
  85245. enumerable: true,
  85246. configurable: true
  85247. });
  85248. ;
  85249. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  85250. /**
  85251. * The controller corrisponding to the users right hand.
  85252. */
  85253. get: function () {
  85254. if (!this._rightController) {
  85255. this._rightController = this.getControllerByName("right");
  85256. }
  85257. return this._rightController;
  85258. },
  85259. enumerable: true,
  85260. configurable: true
  85261. });
  85262. ;
  85263. /**
  85264. * Casts a ray forward from the vrCamera's gaze.
  85265. * @param length Length of the ray (default: 100)
  85266. * @returns the ray corrisponding to the gaze
  85267. */
  85268. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  85269. if (length === void 0) { length = 100; }
  85270. if (this.leftCamera) {
  85271. // Use left eye to avoid computation to compute center on every call
  85272. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  85273. }
  85274. else {
  85275. return _super.prototype.getForwardRay.call(this, length);
  85276. }
  85277. };
  85278. /**
  85279. * Updates the camera based on device's frame data
  85280. */
  85281. WebVRFreeCamera.prototype._checkInputs = function () {
  85282. if (this._vrDevice && this._vrDevice.isPresenting) {
  85283. this._vrDevice.getFrameData(this._frameData);
  85284. this.updateFromDevice(this._frameData.pose);
  85285. }
  85286. _super.prototype._checkInputs.call(this);
  85287. };
  85288. /**
  85289. * Updates the poseControlled values based on the input device pose.
  85290. * @param poseData Pose coming from the device
  85291. */
  85292. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  85293. if (poseData && poseData.orientation) {
  85294. this.rawPose = poseData;
  85295. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  85296. if (this.getScene().useRightHandedSystem) {
  85297. this._deviceRoomRotationQuaternion.z *= -1;
  85298. this._deviceRoomRotationQuaternion.w *= -1;
  85299. }
  85300. if (this.webVROptions.trackPosition && this.rawPose.position) {
  85301. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  85302. if (this.getScene().useRightHandedSystem) {
  85303. this._deviceRoomPosition.z *= -1;
  85304. }
  85305. }
  85306. }
  85307. };
  85308. /**
  85309. * WebVR's attach control will start broadcasting frames to the device.
  85310. * Note that in certain browsers (chrome for example) this function must be called
  85311. * within a user-interaction callback. Example:
  85312. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  85313. *
  85314. * @param element html element to attach the vrDevice to
  85315. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  85316. */
  85317. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  85318. _super.prototype.attachControl.call(this, element, noPreventDefault);
  85319. this._attached = true;
  85320. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  85321. if (this._vrDevice) {
  85322. this.getEngine().enableVR();
  85323. }
  85324. };
  85325. /**
  85326. * Detaches the camera from the html element and disables VR
  85327. *
  85328. * @param element html element to detach from
  85329. */
  85330. WebVRFreeCamera.prototype.detachControl = function (element) {
  85331. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  85332. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  85333. _super.prototype.detachControl.call(this, element);
  85334. this._attached = false;
  85335. this.getEngine().disableVR();
  85336. };
  85337. /**
  85338. * @returns the name of this class
  85339. */
  85340. WebVRFreeCamera.prototype.getClassName = function () {
  85341. return "WebVRFreeCamera";
  85342. };
  85343. /**
  85344. * Calls resetPose on the vrDisplay
  85345. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  85346. */
  85347. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  85348. //uses the vrDisplay's "resetPose()".
  85349. //pitch and roll won't be affected.
  85350. this._vrDevice.resetPose();
  85351. };
  85352. /**
  85353. * Updates the rig cameras (left and right eye)
  85354. */
  85355. WebVRFreeCamera.prototype._updateRigCameras = function () {
  85356. var camLeft = this._rigCameras[0];
  85357. var camRight = this._rigCameras[1];
  85358. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  85359. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  85360. camLeft.position.copyFrom(this._deviceRoomPosition);
  85361. camRight.position.copyFrom(this._deviceRoomPosition);
  85362. };
  85363. /**
  85364. * Updates the cached values of the camera
  85365. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  85366. */
  85367. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  85368. var _this = this;
  85369. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  85370. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  85371. if (!this.updateCacheCalled) {
  85372. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  85373. this.updateCacheCalled = true;
  85374. this.update();
  85375. }
  85376. // Set working vector to the device position in room space rotated by the new rotation
  85377. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  85378. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  85379. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  85380. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  85381. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  85382. // Add translation from anchor position
  85383. this._deviceToWorld.getTranslationToRef(this._workingVector);
  85384. this._workingVector.addInPlace(this.position);
  85385. this._workingVector.subtractInPlace(this._cache.position);
  85386. this._deviceToWorld.setTranslation(this._workingVector);
  85387. // Set an inverted matrix to be used when updating the camera
  85388. this._deviceToWorld.invertToRef(this._worldToDevice);
  85389. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  85390. this.controllers.forEach(function (controller) {
  85391. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  85392. controller.update();
  85393. });
  85394. }
  85395. if (!ignoreParentClass) {
  85396. _super.prototype._updateCache.call(this);
  85397. }
  85398. this.updateCacheCalled = false;
  85399. };
  85400. /**
  85401. * Updates the current device position and rotation in the babylon world
  85402. */
  85403. WebVRFreeCamera.prototype.update = function () {
  85404. // Get current device position in babylon world
  85405. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  85406. // Get current device rotation in babylon world
  85407. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  85408. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  85409. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  85410. _super.prototype.update.call(this);
  85411. };
  85412. /**
  85413. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  85414. * @returns an identity matrix
  85415. */
  85416. WebVRFreeCamera.prototype._getViewMatrix = function () {
  85417. return BABYLON.Matrix.Identity();
  85418. };
  85419. /**
  85420. * This function is called by the two RIG cameras.
  85421. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  85422. */
  85423. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  85424. var _this = this;
  85425. // Update the parent camera prior to using a child camera to avoid desynchronization
  85426. var parentCamera = this._cameraRigParams["parentCamera"];
  85427. parentCamera._updateCache();
  85428. //WebVR 1.1
  85429. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  85430. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  85431. if (!this.getScene().useRightHandedSystem) {
  85432. [2, 6, 8, 9, 14].forEach(function (num) {
  85433. _this._webvrViewMatrix.m[num] *= -1;
  85434. });
  85435. }
  85436. // update the camera rotation matrix
  85437. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  85438. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  85439. // Computing target and final matrix
  85440. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  85441. // should the view matrix be updated with scale and position offset?
  85442. if (parentCamera.deviceScaleFactor !== 1) {
  85443. this._webvrViewMatrix.invert();
  85444. // scale the position, if set
  85445. if (parentCamera.deviceScaleFactor) {
  85446. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  85447. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  85448. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  85449. }
  85450. this._webvrViewMatrix.invert();
  85451. }
  85452. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  85453. return this._webvrViewMatrix;
  85454. };
  85455. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  85456. var _this = this;
  85457. var parentCamera = this.parent;
  85458. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  85459. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  85460. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  85461. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  85462. //babylon compatible matrix
  85463. if (!this.getScene().useRightHandedSystem) {
  85464. [8, 9, 10, 11].forEach(function (num) {
  85465. _this._projectionMatrix.m[num] *= -1;
  85466. });
  85467. }
  85468. return this._projectionMatrix;
  85469. };
  85470. /**
  85471. * Initializes the controllers and their meshes
  85472. */
  85473. WebVRFreeCamera.prototype.initControllers = function () {
  85474. var _this = this;
  85475. this.controllers = [];
  85476. var manager = this.getScene().gamepadManager;
  85477. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  85478. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  85479. var webVrController = gamepad;
  85480. if (webVrController.defaultModel) {
  85481. webVrController.defaultModel.setEnabled(false);
  85482. }
  85483. if (webVrController.hand === "right") {
  85484. _this._rightController = null;
  85485. }
  85486. if (webVrController.hand === "left") {
  85487. _this._leftController = null;
  85488. }
  85489. var controllerIndex = _this.controllers.indexOf(webVrController);
  85490. if (controllerIndex !== -1) {
  85491. _this.controllers.splice(controllerIndex, 1);
  85492. }
  85493. }
  85494. });
  85495. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  85496. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  85497. var webVrController_1 = gamepad;
  85498. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  85499. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  85500. if (_this.webVROptions.controllerMeshes) {
  85501. if (webVrController_1.defaultModel) {
  85502. webVrController_1.defaultModel.setEnabled(true);
  85503. }
  85504. else {
  85505. // Load the meshes
  85506. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  85507. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  85508. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  85509. if (_this.webVROptions.defaultLightingOnControllers) {
  85510. if (!_this._lightOnControllers) {
  85511. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  85512. }
  85513. var activateLightOnSubMeshes_1 = function (mesh, light) {
  85514. var children = mesh.getChildren();
  85515. if (children.length !== 0) {
  85516. children.forEach(function (mesh) {
  85517. light.includedOnlyMeshes.push(mesh);
  85518. activateLightOnSubMeshes_1(mesh, light);
  85519. });
  85520. }
  85521. };
  85522. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  85523. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  85524. }
  85525. });
  85526. }
  85527. }
  85528. webVrController_1.attachToPoseControlledCamera(_this);
  85529. // since this is async - sanity check. Is the controller already stored?
  85530. if (_this.controllers.indexOf(webVrController_1) === -1) {
  85531. //add to the controllers array
  85532. _this.controllers.push(webVrController_1);
  85533. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  85534. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  85535. // So we're overriding setting left & right manually to be sure
  85536. var firstViveWandDetected = false;
  85537. for (var i = 0; i < _this.controllers.length; i++) {
  85538. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  85539. if (!firstViveWandDetected) {
  85540. firstViveWandDetected = true;
  85541. _this.controllers[i].hand = "left";
  85542. }
  85543. else {
  85544. _this.controllers[i].hand = "right";
  85545. }
  85546. }
  85547. }
  85548. //did we find enough controllers? Great! let the developer know.
  85549. if (_this.controllers.length >= 2) {
  85550. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  85551. }
  85552. }
  85553. }
  85554. });
  85555. };
  85556. return WebVRFreeCamera;
  85557. }(BABYLON.FreeCamera));
  85558. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  85559. })(BABYLON || (BABYLON = {}));
  85560. //# sourceMappingURL=babylon.webVRCamera.js.map
  85561. "use strict";
  85562. var BABYLON;
  85563. (function (BABYLON) {
  85564. // We're mainly based on the logic defined into the FreeCamera code
  85565. /**
  85566. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  85567. * being tilted forward or back and left or right.
  85568. */
  85569. var DeviceOrientationCamera = /** @class */ (function (_super) {
  85570. __extends(DeviceOrientationCamera, _super);
  85571. /**
  85572. * Creates a new device orientation camera
  85573. * @param name The name of the camera
  85574. * @param position The start position camera
  85575. * @param scene The scene the camera belongs to
  85576. */
  85577. function DeviceOrientationCamera(name, position, scene) {
  85578. var _this = _super.call(this, name, position, scene) || this;
  85579. _this._quaternionCache = new BABYLON.Quaternion();
  85580. _this.inputs.addDeviceOrientation();
  85581. return _this;
  85582. }
  85583. /**
  85584. * Gets the current instance class name ("DeviceOrientationCamera").
  85585. * This helps avoiding instanceof at run time.
  85586. * @returns the class name
  85587. */
  85588. DeviceOrientationCamera.prototype.getClassName = function () {
  85589. return "DeviceOrientationCamera";
  85590. };
  85591. /**
  85592. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  85593. */
  85594. DeviceOrientationCamera.prototype._checkInputs = function () {
  85595. _super.prototype._checkInputs.call(this);
  85596. this._quaternionCache.copyFrom(this.rotationQuaternion);
  85597. if (this._initialQuaternion) {
  85598. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  85599. }
  85600. };
  85601. /**
  85602. * Reset the camera to its default orientation on the specified axis only.
  85603. * @param axis The axis to reset
  85604. */
  85605. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  85606. var _this = this;
  85607. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  85608. //can only work if this camera has a rotation quaternion already.
  85609. if (!this.rotationQuaternion)
  85610. return;
  85611. if (!this._initialQuaternion) {
  85612. this._initialQuaternion = new BABYLON.Quaternion();
  85613. }
  85614. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  85615. ['x', 'y', 'z'].forEach(function (axisName) {
  85616. if (!axis[axisName]) {
  85617. _this._initialQuaternion[axisName] = 0;
  85618. }
  85619. else {
  85620. _this._initialQuaternion[axisName] *= -1;
  85621. }
  85622. });
  85623. this._initialQuaternion.normalize();
  85624. //force rotation update
  85625. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  85626. };
  85627. return DeviceOrientationCamera;
  85628. }(BABYLON.FreeCamera));
  85629. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  85630. })(BABYLON || (BABYLON = {}));
  85631. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  85632. "use strict";
  85633. var BABYLON;
  85634. (function (BABYLON) {
  85635. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  85636. __extends(VRDeviceOrientationFreeCamera, _super);
  85637. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  85638. if (compensateDistortion === void 0) { compensateDistortion = true; }
  85639. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  85640. var _this = _super.call(this, name, position, scene) || this;
  85641. vrCameraMetrics.compensateDistortion = compensateDistortion;
  85642. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  85643. return _this;
  85644. }
  85645. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  85646. return "VRDeviceOrientationFreeCamera";
  85647. };
  85648. return VRDeviceOrientationFreeCamera;
  85649. }(BABYLON.DeviceOrientationCamera));
  85650. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  85651. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  85652. __extends(VRDeviceOrientationGamepadCamera, _super);
  85653. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  85654. if (compensateDistortion === void 0) { compensateDistortion = true; }
  85655. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  85656. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  85657. _this.inputs.addGamepad();
  85658. return _this;
  85659. }
  85660. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  85661. return "VRDeviceOrientationGamepadCamera";
  85662. };
  85663. return VRDeviceOrientationGamepadCamera;
  85664. }(VRDeviceOrientationFreeCamera));
  85665. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  85666. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  85667. __extends(VRDeviceOrientationArcRotateCamera, _super);
  85668. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  85669. if (compensateDistortion === void 0) { compensateDistortion = true; }
  85670. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  85671. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  85672. vrCameraMetrics.compensateDistortion = compensateDistortion;
  85673. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  85674. _this.inputs.addVRDeviceOrientation();
  85675. return _this;
  85676. }
  85677. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  85678. return "VRDeviceOrientationArcRotateCamera";
  85679. };
  85680. return VRDeviceOrientationArcRotateCamera;
  85681. }(BABYLON.ArcRotateCamera));
  85682. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  85683. })(BABYLON || (BABYLON = {}));
  85684. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  85685. "use strict";
  85686. var BABYLON;
  85687. (function (BABYLON) {
  85688. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  85689. __extends(AnaglyphFreeCamera, _super);
  85690. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  85691. var _this = _super.call(this, name, position, scene) || this;
  85692. _this.interaxialDistance = interaxialDistance;
  85693. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85694. return _this;
  85695. }
  85696. AnaglyphFreeCamera.prototype.getClassName = function () {
  85697. return "AnaglyphFreeCamera";
  85698. };
  85699. return AnaglyphFreeCamera;
  85700. }(BABYLON.FreeCamera));
  85701. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  85702. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  85703. __extends(AnaglyphArcRotateCamera, _super);
  85704. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  85705. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  85706. _this.interaxialDistance = interaxialDistance;
  85707. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85708. return _this;
  85709. }
  85710. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  85711. return "AnaglyphArcRotateCamera";
  85712. };
  85713. return AnaglyphArcRotateCamera;
  85714. }(BABYLON.ArcRotateCamera));
  85715. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  85716. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  85717. __extends(AnaglyphGamepadCamera, _super);
  85718. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  85719. var _this = _super.call(this, name, position, scene) || this;
  85720. _this.interaxialDistance = interaxialDistance;
  85721. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85722. return _this;
  85723. }
  85724. AnaglyphGamepadCamera.prototype.getClassName = function () {
  85725. return "AnaglyphGamepadCamera";
  85726. };
  85727. return AnaglyphGamepadCamera;
  85728. }(BABYLON.GamepadCamera));
  85729. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  85730. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  85731. __extends(AnaglyphUniversalCamera, _super);
  85732. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  85733. var _this = _super.call(this, name, position, scene) || this;
  85734. _this.interaxialDistance = interaxialDistance;
  85735. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85736. return _this;
  85737. }
  85738. AnaglyphUniversalCamera.prototype.getClassName = function () {
  85739. return "AnaglyphUniversalCamera";
  85740. };
  85741. return AnaglyphUniversalCamera;
  85742. }(BABYLON.UniversalCamera));
  85743. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  85744. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  85745. __extends(StereoscopicFreeCamera, _super);
  85746. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  85747. var _this = _super.call(this, name, position, scene) || this;
  85748. _this.interaxialDistance = interaxialDistance;
  85749. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85750. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85751. return _this;
  85752. }
  85753. StereoscopicFreeCamera.prototype.getClassName = function () {
  85754. return "StereoscopicFreeCamera";
  85755. };
  85756. return StereoscopicFreeCamera;
  85757. }(BABYLON.FreeCamera));
  85758. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  85759. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  85760. __extends(StereoscopicArcRotateCamera, _super);
  85761. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  85762. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  85763. _this.interaxialDistance = interaxialDistance;
  85764. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85765. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85766. return _this;
  85767. }
  85768. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  85769. return "StereoscopicArcRotateCamera";
  85770. };
  85771. return StereoscopicArcRotateCamera;
  85772. }(BABYLON.ArcRotateCamera));
  85773. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  85774. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  85775. __extends(StereoscopicGamepadCamera, _super);
  85776. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  85777. var _this = _super.call(this, name, position, scene) || this;
  85778. _this.interaxialDistance = interaxialDistance;
  85779. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85780. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85781. return _this;
  85782. }
  85783. StereoscopicGamepadCamera.prototype.getClassName = function () {
  85784. return "StereoscopicGamepadCamera";
  85785. };
  85786. return StereoscopicGamepadCamera;
  85787. }(BABYLON.GamepadCamera));
  85788. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  85789. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  85790. __extends(StereoscopicUniversalCamera, _super);
  85791. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  85792. var _this = _super.call(this, name, position, scene) || this;
  85793. _this.interaxialDistance = interaxialDistance;
  85794. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85795. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85796. return _this;
  85797. }
  85798. StereoscopicUniversalCamera.prototype.getClassName = function () {
  85799. return "StereoscopicUniversalCamera";
  85800. };
  85801. return StereoscopicUniversalCamera;
  85802. }(BABYLON.UniversalCamera));
  85803. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  85804. })(BABYLON || (BABYLON = {}));
  85805. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  85806. "use strict";
  85807. var BABYLON;
  85808. (function (BABYLON) {
  85809. var VRExperienceHelperGazer = /** @class */ (function () {
  85810. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  85811. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  85812. this.scene = scene;
  85813. this._pointerDownOnMeshAsked = false;
  85814. this._isActionableMesh = false;
  85815. this._teleportationRequestInitiated = false;
  85816. this._teleportationBackRequestInitiated = false;
  85817. this._dpadPressed = true;
  85818. this._activePointer = false;
  85819. this._id = VRExperienceHelperGazer._idCounter++;
  85820. // Gaze tracker
  85821. if (!gazeTrackerToClone) {
  85822. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  85823. this._gazeTracker.bakeCurrentTransformIntoVertices();
  85824. this._gazeTracker.isPickable = false;
  85825. this._gazeTracker.isVisible = false;
  85826. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  85827. targetMat.specularColor = BABYLON.Color3.Black();
  85828. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  85829. targetMat.backFaceCulling = false;
  85830. this._gazeTracker.material = targetMat;
  85831. }
  85832. else {
  85833. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  85834. }
  85835. }
  85836. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  85837. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  85838. };
  85839. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  85840. this._pointerDownOnMeshAsked = true;
  85841. if (this._currentMeshSelected && this._currentHit) {
  85842. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  85843. }
  85844. };
  85845. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  85846. if (this._currentMeshSelected && this._currentHit) {
  85847. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  85848. }
  85849. this._pointerDownOnMeshAsked = false;
  85850. };
  85851. VRExperienceHelperGazer.prototype._activatePointer = function () {
  85852. this._activePointer = true;
  85853. };
  85854. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  85855. this._activePointer = false;
  85856. };
  85857. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  85858. };
  85859. VRExperienceHelperGazer.prototype.dispose = function () {
  85860. this._interactionsEnabled = false;
  85861. this._teleportationEnabled = false;
  85862. };
  85863. VRExperienceHelperGazer._idCounter = 0;
  85864. return VRExperienceHelperGazer;
  85865. }());
  85866. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  85867. __extends(VRExperienceHelperControllerGazer, _super);
  85868. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  85869. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  85870. _this.webVRController = webVRController;
  85871. // Laser pointer
  85872. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  85873. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  85874. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  85875. laserPointerMaterial.alpha = 0.6;
  85876. _this._laserPointer.material = laserPointerMaterial;
  85877. _this._laserPointer.rotation.x = Math.PI / 2;
  85878. _this._laserPointer.position.z = -0.5;
  85879. _this._laserPointer.isVisible = false;
  85880. if (!webVRController.mesh) {
  85881. // Create an empty mesh that is used prior to loading the high quality model
  85882. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  85883. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  85884. preloadPointerPose.rotation.x = -0.7;
  85885. preloadMesh.addChild(preloadPointerPose);
  85886. webVRController.attachToMesh(preloadMesh);
  85887. }
  85888. _this._setLaserPointerParent(webVRController.mesh);
  85889. return _this;
  85890. }
  85891. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  85892. return this.webVRController.getForwardRay(length);
  85893. };
  85894. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  85895. _super.prototype._activatePointer.call(this);
  85896. this._laserPointer.isVisible = true;
  85897. };
  85898. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  85899. _super.prototype._deactivatePointer.call(this);
  85900. this._laserPointer.isVisible = false;
  85901. };
  85902. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  85903. this._laserPointer.material.emissiveColor = color;
  85904. };
  85905. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  85906. var makeNotPick = function (root) {
  85907. root.name += " laserPointer";
  85908. root.getChildMeshes().forEach(function (c) {
  85909. makeNotPick(c);
  85910. });
  85911. };
  85912. makeNotPick(mesh);
  85913. var childMeshes = mesh.getChildMeshes();
  85914. this.webVRController._pointingPoseNode = null;
  85915. for (var i = 0; i < childMeshes.length; i++) {
  85916. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  85917. mesh = childMeshes[i];
  85918. this.webVRController._pointingPoseNode = mesh;
  85919. break;
  85920. }
  85921. }
  85922. this._laserPointer.parent = mesh;
  85923. };
  85924. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  85925. this._laserPointer.scaling.y = distance;
  85926. this._laserPointer.position.z = -distance / 2;
  85927. };
  85928. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  85929. _super.prototype.dispose.call(this);
  85930. this._laserPointer.dispose();
  85931. };
  85932. return VRExperienceHelperControllerGazer;
  85933. }(VRExperienceHelperGazer));
  85934. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  85935. __extends(VRExperienceHelperCameraGazer, _super);
  85936. function VRExperienceHelperCameraGazer(getCamera, scene) {
  85937. var _this = _super.call(this, scene) || this;
  85938. _this.getCamera = getCamera;
  85939. return _this;
  85940. }
  85941. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  85942. var camera = this.getCamera();
  85943. if (camera) {
  85944. return camera.getForwardRay(length);
  85945. }
  85946. else {
  85947. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  85948. }
  85949. };
  85950. return VRExperienceHelperCameraGazer;
  85951. }(VRExperienceHelperGazer));
  85952. /**
  85953. * Helps to quickly add VR support to an existing scene.
  85954. * See http://doc.babylonjs.com/how_to/webvr_helper
  85955. */
  85956. var VRExperienceHelper = /** @class */ (function () {
  85957. /**
  85958. * Instantiates a VRExperienceHelper.
  85959. * Helps to quickly add VR support to an existing scene.
  85960. * @param scene The scene the VRExperienceHelper belongs to.
  85961. * @param webVROptions Options to modify the vr experience helper's behavior.
  85962. */
  85963. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  85964. if (webVROptions === void 0) { webVROptions = {}; }
  85965. var _this = this;
  85966. this.webVROptions = webVROptions;
  85967. // Can the system support WebVR, even if a headset isn't plugged in?
  85968. this._webVRsupported = false;
  85969. // If WebVR is supported, is a headset plugged in and are we ready to present?
  85970. this._webVRready = false;
  85971. // Are we waiting for the requestPresent callback to complete?
  85972. this._webVRrequesting = false;
  85973. // Are we presenting to the headset right now?
  85974. this._webVRpresenting = false;
  85975. // Are we presenting in the fullscreen fallback?
  85976. this._fullscreenVRpresenting = false;
  85977. /**
  85978. * Observable raised when entering VR.
  85979. */
  85980. this.onEnteringVRObservable = new BABYLON.Observable();
  85981. /**
  85982. * Observable raised when exiting VR.
  85983. */
  85984. this.onExitingVRObservable = new BABYLON.Observable();
  85985. /**
  85986. * Observable raised when controller mesh is loaded.
  85987. */
  85988. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  85989. this._useCustomVRButton = false;
  85990. this._teleportationRequested = false;
  85991. this._teleportActive = false;
  85992. this._floorMeshesCollection = [];
  85993. this._rotationAllowed = true;
  85994. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  85995. this._rotationRightAsked = false;
  85996. this._rotationLeftAsked = false;
  85997. this._isDefaultTeleportationTarget = true;
  85998. this._teleportationFillColor = "#444444";
  85999. this._teleportationBorderColor = "#FFFFFF";
  86000. this._rotationAngle = 0;
  86001. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  86002. this._padSensibilityUp = 0.65;
  86003. this._padSensibilityDown = 0.35;
  86004. this.leftController = null;
  86005. this.rightController = null;
  86006. /**
  86007. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  86008. */
  86009. this.onNewMeshSelected = new BABYLON.Observable();
  86010. /**
  86011. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  86012. */
  86013. this.onNewMeshPicked = new BABYLON.Observable();
  86014. /**
  86015. * Observable raised before camera teleportation
  86016. */
  86017. this.onBeforeCameraTeleport = new BABYLON.Observable();
  86018. /**
  86019. * Observable raised after camera teleportation
  86020. */
  86021. this.onAfterCameraTeleport = new BABYLON.Observable();
  86022. /**
  86023. * Observable raised when current selected mesh gets unselected
  86024. */
  86025. this.onSelectedMeshUnselected = new BABYLON.Observable();
  86026. /**
  86027. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  86028. */
  86029. this.teleportationEnabled = true;
  86030. this._teleportationInitialized = false;
  86031. this._interactionsEnabled = false;
  86032. this._interactionsRequested = false;
  86033. this._displayGaze = true;
  86034. this._displayLaserPointer = true;
  86035. this._onResize = function () {
  86036. _this.moveButtonToBottomRight();
  86037. if (_this._fullscreenVRpresenting && _this._webVRready) {
  86038. _this.exitVR();
  86039. }
  86040. };
  86041. this._onFullscreenChange = function () {
  86042. if (document.fullscreen !== undefined) {
  86043. _this._fullscreenVRpresenting = document.fullscreen;
  86044. }
  86045. else if (document.mozFullScreen !== undefined) {
  86046. _this._fullscreenVRpresenting = document.mozFullScreen;
  86047. }
  86048. else if (document.webkitIsFullScreen !== undefined) {
  86049. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  86050. }
  86051. else if (document.msIsFullScreen !== undefined) {
  86052. _this._fullscreenVRpresenting = document.msIsFullScreen;
  86053. }
  86054. if (!_this._fullscreenVRpresenting && _this._canvas) {
  86055. _this.exitVR();
  86056. if (!_this._useCustomVRButton) {
  86057. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  86058. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  86059. }
  86060. }
  86061. };
  86062. this.beforeRender = function () {
  86063. if (_this.leftController && _this.leftController._activePointer) {
  86064. _this._castRayAndSelectObject(_this.leftController);
  86065. }
  86066. if (_this.rightController && _this.rightController._activePointer) {
  86067. _this._castRayAndSelectObject(_this.rightController);
  86068. }
  86069. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  86070. _this._castRayAndSelectObject(_this._cameraGazer);
  86071. }
  86072. else {
  86073. _this._cameraGazer._gazeTracker.isVisible = false;
  86074. }
  86075. };
  86076. this._onNewGamepadConnected = function (gamepad) {
  86077. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  86078. if (gamepad.leftStick) {
  86079. gamepad.onleftstickchanged(function (stickValues) {
  86080. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  86081. // Listening to classic/xbox gamepad only if no VR controller is active
  86082. if ((!_this.leftController && !_this.rightController) ||
  86083. ((_this.leftController && !_this.leftController._activePointer) &&
  86084. (_this.rightController && !_this.rightController._activePointer))) {
  86085. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  86086. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  86087. }
  86088. }
  86089. });
  86090. }
  86091. if (gamepad.rightStick) {
  86092. gamepad.onrightstickchanged(function (stickValues) {
  86093. if (_this._teleportationInitialized) {
  86094. _this._checkRotate(stickValues, _this._cameraGazer);
  86095. }
  86096. });
  86097. }
  86098. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  86099. gamepad.onbuttondown(function (buttonPressed) {
  86100. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  86101. _this._cameraGazer._selectionPointerDown();
  86102. }
  86103. });
  86104. gamepad.onbuttonup(function (buttonPressed) {
  86105. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  86106. _this._cameraGazer._selectionPointerUp();
  86107. }
  86108. });
  86109. }
  86110. }
  86111. else {
  86112. var webVRController = gamepad;
  86113. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  86114. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  86115. _this.rightController = controller;
  86116. }
  86117. else {
  86118. _this.leftController = controller;
  86119. }
  86120. _this._tryEnableInteractionOnController(controller);
  86121. }
  86122. };
  86123. // 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
  86124. this._tryEnableInteractionOnController = function (controller) {
  86125. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  86126. _this._enableInteractionOnController(controller);
  86127. }
  86128. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  86129. _this._enableTeleportationOnController(controller);
  86130. }
  86131. };
  86132. this._onNewGamepadDisconnected = function (gamepad) {
  86133. if (gamepad instanceof BABYLON.WebVRController) {
  86134. if (gamepad.hand === "left" && _this.leftController != null) {
  86135. _this.leftController.dispose();
  86136. _this.leftController = null;
  86137. }
  86138. if (gamepad.hand === "right" && _this.rightController != null) {
  86139. _this.rightController.dispose();
  86140. _this.rightController = null;
  86141. }
  86142. }
  86143. };
  86144. this._workingVector = BABYLON.Vector3.Zero();
  86145. this._workingQuaternion = BABYLON.Quaternion.Identity();
  86146. this._workingMatrix = BABYLON.Matrix.Identity();
  86147. this._scene = scene;
  86148. this._canvas = scene.getEngine().getRenderingCanvas();
  86149. // Parse options
  86150. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  86151. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  86152. }
  86153. if (webVROptions.createDeviceOrientationCamera === undefined) {
  86154. webVROptions.createDeviceOrientationCamera = true;
  86155. }
  86156. if (webVROptions.defaultHeight === undefined) {
  86157. webVROptions.defaultHeight = 1.7;
  86158. }
  86159. if (webVROptions.useCustomVRButton) {
  86160. this._useCustomVRButton = true;
  86161. if (webVROptions.customVRButton) {
  86162. this._btnVR = webVROptions.customVRButton;
  86163. }
  86164. }
  86165. if (webVROptions.rayLength) {
  86166. this._rayLength = webVROptions.rayLength;
  86167. }
  86168. this._defaultHeight = webVROptions.defaultHeight;
  86169. if (webVROptions.positionScale) {
  86170. this._rayLength *= webVROptions.positionScale;
  86171. this._defaultHeight *= webVROptions.positionScale;
  86172. }
  86173. // Set position
  86174. if (this._scene.activeCamera) {
  86175. this._position = this._scene.activeCamera.position.clone();
  86176. }
  86177. else {
  86178. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  86179. }
  86180. // Set non-vr camera
  86181. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  86182. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  86183. // Copy data from existing camera
  86184. if (this._scene.activeCamera) {
  86185. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  86186. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  86187. // Set rotation from previous camera
  86188. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  86189. var targetCamera = this._scene.activeCamera;
  86190. if (targetCamera.rotationQuaternion) {
  86191. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  86192. }
  86193. else {
  86194. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  86195. }
  86196. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  86197. }
  86198. }
  86199. this._scene.activeCamera = this._deviceOrientationCamera;
  86200. if (this._canvas) {
  86201. this._scene.activeCamera.attachControl(this._canvas);
  86202. }
  86203. }
  86204. else {
  86205. this._existingCamera = this._scene.activeCamera;
  86206. }
  86207. // Create VR cameras
  86208. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  86209. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  86210. }
  86211. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  86212. this._webVRCamera.useStandingMatrix();
  86213. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  86214. // Create default button
  86215. if (!this._useCustomVRButton) {
  86216. this._btnVR = document.createElement("BUTTON");
  86217. this._btnVR.className = "babylonVRicon";
  86218. this._btnVR.id = "babylonVRiconbtn";
  86219. this._btnVR.title = "Click to switch to VR";
  86220. 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) }";
  86221. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  86222. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  86223. // css += ".babylonVRicon.vrdisplaysupported { }";
  86224. // css += ".babylonVRicon.vrdisplayready { }";
  86225. // css += ".babylonVRicon.vrdisplayrequesting { }";
  86226. var style = document.createElement('style');
  86227. style.appendChild(document.createTextNode(css));
  86228. document.getElementsByTagName('head')[0].appendChild(style);
  86229. this.moveButtonToBottomRight();
  86230. }
  86231. // VR button click event
  86232. if (this._btnVR) {
  86233. this._btnVR.addEventListener("click", function () {
  86234. if (!_this.isInVRMode) {
  86235. _this.enterVR();
  86236. }
  86237. else {
  86238. _this.exitVR();
  86239. }
  86240. });
  86241. }
  86242. // Window events
  86243. window.addEventListener("resize", this._onResize);
  86244. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  86245. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  86246. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  86247. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  86248. // Display vr button when headset is connected
  86249. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  86250. this.displayVRButton();
  86251. }
  86252. else {
  86253. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  86254. if (e.vrDisplay) {
  86255. _this.displayVRButton();
  86256. }
  86257. });
  86258. }
  86259. // Exiting VR mode using 'ESC' key on desktop
  86260. this._onKeyDown = function (event) {
  86261. if (event.keyCode === 27 && _this.isInVRMode) {
  86262. _this.exitVR();
  86263. }
  86264. };
  86265. document.addEventListener("keydown", this._onKeyDown);
  86266. // Exiting VR mode double tapping the touch screen
  86267. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  86268. if (_this.isInVRMode) {
  86269. _this.exitVR();
  86270. if (_this._fullscreenVRpresenting) {
  86271. _this._scene.getEngine().switchFullscreen(true);
  86272. }
  86273. }
  86274. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  86275. // Listen for WebVR display changes
  86276. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  86277. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  86278. this._onVRRequestPresentStart = function () {
  86279. _this._webVRrequesting = true;
  86280. _this.updateButtonVisibility();
  86281. };
  86282. this._onVRRequestPresentComplete = function (success) {
  86283. _this._webVRrequesting = false;
  86284. _this.updateButtonVisibility();
  86285. };
  86286. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  86287. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  86288. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  86289. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  86290. scene.onDisposeObservable.add(function () {
  86291. _this.dispose();
  86292. });
  86293. // Gamepad connection events
  86294. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  86295. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  86296. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  86297. this.updateButtonVisibility();
  86298. //create easing functions
  86299. this._circleEase = new BABYLON.CircleEase();
  86300. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  86301. }
  86302. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  86303. /** Return this.onEnteringVRObservable
  86304. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  86305. */
  86306. get: function () {
  86307. return this.onEnteringVRObservable;
  86308. },
  86309. enumerable: true,
  86310. configurable: true
  86311. });
  86312. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  86313. /** Return this.onExitingVRObservable
  86314. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  86315. */
  86316. get: function () {
  86317. return this.onExitingVRObservable;
  86318. },
  86319. enumerable: true,
  86320. configurable: true
  86321. });
  86322. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  86323. /** Return this.onControllerMeshLoadedObservable
  86324. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  86325. */
  86326. get: function () {
  86327. return this.onControllerMeshLoadedObservable;
  86328. },
  86329. enumerable: true,
  86330. configurable: true
  86331. });
  86332. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  86333. /**
  86334. * The mesh used to display where the user is going to teleport.
  86335. */
  86336. get: function () {
  86337. return this._teleportationTarget;
  86338. },
  86339. /**
  86340. * Sets the mesh to be used to display where the user is going to teleport.
  86341. */
  86342. set: function (value) {
  86343. if (value) {
  86344. value.name = "teleportationTarget";
  86345. this._isDefaultTeleportationTarget = false;
  86346. this._teleportationTarget = value;
  86347. }
  86348. },
  86349. enumerable: true,
  86350. configurable: true
  86351. });
  86352. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  86353. /**
  86354. * The mesh used to display where the user is selecting,
  86355. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  86356. * See http://doc.babylonjs.com/resources/baking_transformations
  86357. */
  86358. get: function () {
  86359. return this._cameraGazer._gazeTracker;
  86360. },
  86361. set: function (value) {
  86362. if (value) {
  86363. this._cameraGazer._gazeTracker = value;
  86364. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  86365. this._cameraGazer._gazeTracker.isPickable = false;
  86366. this._cameraGazer._gazeTracker.isVisible = false;
  86367. this._cameraGazer._gazeTracker.name = "gazeTracker";
  86368. if (this.leftController) {
  86369. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  86370. }
  86371. if (this.rightController) {
  86372. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  86373. }
  86374. }
  86375. },
  86376. enumerable: true,
  86377. configurable: true
  86378. });
  86379. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  86380. /**
  86381. * If the ray of the gaze should be displayed.
  86382. */
  86383. get: function () {
  86384. return this._displayGaze;
  86385. },
  86386. /**
  86387. * Sets if the ray of the gaze should be displayed.
  86388. */
  86389. set: function (value) {
  86390. this._displayGaze = value;
  86391. if (!value) {
  86392. this._cameraGazer._gazeTracker.isVisible = false;
  86393. if (this.leftController) {
  86394. this.leftController._gazeTracker.isVisible = false;
  86395. }
  86396. if (this.rightController) {
  86397. this.rightController._gazeTracker.isVisible = false;
  86398. }
  86399. }
  86400. },
  86401. enumerable: true,
  86402. configurable: true
  86403. });
  86404. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  86405. /**
  86406. * If the ray of the LaserPointer should be displayed.
  86407. */
  86408. get: function () {
  86409. return this._displayLaserPointer;
  86410. },
  86411. /**
  86412. * Sets if the ray of the LaserPointer should be displayed.
  86413. */
  86414. set: function (value) {
  86415. this._displayLaserPointer = value;
  86416. if (!value) {
  86417. if (this.rightController) {
  86418. this.rightController._deactivatePointer();
  86419. this.rightController._gazeTracker.isVisible = false;
  86420. }
  86421. if (this.leftController) {
  86422. this.leftController._deactivatePointer();
  86423. this.leftController._gazeTracker.isVisible = false;
  86424. }
  86425. }
  86426. else {
  86427. if (this.rightController) {
  86428. this.rightController._activatePointer();
  86429. }
  86430. else if (this.leftController) {
  86431. this.leftController._activatePointer();
  86432. }
  86433. }
  86434. },
  86435. enumerable: true,
  86436. configurable: true
  86437. });
  86438. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  86439. /**
  86440. * The deviceOrientationCamera used as the camera when not in VR.
  86441. */
  86442. get: function () {
  86443. return this._deviceOrientationCamera;
  86444. },
  86445. enumerable: true,
  86446. configurable: true
  86447. });
  86448. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  86449. /**
  86450. * Based on the current WebVR support, returns the current VR camera used.
  86451. */
  86452. get: function () {
  86453. if (this._webVRready) {
  86454. return this._webVRCamera;
  86455. }
  86456. else {
  86457. return this._scene.activeCamera;
  86458. }
  86459. },
  86460. enumerable: true,
  86461. configurable: true
  86462. });
  86463. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  86464. /**
  86465. * The webVRCamera which is used when in VR.
  86466. */
  86467. get: function () {
  86468. return this._webVRCamera;
  86469. },
  86470. enumerable: true,
  86471. configurable: true
  86472. });
  86473. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  86474. /**
  86475. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  86476. */
  86477. get: function () {
  86478. return this._vrDeviceOrientationCamera;
  86479. },
  86480. enumerable: true,
  86481. configurable: true
  86482. });
  86483. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  86484. get: function () {
  86485. var result = this._cameraGazer._teleportationRequestInitiated
  86486. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  86487. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  86488. return result;
  86489. },
  86490. enumerable: true,
  86491. configurable: true
  86492. });
  86493. // Raised when one of the controller has loaded successfully its associated default mesh
  86494. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  86495. if (this.leftController && this.leftController.webVRController == webVRController) {
  86496. if (webVRController.mesh) {
  86497. this.leftController._setLaserPointerParent(webVRController.mesh);
  86498. }
  86499. }
  86500. if (this.rightController && this.rightController.webVRController == webVRController) {
  86501. if (webVRController.mesh) {
  86502. this.rightController._setLaserPointerParent(webVRController.mesh);
  86503. }
  86504. }
  86505. try {
  86506. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  86507. }
  86508. catch (err) {
  86509. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  86510. }
  86511. };
  86512. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  86513. /**
  86514. * Gets a value indicating if we are currently in VR mode.
  86515. */
  86516. get: function () {
  86517. return this._webVRpresenting || this._fullscreenVRpresenting;
  86518. },
  86519. enumerable: true,
  86520. configurable: true
  86521. });
  86522. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  86523. var vrDisplay = this._scene.getEngine().getVRDevice();
  86524. if (vrDisplay) {
  86525. var wasPresenting = this._webVRpresenting;
  86526. // A VR display is connected
  86527. this._webVRpresenting = vrDisplay.isPresenting;
  86528. if (wasPresenting && !this._webVRpresenting)
  86529. this.exitVR();
  86530. }
  86531. else {
  86532. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  86533. }
  86534. this.updateButtonVisibility();
  86535. };
  86536. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  86537. this._webVRsupported = eventArgs.vrSupported;
  86538. this._webVRready = !!eventArgs.vrDisplay;
  86539. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  86540. this.updateButtonVisibility();
  86541. };
  86542. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  86543. if (this._canvas && !this._useCustomVRButton) {
  86544. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  86545. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  86546. }
  86547. };
  86548. VRExperienceHelper.prototype.displayVRButton = function () {
  86549. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  86550. document.body.appendChild(this._btnVR);
  86551. this._btnVRDisplayed = true;
  86552. }
  86553. };
  86554. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  86555. if (!this._btnVR || this._useCustomVRButton) {
  86556. return;
  86557. }
  86558. this._btnVR.className = "babylonVRicon";
  86559. if (this.isInVRMode) {
  86560. this._btnVR.className += " vrdisplaypresenting";
  86561. }
  86562. else {
  86563. if (this._webVRready)
  86564. this._btnVR.className += " vrdisplayready";
  86565. if (this._webVRsupported)
  86566. this._btnVR.className += " vrdisplaysupported";
  86567. if (this._webVRrequesting)
  86568. this._btnVR.className += " vrdisplayrequesting";
  86569. }
  86570. };
  86571. /**
  86572. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  86573. * Otherwise, will use the fullscreen API.
  86574. */
  86575. VRExperienceHelper.prototype.enterVR = function () {
  86576. if (this.onEnteringVRObservable) {
  86577. try {
  86578. this.onEnteringVRObservable.notifyObservers(this);
  86579. }
  86580. catch (err) {
  86581. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  86582. }
  86583. }
  86584. if (this._scene.activeCamera) {
  86585. this._position = this._scene.activeCamera.position.clone();
  86586. // make sure that we return to the last active camera
  86587. this._existingCamera = this._scene.activeCamera;
  86588. }
  86589. if (this._webVRrequesting)
  86590. return;
  86591. // If WebVR is supported and a headset is connected
  86592. if (this._webVRready) {
  86593. if (!this._webVRpresenting) {
  86594. this._webVRCamera.position = this._position;
  86595. this._scene.activeCamera = this._webVRCamera;
  86596. }
  86597. }
  86598. else if (this._vrDeviceOrientationCamera) {
  86599. this._vrDeviceOrientationCamera.position = this._position;
  86600. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  86601. this._scene.getEngine().switchFullscreen(true);
  86602. this.updateButtonVisibility();
  86603. }
  86604. if (this._scene.activeCamera && this._canvas) {
  86605. this._scene.activeCamera.attachControl(this._canvas);
  86606. }
  86607. if (this._interactionsEnabled) {
  86608. this._scene.registerBeforeRender(this.beforeRender);
  86609. }
  86610. };
  86611. /**
  86612. * Attempt to exit VR, or fullscreen.
  86613. */
  86614. VRExperienceHelper.prototype.exitVR = function () {
  86615. if (this.onExitingVRObservable) {
  86616. try {
  86617. this.onExitingVRObservable.notifyObservers(this);
  86618. }
  86619. catch (err) {
  86620. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  86621. }
  86622. }
  86623. if (this._webVRpresenting) {
  86624. this._scene.getEngine().disableVR();
  86625. }
  86626. if (this._scene.activeCamera) {
  86627. this._position = this._scene.activeCamera.position.clone();
  86628. }
  86629. if (this._deviceOrientationCamera) {
  86630. this._deviceOrientationCamera.position = this._position;
  86631. this._scene.activeCamera = this._deviceOrientationCamera;
  86632. if (this._canvas) {
  86633. this._scene.activeCamera.attachControl(this._canvas);
  86634. }
  86635. }
  86636. else if (this._existingCamera) {
  86637. this._existingCamera.position = this._position;
  86638. this._scene.activeCamera = this._existingCamera;
  86639. }
  86640. this.updateButtonVisibility();
  86641. if (this._interactionsEnabled) {
  86642. this._scene.unregisterBeforeRender(this.beforeRender);
  86643. }
  86644. };
  86645. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  86646. /**
  86647. * The position of the vr experience helper.
  86648. */
  86649. get: function () {
  86650. return this._position;
  86651. },
  86652. /**
  86653. * Sets the position of the vr experience helper.
  86654. */
  86655. set: function (value) {
  86656. this._position = value;
  86657. if (this._scene.activeCamera) {
  86658. this._scene.activeCamera.position = value;
  86659. }
  86660. },
  86661. enumerable: true,
  86662. configurable: true
  86663. });
  86664. /**
  86665. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  86666. */
  86667. VRExperienceHelper.prototype.enableInteractions = function () {
  86668. var _this = this;
  86669. if (!this._interactionsEnabled) {
  86670. this._interactionsRequested = true;
  86671. if (this.leftController) {
  86672. this._enableInteractionOnController(this.leftController);
  86673. }
  86674. if (this.rightController) {
  86675. this._enableInteractionOnController(this.rightController);
  86676. }
  86677. this.raySelectionPredicate = function (mesh) {
  86678. return mesh.isVisible;
  86679. };
  86680. this.meshSelectionPredicate = function (mesh) {
  86681. return true;
  86682. };
  86683. this._raySelectionPredicate = function (mesh) {
  86684. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  86685. && mesh.name.indexOf("teleportationTarget") === -1
  86686. && mesh.name.indexOf("torusTeleportation") === -1
  86687. && mesh.name.indexOf("laserPointer") === -1)) {
  86688. return _this.raySelectionPredicate(mesh);
  86689. }
  86690. return false;
  86691. };
  86692. this._interactionsEnabled = true;
  86693. }
  86694. };
  86695. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  86696. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  86697. if (this._floorMeshesCollection[i].id === mesh.id) {
  86698. return true;
  86699. }
  86700. }
  86701. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  86702. return true;
  86703. }
  86704. return false;
  86705. };
  86706. /**
  86707. * Adds a floor mesh to be used for teleportation.
  86708. * @param floorMesh the mesh to be used for teleportation.
  86709. */
  86710. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  86711. if (!this._floorMeshesCollection) {
  86712. return;
  86713. }
  86714. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  86715. return;
  86716. }
  86717. this._floorMeshesCollection.push(floorMesh);
  86718. };
  86719. /**
  86720. * Removes a floor mesh from being used for teleportation.
  86721. * @param floorMesh the mesh to be removed.
  86722. */
  86723. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  86724. if (!this._floorMeshesCollection) {
  86725. return;
  86726. }
  86727. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  86728. if (meshIndex !== -1) {
  86729. this._floorMeshesCollection.splice(meshIndex, 1);
  86730. }
  86731. };
  86732. /**
  86733. * Enables interactions and teleportation using the VR controllers and gaze.
  86734. * @param vrTeleportationOptions options to modify teleportation behavior.
  86735. */
  86736. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  86737. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  86738. if (!this._teleportationInitialized) {
  86739. this._teleportationRequested = true;
  86740. this.enableInteractions();
  86741. if (vrTeleportationOptions.floorMeshName) {
  86742. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  86743. }
  86744. if (vrTeleportationOptions.floorMeshes) {
  86745. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  86746. }
  86747. if (this.leftController != null) {
  86748. this._enableTeleportationOnController(this.leftController);
  86749. }
  86750. if (this.rightController != null) {
  86751. this._enableTeleportationOnController(this.rightController);
  86752. }
  86753. // Creates an image processing post process for the vignette not relying
  86754. // on the main scene configuration for image processing to reduce setup and spaces
  86755. // (gamma/linear) conflicts.
  86756. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  86757. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  86758. imageProcessingConfiguration.vignetteEnabled = true;
  86759. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  86760. this._webVRCamera.detachPostProcess(this._postProcessMove);
  86761. this._teleportationInitialized = true;
  86762. if (this._isDefaultTeleportationTarget) {
  86763. this._createTeleportationCircles();
  86764. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  86765. }
  86766. }
  86767. };
  86768. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  86769. var _this = this;
  86770. var controllerMesh = controller.webVRController.mesh;
  86771. if (controllerMesh) {
  86772. controller._interactionsEnabled = true;
  86773. controller._activatePointer();
  86774. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  86775. // Enabling / disabling laserPointer
  86776. if (_this._displayLaserPointer && stateObject.value === 1) {
  86777. if (controller._activePointer) {
  86778. controller._deactivatePointer();
  86779. }
  86780. else {
  86781. controller._activatePointer();
  86782. }
  86783. if (_this.displayGaze) {
  86784. controller._gazeTracker.isVisible = controller._activePointer;
  86785. }
  86786. }
  86787. });
  86788. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  86789. if (!controller._pointerDownOnMeshAsked) {
  86790. if (stateObject.value > _this._padSensibilityUp) {
  86791. controller._selectionPointerDown();
  86792. }
  86793. }
  86794. else if (stateObject.value < _this._padSensibilityDown) {
  86795. controller._selectionPointerUp();
  86796. }
  86797. });
  86798. }
  86799. };
  86800. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  86801. // Dont teleport if another gaze already requested teleportation
  86802. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  86803. return;
  86804. }
  86805. if (!gazer._teleportationRequestInitiated) {
  86806. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  86807. gazer._activatePointer();
  86808. gazer._teleportationRequestInitiated = true;
  86809. }
  86810. }
  86811. else {
  86812. // Listening to the proper controller values changes to confirm teleportation
  86813. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  86814. if (this._teleportActive) {
  86815. this._teleportCamera(this._haloCenter);
  86816. }
  86817. gazer._teleportationRequestInitiated = false;
  86818. }
  86819. }
  86820. };
  86821. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  86822. // Only rotate when user is not currently selecting a teleportation location
  86823. if (gazer._teleportationRequestInitiated) {
  86824. return;
  86825. }
  86826. if (!this._rotationLeftAsked) {
  86827. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  86828. this._rotationLeftAsked = true;
  86829. if (this._rotationAllowed) {
  86830. this._rotateCamera(false);
  86831. }
  86832. }
  86833. }
  86834. else {
  86835. if (stateObject.x > -this._padSensibilityDown) {
  86836. this._rotationLeftAsked = false;
  86837. }
  86838. }
  86839. if (!this._rotationRightAsked) {
  86840. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  86841. this._rotationRightAsked = true;
  86842. if (this._rotationAllowed) {
  86843. this._rotateCamera(true);
  86844. }
  86845. }
  86846. }
  86847. else {
  86848. if (stateObject.x < this._padSensibilityDown) {
  86849. this._rotationRightAsked = false;
  86850. }
  86851. }
  86852. };
  86853. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  86854. // Only teleport backwards when user is not currently selecting a teleportation location
  86855. if (gazer._teleportationRequestInitiated) {
  86856. return;
  86857. }
  86858. // Teleport backwards
  86859. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  86860. if (!gazer._teleportationBackRequestInitiated) {
  86861. if (!this.currentVRCamera) {
  86862. return;
  86863. }
  86864. // Get rotation and position of the current camera
  86865. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  86866. var position = this.currentVRCamera.position;
  86867. // If the camera has device position, use that instead
  86868. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  86869. rotation = this.currentVRCamera.deviceRotationQuaternion;
  86870. position = this.currentVRCamera.devicePosition;
  86871. }
  86872. // Get matrix with only the y rotation of the device rotation
  86873. rotation.toEulerAnglesToRef(this._workingVector);
  86874. this._workingVector.z = 0;
  86875. this._workingVector.x = 0;
  86876. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  86877. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  86878. // Rotate backwards ray by device rotation to cast at the ground behind the user
  86879. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  86880. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  86881. var ray = new BABYLON.Ray(position, this._workingVector);
  86882. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  86883. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  86884. this._teleportCamera(hit.pickedPoint);
  86885. }
  86886. gazer._teleportationBackRequestInitiated = true;
  86887. }
  86888. }
  86889. else {
  86890. gazer._teleportationBackRequestInitiated = false;
  86891. }
  86892. };
  86893. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  86894. var _this = this;
  86895. var controllerMesh = controller.webVRController.mesh;
  86896. if (controllerMesh) {
  86897. if (!controller._interactionsEnabled) {
  86898. this._enableInteractionOnController(controller);
  86899. }
  86900. controller._interactionsEnabled = true;
  86901. controller._teleportationEnabled = true;
  86902. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  86903. controller._dpadPressed = false;
  86904. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  86905. controller._dpadPressed = stateObject.pressed;
  86906. if (!controller._dpadPressed) {
  86907. _this._rotationLeftAsked = false;
  86908. _this._rotationRightAsked = false;
  86909. controller._teleportationBackRequestInitiated = false;
  86910. }
  86911. });
  86912. }
  86913. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  86914. if (_this.teleportationEnabled) {
  86915. _this._checkTeleportBackwards(stateObject, controller);
  86916. _this._checkTeleportWithRay(stateObject, controller);
  86917. }
  86918. _this._checkRotate(stateObject, controller);
  86919. });
  86920. }
  86921. };
  86922. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  86923. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  86924. this._teleportationTarget.isPickable = false;
  86925. var length = 512;
  86926. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  86927. dynamicTexture.hasAlpha = true;
  86928. var context = dynamicTexture.getContext();
  86929. var centerX = length / 2;
  86930. var centerY = length / 2;
  86931. var radius = 200;
  86932. context.beginPath();
  86933. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  86934. context.fillStyle = this._teleportationFillColor;
  86935. context.fill();
  86936. context.lineWidth = 10;
  86937. context.strokeStyle = this._teleportationBorderColor;
  86938. context.stroke();
  86939. context.closePath();
  86940. dynamicTexture.update();
  86941. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  86942. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  86943. this._teleportationTarget.material = teleportationCircleMaterial;
  86944. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  86945. torus.isPickable = false;
  86946. torus.parent = this._teleportationTarget;
  86947. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  86948. var keys = [];
  86949. keys.push({
  86950. frame: 0,
  86951. value: 0
  86952. });
  86953. keys.push({
  86954. frame: 30,
  86955. value: 0.4
  86956. });
  86957. keys.push({
  86958. frame: 60,
  86959. value: 0
  86960. });
  86961. animationInnerCircle.setKeys(keys);
  86962. var easingFunction = new BABYLON.SineEase();
  86963. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  86964. animationInnerCircle.setEasingFunction(easingFunction);
  86965. torus.animations = [];
  86966. torus.animations.push(animationInnerCircle);
  86967. this._scene.beginAnimation(torus, 0, 60, true);
  86968. this._hideTeleportationTarget();
  86969. };
  86970. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  86971. this._teleportActive = true;
  86972. if (this._teleportationInitialized) {
  86973. this._teleportationTarget.isVisible = true;
  86974. if (this._isDefaultTeleportationTarget) {
  86975. this._teleportationTarget.getChildren()[0].isVisible = true;
  86976. }
  86977. }
  86978. };
  86979. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  86980. this._teleportActive = false;
  86981. if (this._teleportationInitialized) {
  86982. this._teleportationTarget.isVisible = false;
  86983. if (this._isDefaultTeleportationTarget) {
  86984. this._teleportationTarget.getChildren()[0].isVisible = false;
  86985. }
  86986. }
  86987. };
  86988. VRExperienceHelper.prototype._rotateCamera = function (right) {
  86989. var _this = this;
  86990. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  86991. return;
  86992. }
  86993. if (right) {
  86994. this._rotationAngle++;
  86995. }
  86996. else {
  86997. this._rotationAngle--;
  86998. }
  86999. this.currentVRCamera.animations = [];
  87000. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  87001. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87002. var animationRotationKeys = [];
  87003. animationRotationKeys.push({
  87004. frame: 0,
  87005. value: this.currentVRCamera.rotationQuaternion
  87006. });
  87007. animationRotationKeys.push({
  87008. frame: 6,
  87009. value: target
  87010. });
  87011. animationRotation.setKeys(animationRotationKeys);
  87012. animationRotation.setEasingFunction(this._circleEase);
  87013. this.currentVRCamera.animations.push(animationRotation);
  87014. this._postProcessMove.animations = [];
  87015. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87016. var vignetteWeightKeys = [];
  87017. vignetteWeightKeys.push({
  87018. frame: 0,
  87019. value: 0
  87020. });
  87021. vignetteWeightKeys.push({
  87022. frame: 3,
  87023. value: 4
  87024. });
  87025. vignetteWeightKeys.push({
  87026. frame: 6,
  87027. value: 0
  87028. });
  87029. animationPP.setKeys(vignetteWeightKeys);
  87030. animationPP.setEasingFunction(this._circleEase);
  87031. this._postProcessMove.animations.push(animationPP);
  87032. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87033. var vignetteStretchKeys = [];
  87034. vignetteStretchKeys.push({
  87035. frame: 0,
  87036. value: 0
  87037. });
  87038. vignetteStretchKeys.push({
  87039. frame: 3,
  87040. value: 10
  87041. });
  87042. vignetteStretchKeys.push({
  87043. frame: 6,
  87044. value: 0
  87045. });
  87046. animationPP2.setKeys(vignetteStretchKeys);
  87047. animationPP2.setEasingFunction(this._circleEase);
  87048. this._postProcessMove.animations.push(animationPP2);
  87049. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  87050. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  87051. this._postProcessMove.samples = 4;
  87052. this._webVRCamera.attachPostProcess(this._postProcessMove);
  87053. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  87054. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  87055. });
  87056. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  87057. };
  87058. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  87059. if (hit.pickedPoint) {
  87060. if (gazer._teleportationRequestInitiated) {
  87061. this._displayTeleportationTarget();
  87062. this._haloCenter.copyFrom(hit.pickedPoint);
  87063. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  87064. }
  87065. var pickNormal = hit.getNormal(true, false);
  87066. if (pickNormal) {
  87067. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  87068. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  87069. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  87070. }
  87071. this._teleportationTarget.position.y += 0.1;
  87072. }
  87073. };
  87074. VRExperienceHelper.prototype._teleportCamera = function (location) {
  87075. var _this = this;
  87076. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87077. return;
  87078. }
  87079. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  87080. // offset of the headset from the anchor.
  87081. if (this.webVRCamera.leftCamera) {
  87082. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  87083. this._workingVector.subtractInPlace(this.webVRCamera.position);
  87084. location.subtractToRef(this._workingVector, this._workingVector);
  87085. }
  87086. else {
  87087. this._workingVector.copyFrom(location);
  87088. }
  87089. // Add height to account for user's height offset
  87090. if (this.isInVRMode) {
  87091. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  87092. }
  87093. else {
  87094. this._workingVector.y += this._defaultHeight;
  87095. }
  87096. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  87097. // Create animation from the camera's position to the new location
  87098. this.currentVRCamera.animations = [];
  87099. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87100. var animationCameraTeleportationKeys = [{
  87101. frame: 0,
  87102. value: this.currentVRCamera.position
  87103. },
  87104. {
  87105. frame: 11,
  87106. value: this._workingVector
  87107. }
  87108. ];
  87109. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  87110. animationCameraTeleportation.setEasingFunction(this._circleEase);
  87111. this.currentVRCamera.animations.push(animationCameraTeleportation);
  87112. this._postProcessMove.animations = [];
  87113. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87114. var vignetteWeightKeys = [];
  87115. vignetteWeightKeys.push({
  87116. frame: 0,
  87117. value: 0
  87118. });
  87119. vignetteWeightKeys.push({
  87120. frame: 5,
  87121. value: 8
  87122. });
  87123. vignetteWeightKeys.push({
  87124. frame: 11,
  87125. value: 0
  87126. });
  87127. animationPP.setKeys(vignetteWeightKeys);
  87128. this._postProcessMove.animations.push(animationPP);
  87129. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87130. var vignetteStretchKeys = [];
  87131. vignetteStretchKeys.push({
  87132. frame: 0,
  87133. value: 0
  87134. });
  87135. vignetteStretchKeys.push({
  87136. frame: 5,
  87137. value: 10
  87138. });
  87139. vignetteStretchKeys.push({
  87140. frame: 11,
  87141. value: 0
  87142. });
  87143. animationPP2.setKeys(vignetteStretchKeys);
  87144. this._postProcessMove.animations.push(animationPP2);
  87145. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  87146. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  87147. this._webVRCamera.attachPostProcess(this._postProcessMove);
  87148. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  87149. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  87150. });
  87151. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  87152. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  87153. });
  87154. this._hideTeleportationTarget();
  87155. };
  87156. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  87157. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87158. return;
  87159. }
  87160. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  87161. // Moving the gazeTracker on the mesh face targetted
  87162. if (hit && hit.pickedPoint) {
  87163. if (this._displayGaze) {
  87164. var multiplier = 1;
  87165. gazer._gazeTracker.isVisible = true;
  87166. if (gazer._isActionableMesh) {
  87167. multiplier = 3;
  87168. }
  87169. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  87170. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  87171. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  87172. var pickNormal = hit.getNormal();
  87173. // To avoid z-fighting
  87174. var deltaFighting = 0.002;
  87175. if (pickNormal) {
  87176. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  87177. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  87178. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  87179. }
  87180. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  87181. if (gazer._gazeTracker.position.x < 0) {
  87182. gazer._gazeTracker.position.x += deltaFighting;
  87183. }
  87184. else {
  87185. gazer._gazeTracker.position.x -= deltaFighting;
  87186. }
  87187. if (gazer._gazeTracker.position.y < 0) {
  87188. gazer._gazeTracker.position.y += deltaFighting;
  87189. }
  87190. else {
  87191. gazer._gazeTracker.position.y -= deltaFighting;
  87192. }
  87193. if (gazer._gazeTracker.position.z < 0) {
  87194. gazer._gazeTracker.position.z += deltaFighting;
  87195. }
  87196. else {
  87197. gazer._gazeTracker.position.z -= deltaFighting;
  87198. }
  87199. }
  87200. // Changing the size of the laser pointer based on the distance from the targetted point
  87201. gazer._updatePointerDistance(hit.distance);
  87202. }
  87203. else {
  87204. gazer._gazeTracker.isVisible = false;
  87205. }
  87206. if (hit && hit.pickedMesh) {
  87207. gazer._currentHit = hit;
  87208. if (gazer._pointerDownOnMeshAsked) {
  87209. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  87210. }
  87211. // The object selected is the floor, we're in a teleportation scenario
  87212. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  87213. // Moving the teleportation area to this targetted point
  87214. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  87215. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  87216. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  87217. }
  87218. gazer._currentMeshSelected = null;
  87219. if (gazer._teleportationRequestInitiated) {
  87220. this._moveTeleportationSelectorTo(hit, gazer);
  87221. }
  87222. return;
  87223. }
  87224. // If not, we're in a selection scenario
  87225. //this._teleportationAllowed = false;
  87226. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  87227. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  87228. this.onNewMeshPicked.notifyObservers(hit);
  87229. gazer._currentMeshSelected = hit.pickedMesh;
  87230. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  87231. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  87232. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  87233. gazer._isActionableMesh = true;
  87234. }
  87235. else {
  87236. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87237. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87238. gazer._isActionableMesh = false;
  87239. }
  87240. try {
  87241. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  87242. }
  87243. catch (err) {
  87244. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  87245. }
  87246. }
  87247. else {
  87248. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  87249. gazer._currentMeshSelected = null;
  87250. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87251. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87252. }
  87253. }
  87254. }
  87255. else {
  87256. gazer._currentHit = null;
  87257. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  87258. gazer._currentMeshSelected = null;
  87259. //this._teleportationAllowed = false;
  87260. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87261. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87262. }
  87263. };
  87264. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  87265. if (mesh) {
  87266. this.onSelectedMeshUnselected.notifyObservers(mesh);
  87267. }
  87268. };
  87269. /**
  87270. * Sets the color of the laser ray from the vr controllers.
  87271. * @param color new color for the ray.
  87272. */
  87273. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  87274. if (this.leftController) {
  87275. this.leftController._setLaserPointerColor(color);
  87276. }
  87277. if (this.rightController) {
  87278. this.rightController._setLaserPointerColor(color);
  87279. }
  87280. };
  87281. /**
  87282. * Sets the color of the ray from the vr headsets gaze.
  87283. * @param color new color for the ray.
  87284. */
  87285. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  87286. if (!this._cameraGazer._gazeTracker.material) {
  87287. return;
  87288. }
  87289. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  87290. if (this.leftController) {
  87291. this.leftController._gazeTracker.material.emissiveColor = color;
  87292. }
  87293. if (this.rightController) {
  87294. this.rightController._gazeTracker.material.emissiveColor = color;
  87295. }
  87296. };
  87297. /**
  87298. * Exits VR and disposes of the vr experience helper
  87299. */
  87300. VRExperienceHelper.prototype.dispose = function () {
  87301. if (this.isInVRMode) {
  87302. this.exitVR();
  87303. }
  87304. if (this._postProcessMove) {
  87305. this._postProcessMove.dispose();
  87306. }
  87307. if (this._webVRCamera) {
  87308. this._webVRCamera.dispose();
  87309. }
  87310. if (this._vrDeviceOrientationCamera) {
  87311. this._vrDeviceOrientationCamera.dispose();
  87312. }
  87313. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  87314. document.body.removeChild(this._btnVR);
  87315. }
  87316. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  87317. this._deviceOrientationCamera.dispose();
  87318. }
  87319. if (this._cameraGazer) {
  87320. this._cameraGazer.dispose();
  87321. }
  87322. if (this.leftController) {
  87323. this.leftController.dispose();
  87324. }
  87325. if (this.rightController) {
  87326. this.rightController.dispose();
  87327. }
  87328. if (this._teleportationTarget) {
  87329. this._teleportationTarget.dispose();
  87330. }
  87331. this._floorMeshesCollection = [];
  87332. document.removeEventListener("keydown", this._onKeyDown);
  87333. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87334. window.removeEventListener("resize", this._onResize);
  87335. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  87336. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  87337. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  87338. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  87339. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  87340. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  87341. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  87342. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87343. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  87344. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  87345. this._scene.unregisterBeforeRender(this.beforeRender);
  87346. };
  87347. /**
  87348. * Gets the name of the VRExperienceHelper class
  87349. * @returns "VRExperienceHelper"
  87350. */
  87351. VRExperienceHelper.prototype.getClassName = function () {
  87352. return "VRExperienceHelper";
  87353. };
  87354. return VRExperienceHelper;
  87355. }());
  87356. BABYLON.VRExperienceHelper = VRExperienceHelper;
  87357. })(BABYLON || (BABYLON = {}));
  87358. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  87359. "use strict";
  87360. // Mainly based on these 2 articles :
  87361. // 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
  87362. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  87363. var BABYLON;
  87364. (function (BABYLON) {
  87365. var JoystickAxis;
  87366. (function (JoystickAxis) {
  87367. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  87368. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  87369. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  87370. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  87371. var VirtualJoystick = /** @class */ (function () {
  87372. function VirtualJoystick(leftJoystick) {
  87373. var _this = this;
  87374. if (leftJoystick) {
  87375. this._leftJoystick = true;
  87376. }
  87377. else {
  87378. this._leftJoystick = false;
  87379. }
  87380. VirtualJoystick._globalJoystickIndex++;
  87381. // By default left & right arrow keys are moving the X
  87382. // and up & down keys are moving the Y
  87383. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  87384. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  87385. this.reverseLeftRight = false;
  87386. this.reverseUpDown = false;
  87387. // collections of pointers
  87388. this._touches = new BABYLON.StringDictionary();
  87389. this.deltaPosition = BABYLON.Vector3.Zero();
  87390. this._joystickSensibility = 25;
  87391. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  87392. this._onResize = function (evt) {
  87393. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  87394. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  87395. if (VirtualJoystick.vjCanvas) {
  87396. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  87397. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  87398. }
  87399. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  87400. };
  87401. // injecting a canvas element on top of the canvas 3D game
  87402. if (!VirtualJoystick.vjCanvas) {
  87403. window.addEventListener("resize", this._onResize, false);
  87404. VirtualJoystick.vjCanvas = document.createElement("canvas");
  87405. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  87406. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  87407. VirtualJoystick.vjCanvas.width = window.innerWidth;
  87408. VirtualJoystick.vjCanvas.height = window.innerHeight;
  87409. VirtualJoystick.vjCanvas.style.width = "100%";
  87410. VirtualJoystick.vjCanvas.style.height = "100%";
  87411. VirtualJoystick.vjCanvas.style.position = "absolute";
  87412. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  87413. VirtualJoystick.vjCanvas.style.top = "0px";
  87414. VirtualJoystick.vjCanvas.style.left = "0px";
  87415. VirtualJoystick.vjCanvas.style.zIndex = "5";
  87416. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  87417. // Support for jQuery PEP polyfill
  87418. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  87419. var context = VirtualJoystick.vjCanvas.getContext('2d');
  87420. if (!context) {
  87421. throw new Error("Unable to create canvas for virtual joystick");
  87422. }
  87423. VirtualJoystick.vjCanvasContext = context;
  87424. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  87425. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  87426. document.body.appendChild(VirtualJoystick.vjCanvas);
  87427. }
  87428. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  87429. this.pressed = false;
  87430. // default joystick color
  87431. this._joystickColor = "cyan";
  87432. this._joystickPointerID = -1;
  87433. // current joystick position
  87434. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  87435. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  87436. // origin joystick position
  87437. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  87438. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  87439. this._onPointerDownHandlerRef = function (evt) {
  87440. _this._onPointerDown(evt);
  87441. };
  87442. this._onPointerMoveHandlerRef = function (evt) {
  87443. _this._onPointerMove(evt);
  87444. };
  87445. this._onPointerUpHandlerRef = function (evt) {
  87446. _this._onPointerUp(evt);
  87447. };
  87448. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  87449. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  87450. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  87451. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  87452. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  87453. evt.preventDefault(); // Disables system menu
  87454. }, false);
  87455. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  87456. }
  87457. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  87458. this._joystickSensibility = newJoystickSensibility;
  87459. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  87460. };
  87461. VirtualJoystick.prototype._onPointerDown = function (e) {
  87462. var positionOnScreenCondition;
  87463. e.preventDefault();
  87464. if (this._leftJoystick === true) {
  87465. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  87466. }
  87467. else {
  87468. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  87469. }
  87470. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  87471. // First contact will be dedicated to the virtual joystick
  87472. this._joystickPointerID = e.pointerId;
  87473. this._joystickPointerStartPos.x = e.clientX;
  87474. this._joystickPointerStartPos.y = e.clientY;
  87475. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  87476. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  87477. this._deltaJoystickVector.x = 0;
  87478. this._deltaJoystickVector.y = 0;
  87479. this.pressed = true;
  87480. this._touches.add(e.pointerId.toString(), e);
  87481. }
  87482. else {
  87483. // You can only trigger the action buttons with a joystick declared
  87484. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  87485. this._action();
  87486. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  87487. }
  87488. }
  87489. };
  87490. VirtualJoystick.prototype._onPointerMove = function (e) {
  87491. // If the current pointer is the one associated to the joystick (first touch contact)
  87492. if (this._joystickPointerID == e.pointerId) {
  87493. this._joystickPointerPos.x = e.clientX;
  87494. this._joystickPointerPos.y = e.clientY;
  87495. this._deltaJoystickVector = this._joystickPointerPos.clone();
  87496. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  87497. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  87498. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  87499. switch (this._axisTargetedByLeftAndRight) {
  87500. case JoystickAxis.X:
  87501. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  87502. break;
  87503. case JoystickAxis.Y:
  87504. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  87505. break;
  87506. case JoystickAxis.Z:
  87507. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  87508. break;
  87509. }
  87510. var directionUpDown = this.reverseUpDown ? 1 : -1;
  87511. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  87512. switch (this._axisTargetedByUpAndDown) {
  87513. case JoystickAxis.X:
  87514. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  87515. break;
  87516. case JoystickAxis.Y:
  87517. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  87518. break;
  87519. case JoystickAxis.Z:
  87520. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  87521. break;
  87522. }
  87523. }
  87524. else {
  87525. var data = this._touches.get(e.pointerId.toString());
  87526. if (data) {
  87527. data.x = e.clientX;
  87528. data.y = e.clientY;
  87529. }
  87530. }
  87531. };
  87532. VirtualJoystick.prototype._onPointerUp = function (e) {
  87533. if (this._joystickPointerID == e.pointerId) {
  87534. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  87535. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  87536. this._joystickPointerID = -1;
  87537. this.pressed = false;
  87538. }
  87539. else {
  87540. var touch = this._touches.get(e.pointerId.toString());
  87541. if (touch) {
  87542. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  87543. }
  87544. }
  87545. this._deltaJoystickVector.x = 0;
  87546. this._deltaJoystickVector.y = 0;
  87547. this._touches.remove(e.pointerId.toString());
  87548. };
  87549. /**
  87550. * Change the color of the virtual joystick
  87551. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  87552. */
  87553. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  87554. this._joystickColor = newColor;
  87555. };
  87556. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  87557. this._action = action;
  87558. };
  87559. // Define which axis you'd like to control for left & right
  87560. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  87561. switch (axis) {
  87562. case JoystickAxis.X:
  87563. case JoystickAxis.Y:
  87564. case JoystickAxis.Z:
  87565. this._axisTargetedByLeftAndRight = axis;
  87566. break;
  87567. default:
  87568. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  87569. break;
  87570. }
  87571. };
  87572. // Define which axis you'd like to control for up & down
  87573. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  87574. switch (axis) {
  87575. case JoystickAxis.X:
  87576. case JoystickAxis.Y:
  87577. case JoystickAxis.Z:
  87578. this._axisTargetedByUpAndDown = axis;
  87579. break;
  87580. default:
  87581. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  87582. break;
  87583. }
  87584. };
  87585. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  87586. var _this = this;
  87587. if (this.pressed) {
  87588. this._touches.forEach(function (key, touch) {
  87589. if (touch.pointerId === _this._joystickPointerID) {
  87590. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  87591. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  87592. VirtualJoystick.vjCanvasContext.beginPath();
  87593. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  87594. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  87595. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  87596. VirtualJoystick.vjCanvasContext.stroke();
  87597. VirtualJoystick.vjCanvasContext.closePath();
  87598. VirtualJoystick.vjCanvasContext.beginPath();
  87599. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  87600. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  87601. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  87602. VirtualJoystick.vjCanvasContext.stroke();
  87603. VirtualJoystick.vjCanvasContext.closePath();
  87604. VirtualJoystick.vjCanvasContext.beginPath();
  87605. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  87606. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  87607. VirtualJoystick.vjCanvasContext.stroke();
  87608. VirtualJoystick.vjCanvasContext.closePath();
  87609. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  87610. }
  87611. else {
  87612. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  87613. VirtualJoystick.vjCanvasContext.beginPath();
  87614. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  87615. VirtualJoystick.vjCanvasContext.beginPath();
  87616. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  87617. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  87618. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  87619. VirtualJoystick.vjCanvasContext.stroke();
  87620. VirtualJoystick.vjCanvasContext.closePath();
  87621. touch.prevX = touch.x;
  87622. touch.prevY = touch.y;
  87623. }
  87624. ;
  87625. });
  87626. }
  87627. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  87628. };
  87629. VirtualJoystick.prototype.releaseCanvas = function () {
  87630. if (VirtualJoystick.vjCanvas) {
  87631. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  87632. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  87633. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  87634. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  87635. window.removeEventListener("resize", this._onResize);
  87636. document.body.removeChild(VirtualJoystick.vjCanvas);
  87637. VirtualJoystick.vjCanvas = null;
  87638. }
  87639. };
  87640. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  87641. VirtualJoystick._globalJoystickIndex = 0;
  87642. return VirtualJoystick;
  87643. }());
  87644. BABYLON.VirtualJoystick = VirtualJoystick;
  87645. })(BABYLON || (BABYLON = {}));
  87646. //# sourceMappingURL=babylon.virtualJoystick.js.map
  87647. "use strict";
  87648. var BABYLON;
  87649. (function (BABYLON) {
  87650. // We're mainly based on the logic defined into the FreeCamera code
  87651. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  87652. __extends(VirtualJoysticksCamera, _super);
  87653. function VirtualJoysticksCamera(name, position, scene) {
  87654. var _this = _super.call(this, name, position, scene) || this;
  87655. _this.inputs.addVirtualJoystick();
  87656. return _this;
  87657. }
  87658. VirtualJoysticksCamera.prototype.getClassName = function () {
  87659. return "VirtualJoysticksCamera";
  87660. };
  87661. return VirtualJoysticksCamera;
  87662. }(BABYLON.FreeCamera));
  87663. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  87664. })(BABYLON || (BABYLON = {}));
  87665. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  87666. "use strict";
  87667. var BABYLON;
  87668. (function (BABYLON) {
  87669. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  87670. function FreeCameraVirtualJoystickInput() {
  87671. }
  87672. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  87673. return this._leftjoystick;
  87674. };
  87675. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  87676. return this._rightjoystick;
  87677. };
  87678. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  87679. if (this._leftjoystick) {
  87680. var camera = this.camera;
  87681. var speed = camera._computeLocalCameraSpeed() * 50;
  87682. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  87683. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  87684. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  87685. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  87686. if (!this._leftjoystick.pressed) {
  87687. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  87688. }
  87689. if (!this._rightjoystick.pressed) {
  87690. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  87691. }
  87692. }
  87693. };
  87694. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  87695. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  87696. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  87697. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  87698. this._leftjoystick.setJoystickSensibility(0.15);
  87699. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  87700. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  87701. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  87702. this._rightjoystick.reverseUpDown = true;
  87703. this._rightjoystick.setJoystickSensibility(0.05);
  87704. this._rightjoystick.setJoystickColor("yellow");
  87705. };
  87706. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  87707. this._leftjoystick.releaseCanvas();
  87708. this._rightjoystick.releaseCanvas();
  87709. };
  87710. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  87711. return "FreeCameraVirtualJoystickInput";
  87712. };
  87713. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  87714. return "virtualJoystick";
  87715. };
  87716. return FreeCameraVirtualJoystickInput;
  87717. }());
  87718. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  87719. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  87720. })(BABYLON || (BABYLON = {}));
  87721. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  87722. "use strict";
  87723. var BABYLON;
  87724. (function (BABYLON) {
  87725. var SimplificationSettings = /** @class */ (function () {
  87726. function SimplificationSettings(quality, distance, optimizeMesh) {
  87727. this.quality = quality;
  87728. this.distance = distance;
  87729. this.optimizeMesh = optimizeMesh;
  87730. }
  87731. return SimplificationSettings;
  87732. }());
  87733. BABYLON.SimplificationSettings = SimplificationSettings;
  87734. var SimplificationQueue = /** @class */ (function () {
  87735. function SimplificationQueue() {
  87736. this.running = false;
  87737. this._simplificationArray = [];
  87738. }
  87739. SimplificationQueue.prototype.addTask = function (task) {
  87740. this._simplificationArray.push(task);
  87741. };
  87742. SimplificationQueue.prototype.executeNext = function () {
  87743. var task = this._simplificationArray.pop();
  87744. if (task) {
  87745. this.running = true;
  87746. this.runSimplification(task);
  87747. }
  87748. else {
  87749. this.running = false;
  87750. }
  87751. };
  87752. SimplificationQueue.prototype.runSimplification = function (task) {
  87753. var _this = this;
  87754. if (task.parallelProcessing) {
  87755. //parallel simplifier
  87756. task.settings.forEach(function (setting) {
  87757. var simplifier = _this.getSimplifier(task);
  87758. simplifier.simplify(setting, function (newMesh) {
  87759. task.mesh.addLODLevel(setting.distance, newMesh);
  87760. newMesh.isVisible = true;
  87761. //check if it is the last
  87762. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  87763. //all done, run the success callback.
  87764. task.successCallback();
  87765. }
  87766. _this.executeNext();
  87767. });
  87768. });
  87769. }
  87770. else {
  87771. //single simplifier.
  87772. var simplifier = this.getSimplifier(task);
  87773. var runDecimation = function (setting, callback) {
  87774. simplifier.simplify(setting, function (newMesh) {
  87775. task.mesh.addLODLevel(setting.distance, newMesh);
  87776. newMesh.isVisible = true;
  87777. //run the next quality level
  87778. callback();
  87779. });
  87780. };
  87781. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  87782. runDecimation(task.settings[loop.index], function () {
  87783. loop.executeNext();
  87784. });
  87785. }, function () {
  87786. //execution ended, run the success callback.
  87787. if (task.successCallback) {
  87788. task.successCallback();
  87789. }
  87790. _this.executeNext();
  87791. });
  87792. }
  87793. };
  87794. SimplificationQueue.prototype.getSimplifier = function (task) {
  87795. switch (task.simplificationType) {
  87796. case SimplificationType.QUADRATIC:
  87797. default:
  87798. return new QuadraticErrorSimplification(task.mesh);
  87799. }
  87800. };
  87801. return SimplificationQueue;
  87802. }());
  87803. BABYLON.SimplificationQueue = SimplificationQueue;
  87804. /**
  87805. * The implemented types of simplification.
  87806. * At the moment only Quadratic Error Decimation is implemented.
  87807. */
  87808. var SimplificationType;
  87809. (function (SimplificationType) {
  87810. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  87811. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  87812. var DecimationTriangle = /** @class */ (function () {
  87813. function DecimationTriangle(vertices) {
  87814. this.vertices = vertices;
  87815. this.error = new Array(4);
  87816. this.deleted = false;
  87817. this.isDirty = false;
  87818. this.deletePending = false;
  87819. this.borderFactor = 0;
  87820. }
  87821. return DecimationTriangle;
  87822. }());
  87823. BABYLON.DecimationTriangle = DecimationTriangle;
  87824. var DecimationVertex = /** @class */ (function () {
  87825. function DecimationVertex(position, id) {
  87826. this.position = position;
  87827. this.id = id;
  87828. this.isBorder = true;
  87829. this.q = new QuadraticMatrix();
  87830. this.triangleCount = 0;
  87831. this.triangleStart = 0;
  87832. this.originalOffsets = [];
  87833. }
  87834. DecimationVertex.prototype.updatePosition = function (newPosition) {
  87835. this.position.copyFrom(newPosition);
  87836. };
  87837. return DecimationVertex;
  87838. }());
  87839. BABYLON.DecimationVertex = DecimationVertex;
  87840. var QuadraticMatrix = /** @class */ (function () {
  87841. function QuadraticMatrix(data) {
  87842. this.data = new Array(10);
  87843. for (var i = 0; i < 10; ++i) {
  87844. if (data && data[i]) {
  87845. this.data[i] = data[i];
  87846. }
  87847. else {
  87848. this.data[i] = 0;
  87849. }
  87850. }
  87851. }
  87852. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  87853. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  87854. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  87855. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  87856. return det;
  87857. };
  87858. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  87859. for (var i = 0; i < 10; ++i) {
  87860. this.data[i] += matrix.data[i];
  87861. }
  87862. };
  87863. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  87864. for (var i = 0; i < 10; ++i) {
  87865. this.data[i] += data[i];
  87866. }
  87867. };
  87868. QuadraticMatrix.prototype.add = function (matrix) {
  87869. var m = new QuadraticMatrix();
  87870. for (var i = 0; i < 10; ++i) {
  87871. m.data[i] = this.data[i] + matrix.data[i];
  87872. }
  87873. return m;
  87874. };
  87875. QuadraticMatrix.FromData = function (a, b, c, d) {
  87876. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  87877. };
  87878. //returning an array to avoid garbage collection
  87879. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  87880. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  87881. };
  87882. return QuadraticMatrix;
  87883. }());
  87884. BABYLON.QuadraticMatrix = QuadraticMatrix;
  87885. var Reference = /** @class */ (function () {
  87886. function Reference(vertexId, triangleId) {
  87887. this.vertexId = vertexId;
  87888. this.triangleId = triangleId;
  87889. }
  87890. return Reference;
  87891. }());
  87892. BABYLON.Reference = Reference;
  87893. /**
  87894. * An implementation of the Quadratic Error simplification algorithm.
  87895. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  87896. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  87897. * @author RaananW
  87898. */
  87899. var QuadraticErrorSimplification = /** @class */ (function () {
  87900. function QuadraticErrorSimplification(_mesh) {
  87901. this._mesh = _mesh;
  87902. this.syncIterations = 5000;
  87903. this.aggressiveness = 7;
  87904. this.decimationIterations = 100;
  87905. this.boundingBoxEpsilon = BABYLON.Epsilon;
  87906. }
  87907. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  87908. var _this = this;
  87909. this.initDecimatedMesh();
  87910. //iterating through the submeshes array, one after the other.
  87911. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  87912. _this.initWithMesh(loop.index, function () {
  87913. _this.runDecimation(settings, loop.index, function () {
  87914. loop.executeNext();
  87915. });
  87916. }, settings.optimizeMesh);
  87917. }, function () {
  87918. setTimeout(function () {
  87919. successCallback(_this._reconstructedMesh);
  87920. }, 0);
  87921. });
  87922. };
  87923. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  87924. var _this = this;
  87925. var targetCount = ~~(this.triangles.length * settings.quality);
  87926. var deletedTriangles = 0;
  87927. var triangleCount = this.triangles.length;
  87928. var iterationFunction = function (iteration, callback) {
  87929. setTimeout(function () {
  87930. if (iteration % 5 === 0) {
  87931. _this.updateMesh(iteration === 0);
  87932. }
  87933. for (var i = 0; i < _this.triangles.length; ++i) {
  87934. _this.triangles[i].isDirty = false;
  87935. }
  87936. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  87937. var trianglesIterator = function (i) {
  87938. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  87939. var t = _this.triangles[tIdx];
  87940. if (!t)
  87941. return;
  87942. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  87943. return;
  87944. }
  87945. for (var j = 0; j < 3; ++j) {
  87946. if (t.error[j] < threshold) {
  87947. var deleted0 = [];
  87948. var deleted1 = [];
  87949. var v0 = t.vertices[j];
  87950. var v1 = t.vertices[(j + 1) % 3];
  87951. if (v0.isBorder || v1.isBorder)
  87952. continue;
  87953. var p = BABYLON.Vector3.Zero();
  87954. var n = BABYLON.Vector3.Zero();
  87955. var uv = BABYLON.Vector2.Zero();
  87956. var color = new BABYLON.Color4(0, 0, 0, 1);
  87957. _this.calculateError(v0, v1, p, n, uv, color);
  87958. var delTr = new Array();
  87959. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  87960. continue;
  87961. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  87962. continue;
  87963. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  87964. continue;
  87965. var uniqueArray = new Array();
  87966. delTr.forEach(function (deletedT) {
  87967. if (uniqueArray.indexOf(deletedT) === -1) {
  87968. deletedT.deletePending = true;
  87969. uniqueArray.push(deletedT);
  87970. }
  87971. });
  87972. if (uniqueArray.length % 2 !== 0) {
  87973. continue;
  87974. }
  87975. v0.q = v1.q.add(v0.q);
  87976. v0.updatePosition(p);
  87977. var tStart = _this.references.length;
  87978. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  87979. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  87980. var tCount = _this.references.length - tStart;
  87981. if (tCount <= v0.triangleCount) {
  87982. if (tCount) {
  87983. for (var c = 0; c < tCount; c++) {
  87984. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  87985. }
  87986. }
  87987. }
  87988. else {
  87989. v0.triangleStart = tStart;
  87990. }
  87991. v0.triangleCount = tCount;
  87992. break;
  87993. }
  87994. }
  87995. };
  87996. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  87997. }, 0);
  87998. };
  87999. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  88000. if (triangleCount - deletedTriangles <= targetCount)
  88001. loop.breakLoop();
  88002. else {
  88003. iterationFunction(loop.index, function () {
  88004. loop.executeNext();
  88005. });
  88006. }
  88007. }, function () {
  88008. setTimeout(function () {
  88009. //reconstruct this part of the mesh
  88010. _this.reconstructMesh(submeshIndex);
  88011. successCallback();
  88012. }, 0);
  88013. });
  88014. };
  88015. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  88016. var _this = this;
  88017. this.vertices = [];
  88018. this.triangles = [];
  88019. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  88020. var indices = this._mesh.getIndices();
  88021. var submesh = this._mesh.subMeshes[submeshIndex];
  88022. var findInVertices = function (positionToSearch) {
  88023. if (optimizeMesh) {
  88024. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  88025. if (_this.vertices[ii].position.equals(positionToSearch)) {
  88026. return _this.vertices[ii];
  88027. }
  88028. }
  88029. }
  88030. return null;
  88031. };
  88032. var vertexReferences = [];
  88033. var vertexInit = function (i) {
  88034. if (!positionData) {
  88035. return;
  88036. }
  88037. var offset = i + submesh.verticesStart;
  88038. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  88039. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  88040. vertex.originalOffsets.push(offset);
  88041. if (vertex.id === _this.vertices.length) {
  88042. _this.vertices.push(vertex);
  88043. }
  88044. vertexReferences.push(vertex.id);
  88045. };
  88046. //var totalVertices = mesh.getTotalVertices();
  88047. var totalVertices = submesh.verticesCount;
  88048. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  88049. var indicesInit = function (i) {
  88050. if (!indices) {
  88051. return;
  88052. }
  88053. var offset = (submesh.indexStart / 3) + i;
  88054. var pos = (offset * 3);
  88055. var i0 = indices[pos + 0];
  88056. var i1 = indices[pos + 1];
  88057. var i2 = indices[pos + 2];
  88058. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  88059. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  88060. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  88061. var triangle = new DecimationTriangle([v0, v1, v2]);
  88062. triangle.originalOffset = pos;
  88063. _this.triangles.push(triangle);
  88064. };
  88065. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  88066. _this.init(callback);
  88067. });
  88068. });
  88069. };
  88070. QuadraticErrorSimplification.prototype.init = function (callback) {
  88071. var _this = this;
  88072. var triangleInit1 = function (i) {
  88073. var t = _this.triangles[i];
  88074. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  88075. for (var j = 0; j < 3; j++) {
  88076. 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))));
  88077. }
  88078. };
  88079. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  88080. var triangleInit2 = function (i) {
  88081. var t = _this.triangles[i];
  88082. for (var j = 0; j < 3; ++j) {
  88083. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  88084. }
  88085. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  88086. };
  88087. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  88088. callback();
  88089. });
  88090. });
  88091. };
  88092. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  88093. var newTriangles = [];
  88094. var i;
  88095. for (i = 0; i < this.vertices.length; ++i) {
  88096. this.vertices[i].triangleCount = 0;
  88097. }
  88098. var t;
  88099. var j;
  88100. for (i = 0; i < this.triangles.length; ++i) {
  88101. if (!this.triangles[i].deleted) {
  88102. t = this.triangles[i];
  88103. for (j = 0; j < 3; ++j) {
  88104. t.vertices[j].triangleCount = 1;
  88105. }
  88106. newTriangles.push(t);
  88107. }
  88108. }
  88109. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  88110. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  88111. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  88112. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  88113. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  88114. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  88115. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  88116. var vertexCount = 0;
  88117. for (i = 0; i < this.vertices.length; ++i) {
  88118. var vertex = this.vertices[i];
  88119. vertex.id = vertexCount;
  88120. if (vertex.triangleCount) {
  88121. vertex.originalOffsets.forEach(function (originalOffset) {
  88122. if (!normalData) {
  88123. return;
  88124. }
  88125. newPositionData.push(vertex.position.x);
  88126. newPositionData.push(vertex.position.y);
  88127. newPositionData.push(vertex.position.z);
  88128. newNormalData.push(normalData[originalOffset * 3]);
  88129. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  88130. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  88131. if (uvs && uvs.length) {
  88132. newUVsData.push(uvs[(originalOffset * 2)]);
  88133. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  88134. }
  88135. else if (colorsData && colorsData.length) {
  88136. newColorsData.push(colorsData[(originalOffset * 4)]);
  88137. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  88138. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  88139. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  88140. }
  88141. ++vertexCount;
  88142. });
  88143. }
  88144. }
  88145. var startingIndex = this._reconstructedMesh.getTotalIndices();
  88146. var startingVertex = this._reconstructedMesh.getTotalVertices();
  88147. var submeshesArray = this._reconstructedMesh.subMeshes;
  88148. this._reconstructedMesh.subMeshes = [];
  88149. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  88150. var originalIndices = this._mesh.getIndices();
  88151. for (i = 0; i < newTriangles.length; ++i) {
  88152. t = newTriangles[i]; //now get the new referencing point for each vertex
  88153. [0, 1, 2].forEach(function (idx) {
  88154. var id = originalIndices[t.originalOffset + idx];
  88155. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  88156. if (offset < 0)
  88157. offset = 0;
  88158. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  88159. });
  88160. }
  88161. //overwriting the old vertex buffers and indices.
  88162. this._reconstructedMesh.setIndices(newIndicesArray);
  88163. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  88164. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  88165. if (newUVsData.length > 0)
  88166. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  88167. if (newColorsData.length > 0)
  88168. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  88169. //create submesh
  88170. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  88171. if (submeshIndex > 0) {
  88172. this._reconstructedMesh.subMeshes = [];
  88173. submeshesArray.forEach(function (submesh) {
  88174. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  88175. });
  88176. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  88177. }
  88178. };
  88179. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  88180. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  88181. this._reconstructedMesh.material = this._mesh.material;
  88182. this._reconstructedMesh.parent = this._mesh.parent;
  88183. this._reconstructedMesh.isVisible = false;
  88184. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  88185. };
  88186. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  88187. for (var i = 0; i < vertex1.triangleCount; ++i) {
  88188. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  88189. if (t.deleted)
  88190. continue;
  88191. var s = this.references[vertex1.triangleStart + i].vertexId;
  88192. var v1 = t.vertices[(s + 1) % 3];
  88193. var v2 = t.vertices[(s + 2) % 3];
  88194. if ((v1 === vertex2 || v2 === vertex2)) {
  88195. deletedArray[i] = true;
  88196. delTr.push(t);
  88197. continue;
  88198. }
  88199. var d1 = v1.position.subtract(point);
  88200. d1 = d1.normalize();
  88201. var d2 = v2.position.subtract(point);
  88202. d2 = d2.normalize();
  88203. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  88204. return true;
  88205. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  88206. deletedArray[i] = false;
  88207. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  88208. return true;
  88209. }
  88210. return false;
  88211. };
  88212. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  88213. var newDeleted = deletedTriangles;
  88214. for (var i = 0; i < vertex.triangleCount; ++i) {
  88215. var ref = this.references[vertex.triangleStart + i];
  88216. var t = this.triangles[ref.triangleId];
  88217. if (t.deleted)
  88218. continue;
  88219. if (deletedArray[i] && t.deletePending) {
  88220. t.deleted = true;
  88221. newDeleted++;
  88222. continue;
  88223. }
  88224. t.vertices[ref.vertexId] = origVertex;
  88225. t.isDirty = true;
  88226. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  88227. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  88228. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  88229. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  88230. this.references.push(ref);
  88231. }
  88232. return newDeleted;
  88233. };
  88234. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  88235. for (var i = 0; i < this.vertices.length; ++i) {
  88236. var vCount = [];
  88237. var vId = [];
  88238. var v = this.vertices[i];
  88239. var j;
  88240. for (j = 0; j < v.triangleCount; ++j) {
  88241. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  88242. for (var ii = 0; ii < 3; ii++) {
  88243. var ofs = 0;
  88244. var vv = triangle.vertices[ii];
  88245. while (ofs < vCount.length) {
  88246. if (vId[ofs] === vv.id)
  88247. break;
  88248. ++ofs;
  88249. }
  88250. if (ofs === vCount.length) {
  88251. vCount.push(1);
  88252. vId.push(vv.id);
  88253. }
  88254. else {
  88255. vCount[ofs]++;
  88256. }
  88257. }
  88258. }
  88259. for (j = 0; j < vCount.length; ++j) {
  88260. if (vCount[j] === 1) {
  88261. this.vertices[vId[j]].isBorder = true;
  88262. }
  88263. else {
  88264. this.vertices[vId[j]].isBorder = false;
  88265. }
  88266. }
  88267. }
  88268. };
  88269. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  88270. if (identifyBorders === void 0) { identifyBorders = false; }
  88271. var i;
  88272. if (!identifyBorders) {
  88273. var newTrianglesVector = [];
  88274. for (i = 0; i < this.triangles.length; ++i) {
  88275. if (!this.triangles[i].deleted) {
  88276. newTrianglesVector.push(this.triangles[i]);
  88277. }
  88278. }
  88279. this.triangles = newTrianglesVector;
  88280. }
  88281. for (i = 0; i < this.vertices.length; ++i) {
  88282. this.vertices[i].triangleCount = 0;
  88283. this.vertices[i].triangleStart = 0;
  88284. }
  88285. var t;
  88286. var j;
  88287. var v;
  88288. for (i = 0; i < this.triangles.length; ++i) {
  88289. t = this.triangles[i];
  88290. for (j = 0; j < 3; ++j) {
  88291. v = t.vertices[j];
  88292. v.triangleCount++;
  88293. }
  88294. }
  88295. var tStart = 0;
  88296. for (i = 0; i < this.vertices.length; ++i) {
  88297. this.vertices[i].triangleStart = tStart;
  88298. tStart += this.vertices[i].triangleCount;
  88299. this.vertices[i].triangleCount = 0;
  88300. }
  88301. var newReferences = new Array(this.triangles.length * 3);
  88302. for (i = 0; i < this.triangles.length; ++i) {
  88303. t = this.triangles[i];
  88304. for (j = 0; j < 3; ++j) {
  88305. v = t.vertices[j];
  88306. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  88307. v.triangleCount++;
  88308. }
  88309. }
  88310. this.references = newReferences;
  88311. if (identifyBorders) {
  88312. this.identifyBorder();
  88313. }
  88314. };
  88315. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  88316. var x = point.x;
  88317. var y = point.y;
  88318. var z = point.z;
  88319. 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
  88320. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  88321. };
  88322. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  88323. var q = vertex1.q.add(vertex2.q);
  88324. var border = vertex1.isBorder && vertex2.isBorder;
  88325. var error = 0;
  88326. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  88327. if (qDet !== 0 && !border) {
  88328. if (!pointResult) {
  88329. pointResult = BABYLON.Vector3.Zero();
  88330. }
  88331. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  88332. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  88333. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  88334. error = this.vertexError(q, pointResult);
  88335. }
  88336. else {
  88337. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  88338. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  88339. var error1 = this.vertexError(q, vertex1.position);
  88340. var error2 = this.vertexError(q, vertex2.position);
  88341. var error3 = this.vertexError(q, p3);
  88342. error = Math.min(error1, error2, error3);
  88343. if (error === error1) {
  88344. if (pointResult) {
  88345. pointResult.copyFrom(vertex1.position);
  88346. }
  88347. }
  88348. else if (error === error2) {
  88349. if (pointResult) {
  88350. pointResult.copyFrom(vertex2.position);
  88351. }
  88352. }
  88353. else {
  88354. if (pointResult) {
  88355. pointResult.copyFrom(p3);
  88356. }
  88357. }
  88358. }
  88359. return error;
  88360. };
  88361. return QuadraticErrorSimplification;
  88362. }());
  88363. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  88364. })(BABYLON || (BABYLON = {}));
  88365. //# sourceMappingURL=babylon.meshSimplification.js.map
  88366. "use strict";
  88367. var BABYLON;
  88368. (function (BABYLON) {
  88369. var MeshLODLevel = /** @class */ (function () {
  88370. function MeshLODLevel(distance, mesh) {
  88371. this.distance = distance;
  88372. this.mesh = mesh;
  88373. }
  88374. return MeshLODLevel;
  88375. }());
  88376. BABYLON.MeshLODLevel = MeshLODLevel;
  88377. })(BABYLON || (BABYLON = {}));
  88378. //# sourceMappingURL=babylon.meshLODLevel.js.map
  88379. "use strict";
  88380. var BABYLON;
  88381. (function (BABYLON) {
  88382. /**
  88383. * Defines the root class used to create scene optimization to use with SceneOptimizer
  88384. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88385. */
  88386. var SceneOptimization = /** @class */ (function () {
  88387. /**
  88388. * Creates the SceneOptimization object
  88389. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  88390. * @param desc defines the description associated with the optimization
  88391. */
  88392. function SceneOptimization(
  88393. /**
  88394. * Defines the priority of this optimization (0 by default which means first in the list)
  88395. */
  88396. priority) {
  88397. if (priority === void 0) { priority = 0; }
  88398. this.priority = priority;
  88399. }
  88400. /**
  88401. * Gets a string describing the action executed by the current optimization
  88402. * @returns description string
  88403. */
  88404. SceneOptimization.prototype.getDescription = function () {
  88405. return "";
  88406. };
  88407. /**
  88408. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88409. * @param scene defines the current scene where to apply this optimization
  88410. * @param optimizer defines the current optimizer
  88411. * @returns true if everything that can be done was applied
  88412. */
  88413. SceneOptimization.prototype.apply = function (scene, optimizer) {
  88414. return true;
  88415. };
  88416. ;
  88417. return SceneOptimization;
  88418. }());
  88419. BABYLON.SceneOptimization = SceneOptimization;
  88420. /**
  88421. * Defines an optimization used to reduce the size of render target textures
  88422. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88423. */
  88424. var TextureOptimization = /** @class */ (function (_super) {
  88425. __extends(TextureOptimization, _super);
  88426. /**
  88427. * Creates the TextureOptimization object
  88428. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  88429. * @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
  88430. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  88431. */
  88432. function TextureOptimization(
  88433. /**
  88434. * Defines the priority of this optimization (0 by default which means first in the list)
  88435. */
  88436. priority,
  88437. /**
  88438. * 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
  88439. */
  88440. maximumSize,
  88441. /**
  88442. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  88443. */
  88444. step) {
  88445. if (priority === void 0) { priority = 0; }
  88446. if (maximumSize === void 0) { maximumSize = 1024; }
  88447. if (step === void 0) { step = 0.5; }
  88448. var _this = _super.call(this, priority) || this;
  88449. _this.priority = priority;
  88450. _this.maximumSize = maximumSize;
  88451. _this.step = step;
  88452. return _this;
  88453. }
  88454. /**
  88455. * Gets a string describing the action executed by the current optimization
  88456. * @returns description string
  88457. */
  88458. TextureOptimization.prototype.getDescription = function () {
  88459. return "Reducing render target texture size to " + this.maximumSize;
  88460. };
  88461. /**
  88462. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88463. * @param scene defines the current scene where to apply this optimization
  88464. * @param optimizer defines the current optimizer
  88465. * @returns true if everything that can be done was applied
  88466. */
  88467. TextureOptimization.prototype.apply = function (scene, optimizer) {
  88468. var allDone = true;
  88469. for (var index = 0; index < scene.textures.length; index++) {
  88470. var texture = scene.textures[index];
  88471. if (!texture.canRescale || texture.getContext) {
  88472. continue;
  88473. }
  88474. var currentSize = texture.getSize();
  88475. var maxDimension = Math.max(currentSize.width, currentSize.height);
  88476. if (maxDimension > this.maximumSize) {
  88477. texture.scale(this.step);
  88478. allDone = false;
  88479. }
  88480. }
  88481. return allDone;
  88482. };
  88483. return TextureOptimization;
  88484. }(SceneOptimization));
  88485. BABYLON.TextureOptimization = TextureOptimization;
  88486. /**
  88487. * Defines an optimization used to increase or decrease the rendering resolution
  88488. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88489. */
  88490. var HardwareScalingOptimization = /** @class */ (function (_super) {
  88491. __extends(HardwareScalingOptimization, _super);
  88492. /**
  88493. * Creates the HardwareScalingOptimization object
  88494. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  88495. * @param maximumScale defines the maximum scale to use (2 by default)
  88496. * @param step defines the step to use between two passes (0.5 by default)
  88497. */
  88498. function HardwareScalingOptimization(
  88499. /**
  88500. * Defines the priority of this optimization (0 by default which means first in the list)
  88501. */
  88502. priority,
  88503. /**
  88504. * Defines the maximum scale to use (2 by default)
  88505. */
  88506. maximumScale,
  88507. /**
  88508. * Defines the step to use between two passes (0.5 by default)
  88509. */
  88510. step) {
  88511. if (priority === void 0) { priority = 0; }
  88512. if (maximumScale === void 0) { maximumScale = 2; }
  88513. if (step === void 0) { step = 0.25; }
  88514. var _this = _super.call(this, priority) || this;
  88515. _this.priority = priority;
  88516. _this.maximumScale = maximumScale;
  88517. _this.step = step;
  88518. _this._currentScale = -1;
  88519. _this._directionOffset = 1;
  88520. return _this;
  88521. }
  88522. /**
  88523. * Gets a string describing the action executed by the current optimization
  88524. * @return description string
  88525. */
  88526. HardwareScalingOptimization.prototype.getDescription = function () {
  88527. return "Setting hardware scaling level to " + this._currentScale;
  88528. };
  88529. /**
  88530. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88531. * @param scene defines the current scene where to apply this optimization
  88532. * @param optimizer defines the current optimizer
  88533. * @returns true if everything that can be done was applied
  88534. */
  88535. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  88536. if (this._currentScale === -1) {
  88537. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  88538. if (this._currentScale > this.maximumScale) {
  88539. this._directionOffset = -1;
  88540. }
  88541. }
  88542. this._currentScale += this._directionOffset * this.step;
  88543. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  88544. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  88545. };
  88546. ;
  88547. return HardwareScalingOptimization;
  88548. }(SceneOptimization));
  88549. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  88550. /**
  88551. * Defines an optimization used to remove shadows
  88552. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88553. */
  88554. var ShadowsOptimization = /** @class */ (function (_super) {
  88555. __extends(ShadowsOptimization, _super);
  88556. function ShadowsOptimization() {
  88557. return _super !== null && _super.apply(this, arguments) || this;
  88558. }
  88559. /**
  88560. * Gets a string describing the action executed by the current optimization
  88561. * @return description string
  88562. */
  88563. ShadowsOptimization.prototype.getDescription = function () {
  88564. return "Turning shadows on/off";
  88565. };
  88566. /**
  88567. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88568. * @param scene defines the current scene where to apply this optimization
  88569. * @param optimizer defines the current optimizer
  88570. * @returns true if everything that can be done was applied
  88571. */
  88572. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  88573. scene.shadowsEnabled = optimizer.isInImprovementMode;
  88574. return true;
  88575. };
  88576. ;
  88577. return ShadowsOptimization;
  88578. }(SceneOptimization));
  88579. BABYLON.ShadowsOptimization = ShadowsOptimization;
  88580. /**
  88581. * Defines an optimization used to turn post-processes off
  88582. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88583. */
  88584. var PostProcessesOptimization = /** @class */ (function (_super) {
  88585. __extends(PostProcessesOptimization, _super);
  88586. function PostProcessesOptimization() {
  88587. return _super !== null && _super.apply(this, arguments) || this;
  88588. }
  88589. /**
  88590. * Gets a string describing the action executed by the current optimization
  88591. * @return description string
  88592. */
  88593. PostProcessesOptimization.prototype.getDescription = function () {
  88594. return "Turning post-processes on/off";
  88595. };
  88596. /**
  88597. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88598. * @param scene defines the current scene where to apply this optimization
  88599. * @param optimizer defines the current optimizer
  88600. * @returns true if everything that can be done was applied
  88601. */
  88602. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  88603. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  88604. return true;
  88605. };
  88606. ;
  88607. return PostProcessesOptimization;
  88608. }(SceneOptimization));
  88609. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  88610. /**
  88611. * Defines an optimization used to turn lens flares off
  88612. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88613. */
  88614. var LensFlaresOptimization = /** @class */ (function (_super) {
  88615. __extends(LensFlaresOptimization, _super);
  88616. function LensFlaresOptimization() {
  88617. return _super !== null && _super.apply(this, arguments) || this;
  88618. }
  88619. /**
  88620. * Gets a string describing the action executed by the current optimization
  88621. * @return description string
  88622. */
  88623. LensFlaresOptimization.prototype.getDescription = function () {
  88624. return "Turning lens flares on/off";
  88625. };
  88626. /**
  88627. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88628. * @param scene defines the current scene where to apply this optimization
  88629. * @param optimizer defines the current optimizer
  88630. * @returns true if everything that can be done was applied
  88631. */
  88632. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  88633. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  88634. return true;
  88635. };
  88636. ;
  88637. return LensFlaresOptimization;
  88638. }(SceneOptimization));
  88639. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  88640. /**
  88641. * Defines an optimization based on user defined callback.
  88642. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88643. */
  88644. var CustomOptimization = /** @class */ (function (_super) {
  88645. __extends(CustomOptimization, _super);
  88646. function CustomOptimization() {
  88647. return _super !== null && _super.apply(this, arguments) || this;
  88648. }
  88649. /**
  88650. * Gets a string describing the action executed by the current optimization
  88651. * @returns description string
  88652. */
  88653. CustomOptimization.prototype.getDescription = function () {
  88654. if (this.onGetDescription) {
  88655. return this.onGetDescription();
  88656. }
  88657. return "Running user defined callback";
  88658. };
  88659. /**
  88660. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88661. * @param scene defines the current scene where to apply this optimization
  88662. * @param optimizer defines the current optimizer
  88663. * @returns true if everything that can be done was applied
  88664. */
  88665. CustomOptimization.prototype.apply = function (scene, optimizer) {
  88666. if (this.onApply) {
  88667. return this.onApply(scene, optimizer);
  88668. }
  88669. return true;
  88670. };
  88671. ;
  88672. return CustomOptimization;
  88673. }(SceneOptimization));
  88674. BABYLON.CustomOptimization = CustomOptimization;
  88675. /**
  88676. * Defines an optimization used to turn particles off
  88677. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88678. */
  88679. var ParticlesOptimization = /** @class */ (function (_super) {
  88680. __extends(ParticlesOptimization, _super);
  88681. function ParticlesOptimization() {
  88682. return _super !== null && _super.apply(this, arguments) || this;
  88683. }
  88684. /**
  88685. * Gets a string describing the action executed by the current optimization
  88686. * @return description string
  88687. */
  88688. ParticlesOptimization.prototype.getDescription = function () {
  88689. return "Turning particles on/off";
  88690. };
  88691. /**
  88692. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88693. * @param scene defines the current scene where to apply this optimization
  88694. * @param optimizer defines the current optimizer
  88695. * @returns true if everything that can be done was applied
  88696. */
  88697. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  88698. scene.particlesEnabled = optimizer.isInImprovementMode;
  88699. return true;
  88700. };
  88701. ;
  88702. return ParticlesOptimization;
  88703. }(SceneOptimization));
  88704. BABYLON.ParticlesOptimization = ParticlesOptimization;
  88705. /**
  88706. * Defines an optimization used to turn render targets off
  88707. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88708. */
  88709. var RenderTargetsOptimization = /** @class */ (function (_super) {
  88710. __extends(RenderTargetsOptimization, _super);
  88711. function RenderTargetsOptimization() {
  88712. return _super !== null && _super.apply(this, arguments) || this;
  88713. }
  88714. /**
  88715. * Gets a string describing the action executed by the current optimization
  88716. * @return description string
  88717. */
  88718. RenderTargetsOptimization.prototype.getDescription = function () {
  88719. return "Turning render targets off";
  88720. };
  88721. /**
  88722. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88723. * @param scene defines the current scene where to apply this optimization
  88724. * @param optimizer defines the current optimizer
  88725. * @returns true if everything that can be done was applied
  88726. */
  88727. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  88728. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  88729. return true;
  88730. };
  88731. ;
  88732. return RenderTargetsOptimization;
  88733. }(SceneOptimization));
  88734. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  88735. /**
  88736. * Defines an optimization used to merge meshes with compatible materials
  88737. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88738. */
  88739. var MergeMeshesOptimization = /** @class */ (function (_super) {
  88740. __extends(MergeMeshesOptimization, _super);
  88741. function MergeMeshesOptimization() {
  88742. var _this = _super !== null && _super.apply(this, arguments) || this;
  88743. _this._canBeMerged = function (abstractMesh) {
  88744. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  88745. return false;
  88746. }
  88747. var mesh = abstractMesh;
  88748. if (!mesh.isVisible || !mesh.isEnabled()) {
  88749. return false;
  88750. }
  88751. if (mesh.instances.length > 0) {
  88752. return false;
  88753. }
  88754. if (mesh.skeleton || mesh.hasLODLevels) {
  88755. return false;
  88756. }
  88757. if (mesh.parent) {
  88758. return false;
  88759. }
  88760. return true;
  88761. };
  88762. return _this;
  88763. }
  88764. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  88765. /**
  88766. * Gets or sets a boolean which defines if optimization octree has to be updated
  88767. */
  88768. get: function () {
  88769. return MergeMeshesOptimization._UpdateSelectionTree;
  88770. },
  88771. /**
  88772. * Gets or sets a boolean which defines if optimization octree has to be updated
  88773. */
  88774. set: function (value) {
  88775. MergeMeshesOptimization._UpdateSelectionTree = value;
  88776. },
  88777. enumerable: true,
  88778. configurable: true
  88779. });
  88780. /**
  88781. * Gets a string describing the action executed by the current optimization
  88782. * @return description string
  88783. */
  88784. MergeMeshesOptimization.prototype.getDescription = function () {
  88785. return "Merging similar meshes together";
  88786. };
  88787. /**
  88788. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88789. * @param scene defines the current scene where to apply this optimization
  88790. * @param optimizer defines the current optimizer
  88791. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  88792. * @returns true if everything that can be done was applied
  88793. */
  88794. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  88795. var globalPool = scene.meshes.slice(0);
  88796. var globalLength = globalPool.length;
  88797. for (var index = 0; index < globalLength; index++) {
  88798. var currentPool = new Array();
  88799. var current = globalPool[index];
  88800. // Checks
  88801. if (!this._canBeMerged(current)) {
  88802. continue;
  88803. }
  88804. currentPool.push(current);
  88805. // Find compatible meshes
  88806. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  88807. var otherMesh = globalPool[subIndex];
  88808. if (!this._canBeMerged(otherMesh)) {
  88809. continue;
  88810. }
  88811. if (otherMesh.material !== current.material) {
  88812. continue;
  88813. }
  88814. if (otherMesh.checkCollisions !== current.checkCollisions) {
  88815. continue;
  88816. }
  88817. currentPool.push(otherMesh);
  88818. globalLength--;
  88819. globalPool.splice(subIndex, 1);
  88820. subIndex--;
  88821. }
  88822. if (currentPool.length < 2) {
  88823. continue;
  88824. }
  88825. // Merge meshes
  88826. BABYLON.Mesh.MergeMeshes(currentPool);
  88827. }
  88828. if (updateSelectionTree != undefined) {
  88829. if (updateSelectionTree) {
  88830. scene.createOrUpdateSelectionOctree();
  88831. }
  88832. }
  88833. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  88834. scene.createOrUpdateSelectionOctree();
  88835. }
  88836. return true;
  88837. };
  88838. ;
  88839. MergeMeshesOptimization._UpdateSelectionTree = false;
  88840. return MergeMeshesOptimization;
  88841. }(SceneOptimization));
  88842. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  88843. /**
  88844. * Defines a list of options used by SceneOptimizer
  88845. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88846. */
  88847. var SceneOptimizerOptions = /** @class */ (function () {
  88848. /**
  88849. * Creates a new list of options used by SceneOptimizer
  88850. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  88851. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  88852. */
  88853. function SceneOptimizerOptions(
  88854. /**
  88855. * Defines the target frame rate to reach (60 by default)
  88856. */
  88857. targetFrameRate,
  88858. /**
  88859. * Defines the interval between two checkes (2000ms by default)
  88860. */
  88861. trackerDuration) {
  88862. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  88863. if (trackerDuration === void 0) { trackerDuration = 2000; }
  88864. this.targetFrameRate = targetFrameRate;
  88865. this.trackerDuration = trackerDuration;
  88866. /**
  88867. * Gets the list of optimizations to apply
  88868. */
  88869. this.optimizations = new Array();
  88870. }
  88871. /**
  88872. * Add a new optimization
  88873. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  88874. * @returns the current SceneOptimizerOptions
  88875. */
  88876. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  88877. this.optimizations.push(optimization);
  88878. return this;
  88879. };
  88880. /**
  88881. * Add a new custom optimization
  88882. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  88883. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  88884. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  88885. * @returns the current SceneOptimizerOptions
  88886. */
  88887. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  88888. if (priority === void 0) { priority = 0; }
  88889. var optimization = new CustomOptimization(priority);
  88890. optimization.onApply = onApply;
  88891. optimization.onGetDescription = onGetDescription;
  88892. this.optimizations.push(optimization);
  88893. return this;
  88894. };
  88895. /**
  88896. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  88897. * @param targetFrameRate defines the target frame rate (60 by default)
  88898. * @returns a SceneOptimizerOptions object
  88899. */
  88900. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  88901. var result = new SceneOptimizerOptions(targetFrameRate);
  88902. var priority = 0;
  88903. result.addOptimization(new MergeMeshesOptimization(priority));
  88904. result.addOptimization(new ShadowsOptimization(priority));
  88905. result.addOptimization(new LensFlaresOptimization(priority));
  88906. // Next priority
  88907. priority++;
  88908. result.addOptimization(new PostProcessesOptimization(priority));
  88909. result.addOptimization(new ParticlesOptimization(priority));
  88910. // Next priority
  88911. priority++;
  88912. result.addOptimization(new TextureOptimization(priority, 1024));
  88913. return result;
  88914. };
  88915. /**
  88916. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  88917. * @param targetFrameRate defines the target frame rate (60 by default)
  88918. * @returns a SceneOptimizerOptions object
  88919. */
  88920. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  88921. var result = new SceneOptimizerOptions(targetFrameRate);
  88922. var priority = 0;
  88923. result.addOptimization(new MergeMeshesOptimization(priority));
  88924. result.addOptimization(new ShadowsOptimization(priority));
  88925. result.addOptimization(new LensFlaresOptimization(priority));
  88926. // Next priority
  88927. priority++;
  88928. result.addOptimization(new PostProcessesOptimization(priority));
  88929. result.addOptimization(new ParticlesOptimization(priority));
  88930. // Next priority
  88931. priority++;
  88932. result.addOptimization(new TextureOptimization(priority, 512));
  88933. // Next priority
  88934. priority++;
  88935. result.addOptimization(new RenderTargetsOptimization(priority));
  88936. // Next priority
  88937. priority++;
  88938. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  88939. return result;
  88940. };
  88941. /**
  88942. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  88943. * @param targetFrameRate defines the target frame rate (60 by default)
  88944. * @returns a SceneOptimizerOptions object
  88945. */
  88946. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  88947. var result = new SceneOptimizerOptions(targetFrameRate);
  88948. var priority = 0;
  88949. result.addOptimization(new MergeMeshesOptimization(priority));
  88950. result.addOptimization(new ShadowsOptimization(priority));
  88951. result.addOptimization(new LensFlaresOptimization(priority));
  88952. // Next priority
  88953. priority++;
  88954. result.addOptimization(new PostProcessesOptimization(priority));
  88955. result.addOptimization(new ParticlesOptimization(priority));
  88956. // Next priority
  88957. priority++;
  88958. result.addOptimization(new TextureOptimization(priority, 256));
  88959. // Next priority
  88960. priority++;
  88961. result.addOptimization(new RenderTargetsOptimization(priority));
  88962. // Next priority
  88963. priority++;
  88964. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  88965. return result;
  88966. };
  88967. return SceneOptimizerOptions;
  88968. }());
  88969. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  88970. /**
  88971. * Class used to run optimizations in order to reach a target frame rate
  88972. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88973. */
  88974. var SceneOptimizer = /** @class */ (function () {
  88975. /**
  88976. * Creates a new SceneOptimizer
  88977. * @param scene defines the scene to work on
  88978. * @param options defines the options to use with the SceneOptimizer
  88979. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  88980. * @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)
  88981. */
  88982. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  88983. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  88984. if (improvementMode === void 0) { improvementMode = false; }
  88985. var _this = this;
  88986. this._isRunning = false;
  88987. this._currentPriorityLevel = 0;
  88988. this._targetFrameRate = 60;
  88989. this._trackerDuration = 2000;
  88990. this._currentFrameRate = 0;
  88991. this._improvementMode = false;
  88992. /**
  88993. * Defines an observable called when the optimizer reaches the target frame rate
  88994. */
  88995. this.onSuccessObservable = new BABYLON.Observable();
  88996. /**
  88997. * Defines an observable called when the optimizer enables an optimization
  88998. */
  88999. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  89000. /**
  89001. * Defines an observable called when the optimizer is not able to reach the target frame rate
  89002. */
  89003. this.onFailureObservable = new BABYLON.Observable();
  89004. if (!options) {
  89005. this._options = new SceneOptimizerOptions();
  89006. }
  89007. else {
  89008. this._options = options;
  89009. }
  89010. if (this._options.targetFrameRate) {
  89011. this._targetFrameRate = this._options.targetFrameRate;
  89012. }
  89013. if (this._options.trackerDuration) {
  89014. this._trackerDuration = this._options.trackerDuration;
  89015. }
  89016. if (autoGeneratePriorities) {
  89017. var priority = 0;
  89018. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  89019. var optim = _a[_i];
  89020. optim.priority = priority++;
  89021. }
  89022. }
  89023. this._improvementMode = improvementMode;
  89024. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89025. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  89026. _this._sceneDisposeObserver = null;
  89027. _this.dispose();
  89028. });
  89029. }
  89030. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  89031. /**
  89032. * Gets a boolean indicating if the optimizer is in improvement mode
  89033. */
  89034. get: function () {
  89035. return this._improvementMode;
  89036. },
  89037. enumerable: true,
  89038. configurable: true
  89039. });
  89040. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  89041. /**
  89042. * Gets the current priority level (0 at start)
  89043. */
  89044. get: function () {
  89045. return this._currentPriorityLevel;
  89046. },
  89047. enumerable: true,
  89048. configurable: true
  89049. });
  89050. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  89051. /**
  89052. * Gets the current frame rate checked by the SceneOptimizer
  89053. */
  89054. get: function () {
  89055. return this._currentFrameRate;
  89056. },
  89057. enumerable: true,
  89058. configurable: true
  89059. });
  89060. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  89061. /**
  89062. * Gets or sets the current target frame rate (60 by default)
  89063. */
  89064. get: function () {
  89065. return this._targetFrameRate;
  89066. },
  89067. /**
  89068. * Gets or sets the current target frame rate (60 by default)
  89069. */
  89070. set: function (value) {
  89071. this._targetFrameRate = value;
  89072. },
  89073. enumerable: true,
  89074. configurable: true
  89075. });
  89076. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  89077. /**
  89078. * Gets or sets the current interval between two checks (every 2000ms by default)
  89079. */
  89080. get: function () {
  89081. return this._trackerDuration;
  89082. },
  89083. /**
  89084. * Gets or sets the current interval between two checks (every 2000ms by default)
  89085. */
  89086. set: function (value) {
  89087. this._trackerDuration = value;
  89088. },
  89089. enumerable: true,
  89090. configurable: true
  89091. });
  89092. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  89093. /**
  89094. * Gets the list of active optimizations
  89095. */
  89096. get: function () {
  89097. return this._options.optimizations;
  89098. },
  89099. enumerable: true,
  89100. configurable: true
  89101. });
  89102. /**
  89103. * Stops the current optimizer
  89104. */
  89105. SceneOptimizer.prototype.stop = function () {
  89106. this._isRunning = false;
  89107. };
  89108. /**
  89109. * Reset the optimizer to initial step (current priority level = 0)
  89110. */
  89111. SceneOptimizer.prototype.reset = function () {
  89112. this._currentPriorityLevel = 0;
  89113. };
  89114. /**
  89115. * Start the optimizer. By default it will try to reach a specific framerate
  89116. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  89117. */
  89118. SceneOptimizer.prototype.start = function () {
  89119. var _this = this;
  89120. if (this._isRunning) {
  89121. return;
  89122. }
  89123. this._isRunning = true;
  89124. // Let's wait for the scene to be ready before running our check
  89125. this._scene.executeWhenReady(function () {
  89126. setTimeout(function () {
  89127. _this._checkCurrentState();
  89128. }, _this._trackerDuration);
  89129. });
  89130. };
  89131. SceneOptimizer.prototype._checkCurrentState = function () {
  89132. var _this = this;
  89133. if (!this._isRunning) {
  89134. return;
  89135. }
  89136. var scene = this._scene;
  89137. var options = this._options;
  89138. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  89139. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  89140. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  89141. this._isRunning = false;
  89142. this.onSuccessObservable.notifyObservers(this);
  89143. return;
  89144. }
  89145. // Apply current level of optimizations
  89146. var allDone = true;
  89147. var noOptimizationApplied = true;
  89148. for (var index = 0; index < options.optimizations.length; index++) {
  89149. var optimization = options.optimizations[index];
  89150. if (optimization.priority === this._currentPriorityLevel) {
  89151. noOptimizationApplied = false;
  89152. allDone = allDone && optimization.apply(scene, this);
  89153. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  89154. }
  89155. }
  89156. // If no optimization was applied, this is a failure :(
  89157. if (noOptimizationApplied) {
  89158. this._isRunning = false;
  89159. this.onFailureObservable.notifyObservers(this);
  89160. return;
  89161. }
  89162. // If all optimizations were done, move to next level
  89163. if (allDone) {
  89164. this._currentPriorityLevel++;
  89165. }
  89166. // Let's the system running for a specific amount of time before checking FPS
  89167. scene.executeWhenReady(function () {
  89168. setTimeout(function () {
  89169. _this._checkCurrentState();
  89170. }, _this._trackerDuration);
  89171. });
  89172. };
  89173. /**
  89174. * Release all resources
  89175. */
  89176. SceneOptimizer.prototype.dispose = function () {
  89177. this.stop();
  89178. this.onSuccessObservable.clear();
  89179. this.onFailureObservable.clear();
  89180. this.onNewOptimizationAppliedObservable.clear();
  89181. if (this._sceneDisposeObserver) {
  89182. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  89183. }
  89184. };
  89185. /**
  89186. * Helper function to create a SceneOptimizer with one single line of code
  89187. * @param scene defines the scene to work on
  89188. * @param options defines the options to use with the SceneOptimizer
  89189. * @param onSuccess defines a callback to call on success
  89190. * @param onFailure defines a callback to call on failure
  89191. * @returns the new SceneOptimizer object
  89192. */
  89193. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  89194. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  89195. if (onSuccess) {
  89196. optimizer.onSuccessObservable.add(function () {
  89197. onSuccess();
  89198. });
  89199. }
  89200. if (onFailure) {
  89201. optimizer.onFailureObservable.add(function () {
  89202. onFailure();
  89203. });
  89204. }
  89205. optimizer.start();
  89206. return optimizer;
  89207. };
  89208. return SceneOptimizer;
  89209. }());
  89210. BABYLON.SceneOptimizer = SceneOptimizer;
  89211. })(BABYLON || (BABYLON = {}));
  89212. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  89213. "use strict";
  89214. var BABYLON;
  89215. (function (BABYLON) {
  89216. var OutlineRenderer = /** @class */ (function () {
  89217. function OutlineRenderer(scene) {
  89218. this.zOffset = 1;
  89219. this._scene = scene;
  89220. }
  89221. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  89222. var _this = this;
  89223. if (useOverlay === void 0) { useOverlay = false; }
  89224. var scene = this._scene;
  89225. var engine = this._scene.getEngine();
  89226. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  89227. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  89228. return;
  89229. }
  89230. var mesh = subMesh.getRenderingMesh();
  89231. var material = subMesh.getMaterial();
  89232. if (!material || !scene.activeCamera) {
  89233. return;
  89234. }
  89235. engine.enableEffect(this._effect);
  89236. // Logarithmic depth
  89237. if (material.useLogarithmicDepth) {
  89238. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  89239. }
  89240. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  89241. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  89242. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  89243. // Bones
  89244. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  89245. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  89246. }
  89247. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  89248. // Alpha test
  89249. if (material && material.needAlphaTesting()) {
  89250. var alphaTexture = material.getAlphaTestTexture();
  89251. if (alphaTexture) {
  89252. this._effect.setTexture("diffuseSampler", alphaTexture);
  89253. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  89254. }
  89255. }
  89256. engine.setZOffset(-this.zOffset);
  89257. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  89258. engine.setZOffset(0);
  89259. };
  89260. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  89261. var defines = [];
  89262. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  89263. var mesh = subMesh.getMesh();
  89264. var material = subMesh.getMaterial();
  89265. if (material) {
  89266. // Alpha test
  89267. if (material.needAlphaTesting()) {
  89268. defines.push("#define ALPHATEST");
  89269. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  89270. attribs.push(BABYLON.VertexBuffer.UVKind);
  89271. defines.push("#define UV1");
  89272. }
  89273. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  89274. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89275. defines.push("#define UV2");
  89276. }
  89277. }
  89278. //Logarithmic depth
  89279. if (material.useLogarithmicDepth) {
  89280. defines.push("#define LOGARITHMICDEPTH");
  89281. }
  89282. }
  89283. // Bones
  89284. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  89285. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  89286. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  89287. if (mesh.numBoneInfluencers > 4) {
  89288. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  89289. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  89290. }
  89291. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  89292. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  89293. }
  89294. else {
  89295. defines.push("#define NUM_BONE_INFLUENCERS 0");
  89296. }
  89297. // Instances
  89298. if (useInstances) {
  89299. defines.push("#define INSTANCES");
  89300. attribs.push("world0");
  89301. attribs.push("world1");
  89302. attribs.push("world2");
  89303. attribs.push("world3");
  89304. }
  89305. // Get correct effect
  89306. var join = defines.join("\n");
  89307. if (this._cachedDefines !== join) {
  89308. this._cachedDefines = join;
  89309. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  89310. }
  89311. return this._effect.isReady();
  89312. };
  89313. return OutlineRenderer;
  89314. }());
  89315. BABYLON.OutlineRenderer = OutlineRenderer;
  89316. })(BABYLON || (BABYLON = {}));
  89317. //# sourceMappingURL=babylon.outlineRenderer.js.map
  89318. "use strict";
  89319. var BABYLON;
  89320. (function (BABYLON) {
  89321. var FaceAdjacencies = /** @class */ (function () {
  89322. function FaceAdjacencies() {
  89323. this.edges = new Array();
  89324. this.edgesConnectedCount = 0;
  89325. }
  89326. return FaceAdjacencies;
  89327. }());
  89328. var EdgesRenderer = /** @class */ (function () {
  89329. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  89330. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  89331. if (epsilon === void 0) { epsilon = 0.95; }
  89332. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  89333. this.edgesWidthScalerForOrthographic = 1000.0;
  89334. this.edgesWidthScalerForPerspective = 50.0;
  89335. this._linesPositions = new Array();
  89336. this._linesNormals = new Array();
  89337. this._linesIndices = new Array();
  89338. this._buffers = {};
  89339. this._checkVerticesInsteadOfIndices = false;
  89340. this._source = source;
  89341. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  89342. this._epsilon = epsilon;
  89343. this._prepareRessources();
  89344. this._generateEdgesLines();
  89345. }
  89346. EdgesRenderer.prototype._prepareRessources = function () {
  89347. if (this._lineShader) {
  89348. return;
  89349. }
  89350. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  89351. attributes: ["position", "normal"],
  89352. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  89353. });
  89354. this._lineShader.disableDepthWrite = true;
  89355. this._lineShader.backFaceCulling = false;
  89356. };
  89357. EdgesRenderer.prototype._rebuild = function () {
  89358. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  89359. if (buffer) {
  89360. buffer._rebuild();
  89361. }
  89362. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  89363. if (buffer) {
  89364. buffer._rebuild();
  89365. }
  89366. var scene = this._source.getScene();
  89367. var engine = scene.getEngine();
  89368. this._ib = engine.createIndexBuffer(this._linesIndices);
  89369. };
  89370. EdgesRenderer.prototype.dispose = function () {
  89371. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  89372. if (buffer) {
  89373. buffer.dispose();
  89374. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  89375. }
  89376. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  89377. if (buffer) {
  89378. buffer.dispose();
  89379. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  89380. }
  89381. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  89382. this._lineShader.dispose();
  89383. };
  89384. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  89385. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  89386. return 0;
  89387. }
  89388. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  89389. return 1;
  89390. }
  89391. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  89392. return 2;
  89393. }
  89394. return -1;
  89395. };
  89396. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  89397. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  89398. return 0;
  89399. }
  89400. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  89401. return 1;
  89402. }
  89403. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  89404. return 2;
  89405. }
  89406. return -1;
  89407. };
  89408. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  89409. var needToCreateLine;
  89410. if (edge === undefined) {
  89411. needToCreateLine = true;
  89412. }
  89413. else {
  89414. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  89415. needToCreateLine = dotProduct < this._epsilon;
  89416. }
  89417. if (needToCreateLine) {
  89418. var offset = this._linesPositions.length / 3;
  89419. var normal = p0.subtract(p1);
  89420. normal.normalize();
  89421. // Positions
  89422. this._linesPositions.push(p0.x);
  89423. this._linesPositions.push(p0.y);
  89424. this._linesPositions.push(p0.z);
  89425. this._linesPositions.push(p0.x);
  89426. this._linesPositions.push(p0.y);
  89427. this._linesPositions.push(p0.z);
  89428. this._linesPositions.push(p1.x);
  89429. this._linesPositions.push(p1.y);
  89430. this._linesPositions.push(p1.z);
  89431. this._linesPositions.push(p1.x);
  89432. this._linesPositions.push(p1.y);
  89433. this._linesPositions.push(p1.z);
  89434. // Normals
  89435. this._linesNormals.push(p1.x);
  89436. this._linesNormals.push(p1.y);
  89437. this._linesNormals.push(p1.z);
  89438. this._linesNormals.push(-1);
  89439. this._linesNormals.push(p1.x);
  89440. this._linesNormals.push(p1.y);
  89441. this._linesNormals.push(p1.z);
  89442. this._linesNormals.push(1);
  89443. this._linesNormals.push(p0.x);
  89444. this._linesNormals.push(p0.y);
  89445. this._linesNormals.push(p0.z);
  89446. this._linesNormals.push(-1);
  89447. this._linesNormals.push(p0.x);
  89448. this._linesNormals.push(p0.y);
  89449. this._linesNormals.push(p0.z);
  89450. this._linesNormals.push(1);
  89451. // Indices
  89452. this._linesIndices.push(offset);
  89453. this._linesIndices.push(offset + 1);
  89454. this._linesIndices.push(offset + 2);
  89455. this._linesIndices.push(offset);
  89456. this._linesIndices.push(offset + 2);
  89457. this._linesIndices.push(offset + 3);
  89458. }
  89459. };
  89460. EdgesRenderer.prototype._generateEdgesLines = function () {
  89461. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89462. var indices = this._source.getIndices();
  89463. if (!indices || !positions) {
  89464. return;
  89465. }
  89466. // First let's find adjacencies
  89467. var adjacencies = new Array();
  89468. var faceNormals = new Array();
  89469. var index;
  89470. var faceAdjacencies;
  89471. // Prepare faces
  89472. for (index = 0; index < indices.length; index += 3) {
  89473. faceAdjacencies = new FaceAdjacencies();
  89474. var p0Index = indices[index];
  89475. var p1Index = indices[index + 1];
  89476. var p2Index = indices[index + 2];
  89477. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  89478. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  89479. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  89480. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  89481. faceNormal.normalize();
  89482. faceNormals.push(faceNormal);
  89483. adjacencies.push(faceAdjacencies);
  89484. }
  89485. // Scan
  89486. for (index = 0; index < adjacencies.length; index++) {
  89487. faceAdjacencies = adjacencies[index];
  89488. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  89489. var otherFaceAdjacencies = adjacencies[otherIndex];
  89490. if (faceAdjacencies.edgesConnectedCount === 3) {
  89491. break;
  89492. }
  89493. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  89494. continue;
  89495. }
  89496. var otherP0 = indices[otherIndex * 3];
  89497. var otherP1 = indices[otherIndex * 3 + 1];
  89498. var otherP2 = indices[otherIndex * 3 + 2];
  89499. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  89500. var otherEdgeIndex = 0;
  89501. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  89502. continue;
  89503. }
  89504. switch (edgeIndex) {
  89505. case 0:
  89506. if (this._checkVerticesInsteadOfIndices) {
  89507. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  89508. }
  89509. else {
  89510. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  89511. }
  89512. break;
  89513. case 1:
  89514. if (this._checkVerticesInsteadOfIndices) {
  89515. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  89516. }
  89517. else {
  89518. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  89519. }
  89520. break;
  89521. case 2:
  89522. if (this._checkVerticesInsteadOfIndices) {
  89523. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  89524. }
  89525. else {
  89526. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  89527. }
  89528. break;
  89529. }
  89530. if (otherEdgeIndex === -1) {
  89531. continue;
  89532. }
  89533. faceAdjacencies.edges[edgeIndex] = otherIndex;
  89534. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  89535. faceAdjacencies.edgesConnectedCount++;
  89536. otherFaceAdjacencies.edgesConnectedCount++;
  89537. if (faceAdjacencies.edgesConnectedCount === 3) {
  89538. break;
  89539. }
  89540. }
  89541. }
  89542. }
  89543. // Create lines
  89544. for (index = 0; index < adjacencies.length; index++) {
  89545. // 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
  89546. var current = adjacencies[index];
  89547. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  89548. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  89549. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  89550. }
  89551. // Merge into a single mesh
  89552. var engine = this._source.getScene().getEngine();
  89553. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  89554. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  89555. this._ib = engine.createIndexBuffer(this._linesIndices);
  89556. this._indicesCount = this._linesIndices.length;
  89557. };
  89558. EdgesRenderer.prototype.render = function () {
  89559. var scene = this._source.getScene();
  89560. if (!this._lineShader.isReady() || !scene.activeCamera) {
  89561. return;
  89562. }
  89563. var engine = scene.getEngine();
  89564. this._lineShader._preBind();
  89565. // VBOs
  89566. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  89567. scene.resetCachedMaterial();
  89568. this._lineShader.setColor4("color", this._source.edgesColor);
  89569. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  89570. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  89571. }
  89572. else {
  89573. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  89574. }
  89575. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  89576. this._lineShader.bind(this._source.getWorldMatrix());
  89577. // Draw order
  89578. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  89579. this._lineShader.unbind();
  89580. engine.setDepthWrite(true);
  89581. };
  89582. return EdgesRenderer;
  89583. }());
  89584. BABYLON.EdgesRenderer = EdgesRenderer;
  89585. })(BABYLON || (BABYLON = {}));
  89586. //# sourceMappingURL=babylon.edgesRenderer.js.map
  89587. "use strict";
  89588. var __assign = (this && this.__assign) || Object.assign || function(t) {
  89589. for (var s, i = 1, n = arguments.length; i < n; i++) {
  89590. s = arguments[i];
  89591. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  89592. t[p] = s[p];
  89593. }
  89594. return t;
  89595. };
  89596. var BABYLON;
  89597. (function (BABYLON) {
  89598. /**
  89599. * The effect layer Helps adding post process effect blended with the main pass.
  89600. *
  89601. * This can be for instance use to generate glow or higlight effects on the scene.
  89602. *
  89603. * The effect layer class can not be used directly and is intented to inherited from to be
  89604. * customized per effects.
  89605. */
  89606. var EffectLayer = /** @class */ (function () {
  89607. /**
  89608. * Instantiates a new effect Layer and references it in the scene.
  89609. * @param name The name of the layer
  89610. * @param scene The scene to use the layer in
  89611. */
  89612. function EffectLayer(
  89613. /** The Friendly of the effect in the scene */
  89614. name, scene) {
  89615. this._vertexBuffers = {};
  89616. this._maxSize = 0;
  89617. this._mainTextureDesiredSize = { width: 0, height: 0 };
  89618. this._shouldRender = true;
  89619. this._postProcesses = [];
  89620. this._textures = [];
  89621. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  89622. /**
  89623. * The clear color of the texture used to generate the glow map.
  89624. */
  89625. this.neutralColor = new BABYLON.Color4();
  89626. /**
  89627. * Specifies wether the highlight layer is enabled or not.
  89628. */
  89629. this.isEnabled = true;
  89630. /**
  89631. * An event triggered when the effect layer has been disposed.
  89632. */
  89633. this.onDisposeObservable = new BABYLON.Observable();
  89634. /**
  89635. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  89636. */
  89637. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  89638. /**
  89639. * An event triggered when the generated texture is being merged in the scene.
  89640. */
  89641. this.onBeforeComposeObservable = new BABYLON.Observable();
  89642. /**
  89643. * An event triggered when the generated texture has been merged in the scene.
  89644. */
  89645. this.onAfterComposeObservable = new BABYLON.Observable();
  89646. /**
  89647. * An event triggered when the efffect layer changes its size.
  89648. */
  89649. this.onSizeChangedObservable = new BABYLON.Observable();
  89650. this.name = name;
  89651. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89652. this._engine = scene.getEngine();
  89653. this._maxSize = this._engine.getCaps().maxTextureSize;
  89654. this._scene.effectLayers.push(this);
  89655. // Generate Buffers
  89656. this._generateIndexBuffer();
  89657. this._genrateVertexBuffer();
  89658. }
  89659. Object.defineProperty(EffectLayer.prototype, "camera", {
  89660. /**
  89661. * Gets the camera attached to the layer.
  89662. */
  89663. get: function () {
  89664. return this._effectLayerOptions.camera;
  89665. },
  89666. enumerable: true,
  89667. configurable: true
  89668. });
  89669. /**
  89670. * Initializes the effect layer with the required options.
  89671. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  89672. */
  89673. EffectLayer.prototype._init = function (options) {
  89674. // Adapt options
  89675. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  89676. this._setMainTextureSize();
  89677. this._createMainTexture();
  89678. this._createTextureAndPostProcesses();
  89679. this._mergeEffect = this._createMergeEffect();
  89680. };
  89681. /**
  89682. * Generates the index buffer of the full screen quad blending to the main canvas.
  89683. */
  89684. EffectLayer.prototype._generateIndexBuffer = function () {
  89685. // Indices
  89686. var indices = [];
  89687. indices.push(0);
  89688. indices.push(1);
  89689. indices.push(2);
  89690. indices.push(0);
  89691. indices.push(2);
  89692. indices.push(3);
  89693. this._indexBuffer = this._engine.createIndexBuffer(indices);
  89694. };
  89695. /**
  89696. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  89697. */
  89698. EffectLayer.prototype._genrateVertexBuffer = function () {
  89699. // VBO
  89700. var vertices = [];
  89701. vertices.push(1, 1);
  89702. vertices.push(-1, 1);
  89703. vertices.push(-1, -1);
  89704. vertices.push(1, -1);
  89705. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  89706. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  89707. };
  89708. /**
  89709. * Sets the main texture desired size which is the closest power of two
  89710. * of the engine canvas size.
  89711. */
  89712. EffectLayer.prototype._setMainTextureSize = function () {
  89713. if (this._effectLayerOptions.mainTextureFixedSize) {
  89714. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  89715. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  89716. }
  89717. else {
  89718. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  89719. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  89720. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  89721. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  89722. }
  89723. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  89724. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  89725. };
  89726. /**
  89727. * Creates the main texture for the effect layer.
  89728. */
  89729. EffectLayer.prototype._createMainTexture = function () {
  89730. var _this = this;
  89731. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  89732. width: this._mainTextureDesiredSize.width,
  89733. height: this._mainTextureDesiredSize.height
  89734. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89735. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  89736. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89737. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89738. this._mainTexture.anisotropicFilteringLevel = 1;
  89739. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89740. this._mainTexture.renderParticles = false;
  89741. this._mainTexture.renderList = null;
  89742. this._mainTexture.ignoreCameraViewport = true;
  89743. // Custom render function
  89744. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  89745. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  89746. var index;
  89747. var engine = _this._scene.getEngine();
  89748. if (depthOnlySubMeshes.length) {
  89749. engine.setColorWrite(false);
  89750. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  89751. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  89752. }
  89753. engine.setColorWrite(true);
  89754. }
  89755. for (index = 0; index < opaqueSubMeshes.length; index++) {
  89756. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  89757. }
  89758. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  89759. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  89760. }
  89761. for (index = 0; index < transparentSubMeshes.length; index++) {
  89762. _this._renderSubMesh(transparentSubMeshes.data[index]);
  89763. }
  89764. };
  89765. this._mainTexture.onClearObservable.add(function (engine) {
  89766. engine.clear(_this.neutralColor, true, true, true);
  89767. });
  89768. };
  89769. /**
  89770. * Checks for the readiness of the element composing the layer.
  89771. * @param subMesh the mesh to check for
  89772. * @param useInstances specify wether or not to use instances to render the mesh
  89773. * @param emissiveTexture the associated emissive texture used to generate the glow
  89774. * @return true if ready otherwise, false
  89775. */
  89776. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  89777. var material = subMesh.getMaterial();
  89778. if (!material) {
  89779. return false;
  89780. }
  89781. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  89782. return false;
  89783. }
  89784. var defines = [];
  89785. var attribs = [BABYLON.VertexBuffer.PositionKind];
  89786. var mesh = subMesh.getMesh();
  89787. var uv1 = false;
  89788. var uv2 = false;
  89789. // Alpha test
  89790. if (material && material.needAlphaTesting()) {
  89791. var alphaTexture = material.getAlphaTestTexture();
  89792. if (alphaTexture) {
  89793. defines.push("#define ALPHATEST");
  89794. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  89795. alphaTexture.coordinatesIndex === 1) {
  89796. defines.push("#define DIFFUSEUV2");
  89797. uv2 = true;
  89798. }
  89799. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  89800. defines.push("#define DIFFUSEUV1");
  89801. uv1 = true;
  89802. }
  89803. }
  89804. }
  89805. // Emissive
  89806. if (emissiveTexture) {
  89807. defines.push("#define EMISSIVE");
  89808. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  89809. emissiveTexture.coordinatesIndex === 1) {
  89810. defines.push("#define EMISSIVEUV2");
  89811. uv2 = true;
  89812. }
  89813. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  89814. defines.push("#define EMISSIVEUV1");
  89815. uv1 = true;
  89816. }
  89817. }
  89818. if (uv1) {
  89819. attribs.push(BABYLON.VertexBuffer.UVKind);
  89820. defines.push("#define UV1");
  89821. }
  89822. if (uv2) {
  89823. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89824. defines.push("#define UV2");
  89825. }
  89826. // Bones
  89827. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  89828. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  89829. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  89830. if (mesh.numBoneInfluencers > 4) {
  89831. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  89832. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  89833. }
  89834. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  89835. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  89836. }
  89837. else {
  89838. defines.push("#define NUM_BONE_INFLUENCERS 0");
  89839. }
  89840. // Morph targets
  89841. var manager = mesh.morphTargetManager;
  89842. var morphInfluencers = 0;
  89843. if (manager) {
  89844. if (manager.numInfluencers > 0) {
  89845. defines.push("#define MORPHTARGETS");
  89846. morphInfluencers = manager.numInfluencers;
  89847. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  89848. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  89849. }
  89850. }
  89851. // Instances
  89852. if (useInstances) {
  89853. defines.push("#define INSTANCES");
  89854. attribs.push("world0");
  89855. attribs.push("world1");
  89856. attribs.push("world2");
  89857. attribs.push("world3");
  89858. }
  89859. // Get correct effect
  89860. var join = defines.join("\n");
  89861. if (this._cachedDefines !== join) {
  89862. this._cachedDefines = join;
  89863. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  89864. }
  89865. return this._effectLayerMapGenerationEffect.isReady();
  89866. };
  89867. /**
  89868. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  89869. */
  89870. EffectLayer.prototype.render = function () {
  89871. var currentEffect = this._mergeEffect;
  89872. // Check
  89873. if (!currentEffect.isReady())
  89874. return;
  89875. for (var i = 0; i < this._postProcesses.length; i++) {
  89876. if (!this._postProcesses[i].isReady()) {
  89877. return;
  89878. }
  89879. }
  89880. var engine = this._scene.getEngine();
  89881. this.onBeforeComposeObservable.notifyObservers(this);
  89882. // Render
  89883. engine.enableEffect(currentEffect);
  89884. engine.setState(false);
  89885. // VBOs
  89886. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  89887. // Cache
  89888. var previousAlphaMode = engine.getAlphaMode();
  89889. // Go Blend.
  89890. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  89891. // Blends the map on the main canvas.
  89892. this._internalRender(currentEffect);
  89893. // Restore Alpha
  89894. engine.setAlphaMode(previousAlphaMode);
  89895. this.onAfterComposeObservable.notifyObservers(this);
  89896. // Handle size changes.
  89897. var size = this._mainTexture.getSize();
  89898. this._setMainTextureSize();
  89899. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  89900. // Recreate RTT and post processes on size change.
  89901. this.onSizeChangedObservable.notifyObservers(this);
  89902. this._disposeTextureAndPostProcesses();
  89903. this._createMainTexture();
  89904. this._createTextureAndPostProcesses();
  89905. }
  89906. };
  89907. /**
  89908. * Determine if a given mesh will be used in the current effect.
  89909. * @param mesh mesh to test
  89910. * @returns true if the mesh will be used
  89911. */
  89912. EffectLayer.prototype.hasMesh = function (mesh) {
  89913. return true;
  89914. };
  89915. /**
  89916. * Returns true if the layer contains information to display, otherwise false.
  89917. * @returns true if the glow layer should be rendered
  89918. */
  89919. EffectLayer.prototype.shouldRender = function () {
  89920. return this.isEnabled && this._shouldRender;
  89921. };
  89922. /**
  89923. * Returns true if the mesh should render, otherwise false.
  89924. * @param mesh The mesh to render
  89925. * @returns true if it should render otherwise false
  89926. */
  89927. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  89928. return true;
  89929. };
  89930. /**
  89931. * Returns true if the mesh should render, otherwise false.
  89932. * @param mesh The mesh to render
  89933. * @returns true if it should render otherwise false
  89934. */
  89935. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  89936. return true;
  89937. };
  89938. /**
  89939. * Renders the submesh passed in parameter to the generation map.
  89940. */
  89941. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  89942. var _this = this;
  89943. if (!this.shouldRender()) {
  89944. return;
  89945. }
  89946. var material = subMesh.getMaterial();
  89947. var mesh = subMesh.getRenderingMesh();
  89948. var scene = this._scene;
  89949. var engine = scene.getEngine();
  89950. if (!material) {
  89951. return;
  89952. }
  89953. // Do not block in blend mode.
  89954. if (material.needAlphaBlendingForMesh(mesh)) {
  89955. return;
  89956. }
  89957. // Culling
  89958. engine.setState(material.backFaceCulling);
  89959. // Managing instances
  89960. var batch = mesh._getInstancesRenderList(subMesh._id);
  89961. if (batch.mustReturn) {
  89962. return;
  89963. }
  89964. // Early Exit per mesh
  89965. if (!this._shouldRenderMesh(mesh)) {
  89966. return;
  89967. }
  89968. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  89969. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  89970. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  89971. engine.enableEffect(this._effectLayerMapGenerationEffect);
  89972. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  89973. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  89974. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  89975. // Alpha test
  89976. if (material && material.needAlphaTesting()) {
  89977. var alphaTexture = material.getAlphaTestTexture();
  89978. if (alphaTexture) {
  89979. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  89980. var textureMatrix = alphaTexture.getTextureMatrix();
  89981. if (textureMatrix) {
  89982. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  89983. }
  89984. }
  89985. }
  89986. // Glow emissive only
  89987. if (this._emissiveTextureAndColor.texture) {
  89988. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  89989. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  89990. }
  89991. // Bones
  89992. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  89993. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  89994. }
  89995. // Morph targets
  89996. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  89997. // Draw
  89998. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  89999. }
  90000. else {
  90001. // Need to reset refresh rate of the shadowMap
  90002. this._mainTexture.resetRefreshCounter();
  90003. }
  90004. };
  90005. /**
  90006. * Rebuild the required buffers.
  90007. * @ignore Internal use only.
  90008. */
  90009. EffectLayer.prototype._rebuild = function () {
  90010. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90011. if (vb) {
  90012. vb._rebuild();
  90013. }
  90014. this._generateIndexBuffer();
  90015. };
  90016. /**
  90017. * Dispose only the render target textures and post process.
  90018. */
  90019. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  90020. this._mainTexture.dispose();
  90021. for (var i = 0; i < this._postProcesses.length; i++) {
  90022. if (this._postProcesses[i]) {
  90023. this._postProcesses[i].dispose();
  90024. }
  90025. }
  90026. this._postProcesses = [];
  90027. for (var i = 0; i < this._textures.length; i++) {
  90028. if (this._textures[i]) {
  90029. this._textures[i].dispose();
  90030. }
  90031. }
  90032. this._textures = [];
  90033. };
  90034. /**
  90035. * Dispose the highlight layer and free resources.
  90036. */
  90037. EffectLayer.prototype.dispose = function () {
  90038. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90039. if (vertexBuffer) {
  90040. vertexBuffer.dispose();
  90041. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  90042. }
  90043. if (this._indexBuffer) {
  90044. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  90045. this._indexBuffer = null;
  90046. }
  90047. // Clean textures and post processes
  90048. this._disposeTextureAndPostProcesses();
  90049. // Remove from scene
  90050. var index = this._scene.effectLayers.indexOf(this, 0);
  90051. if (index > -1) {
  90052. this._scene.effectLayers.splice(index, 1);
  90053. }
  90054. // Callback
  90055. this.onDisposeObservable.notifyObservers(this);
  90056. this.onDisposeObservable.clear();
  90057. this.onBeforeRenderMainTextureObservable.clear();
  90058. this.onBeforeComposeObservable.clear();
  90059. this.onAfterComposeObservable.clear();
  90060. this.onSizeChangedObservable.clear();
  90061. };
  90062. /**
  90063. * Gets the class name of the effect layer
  90064. * @returns the string with the class name of the effect layer
  90065. */
  90066. EffectLayer.prototype.getClassName = function () {
  90067. return "EffectLayer";
  90068. };
  90069. /**
  90070. * Creates an effect layer from parsed effect layer data
  90071. * @param parsedEffectLayer defines effect layer data
  90072. * @param scene defines the current scene
  90073. * @param rootUrl defines the root URL containing the effect layer information
  90074. * @returns a parsed effect Layer
  90075. */
  90076. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  90077. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  90078. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  90079. };
  90080. __decorate([
  90081. BABYLON.serialize()
  90082. ], EffectLayer.prototype, "name", void 0);
  90083. __decorate([
  90084. BABYLON.serializeAsColor4()
  90085. ], EffectLayer.prototype, "neutralColor", void 0);
  90086. __decorate([
  90087. BABYLON.serialize()
  90088. ], EffectLayer.prototype, "isEnabled", void 0);
  90089. __decorate([
  90090. BABYLON.serializeAsCameraReference()
  90091. ], EffectLayer.prototype, "camera", null);
  90092. return EffectLayer;
  90093. }());
  90094. BABYLON.EffectLayer = EffectLayer;
  90095. })(BABYLON || (BABYLON = {}));
  90096. //# sourceMappingURL=babylon.effectLayer.js.map
  90097. "use strict";
  90098. var BABYLON;
  90099. (function (BABYLON) {
  90100. /**
  90101. * Special Glow Blur post process only blurring the alpha channel
  90102. * It enforces keeping the most luminous color in the color channel.
  90103. */
  90104. var GlowBlurPostProcess = /** @class */ (function (_super) {
  90105. __extends(GlowBlurPostProcess, _super);
  90106. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  90107. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  90108. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  90109. _this.direction = direction;
  90110. _this.kernel = kernel;
  90111. _this.onApplyObservable.add(function (effect) {
  90112. effect.setFloat2("screenSize", _this.width, _this.height);
  90113. effect.setVector2("direction", _this.direction);
  90114. effect.setFloat("blurWidth", _this.kernel);
  90115. });
  90116. return _this;
  90117. }
  90118. return GlowBlurPostProcess;
  90119. }(BABYLON.PostProcess));
  90120. /**
  90121. * The highlight layer Helps adding a glow effect around a mesh.
  90122. *
  90123. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  90124. * glowy meshes to your scene.
  90125. *
  90126. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  90127. */
  90128. var HighlightLayer = /** @class */ (function (_super) {
  90129. __extends(HighlightLayer, _super);
  90130. /**
  90131. * Instantiates a new highlight Layer and references it to the scene..
  90132. * @param name The name of the layer
  90133. * @param scene The scene to use the layer in
  90134. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  90135. */
  90136. function HighlightLayer(name, scene, options) {
  90137. var _this = _super.call(this, name, scene) || this;
  90138. _this.name = name;
  90139. /**
  90140. * Specifies whether or not the inner glow is ACTIVE in the layer.
  90141. */
  90142. _this.innerGlow = true;
  90143. /**
  90144. * Specifies whether or not the outer glow is ACTIVE in the layer.
  90145. */
  90146. _this.outerGlow = true;
  90147. /**
  90148. * An event triggered when the highlight layer is being blurred.
  90149. */
  90150. _this.onBeforeBlurObservable = new BABYLON.Observable();
  90151. /**
  90152. * An event triggered when the highlight layer has been blurred.
  90153. */
  90154. _this.onAfterBlurObservable = new BABYLON.Observable();
  90155. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  90156. _this._meshes = {};
  90157. _this._excludedMeshes = {};
  90158. _this.neutralColor = HighlightLayer.NeutralColor;
  90159. // Warn on stencil
  90160. if (!_this._engine.isStencilEnable) {
  90161. 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 }");
  90162. }
  90163. // Adapt options
  90164. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  90165. // Initialize the layer
  90166. _this._init({
  90167. alphaBlendingMode: _this._options.alphaBlendingMode,
  90168. camera: _this._options.camera,
  90169. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  90170. mainTextureRatio: _this._options.mainTextureRatio
  90171. });
  90172. // Do not render as long as no meshes have been added
  90173. _this._shouldRender = false;
  90174. return _this;
  90175. }
  90176. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  90177. /**
  90178. * Gets the horizontal size of the blur.
  90179. */
  90180. get: function () {
  90181. return this._horizontalBlurPostprocess.kernel;
  90182. },
  90183. /**
  90184. * Specifies the horizontal size of the blur.
  90185. */
  90186. set: function (value) {
  90187. this._horizontalBlurPostprocess.kernel = value;
  90188. },
  90189. enumerable: true,
  90190. configurable: true
  90191. });
  90192. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  90193. /**
  90194. * Gets the vertical size of the blur.
  90195. */
  90196. get: function () {
  90197. return this._verticalBlurPostprocess.kernel;
  90198. },
  90199. /**
  90200. * Specifies the vertical size of the blur.
  90201. */
  90202. set: function (value) {
  90203. this._verticalBlurPostprocess.kernel = value;
  90204. },
  90205. enumerable: true,
  90206. configurable: true
  90207. });
  90208. /**
  90209. * Get the effect name of the layer.
  90210. * @return The effect name
  90211. */
  90212. HighlightLayer.prototype.getEffectName = function () {
  90213. return HighlightLayer.EffectName;
  90214. };
  90215. /**
  90216. * Create the merge effect. This is the shader use to blit the information back
  90217. * to the main canvas at the end of the scene rendering.
  90218. */
  90219. HighlightLayer.prototype._createMergeEffect = function () {
  90220. // Effect
  90221. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  90222. };
  90223. /**
  90224. * Creates the render target textures and post processes used in the highlight layer.
  90225. */
  90226. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  90227. var _this = this;
  90228. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  90229. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  90230. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  90231. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  90232. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  90233. width: blurTextureWidth,
  90234. height: blurTextureHeight
  90235. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  90236. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90237. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90238. this._blurTexture.anisotropicFilteringLevel = 16;
  90239. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  90240. this._blurTexture.renderParticles = false;
  90241. this._blurTexture.ignoreCameraViewport = true;
  90242. this._textures = [this._blurTexture];
  90243. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  90244. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  90245. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  90246. effect.setTexture("textureSampler", _this._mainTexture);
  90247. });
  90248. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  90249. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  90250. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  90251. });
  90252. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  90253. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  90254. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  90255. });
  90256. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  90257. }
  90258. else {
  90259. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  90260. width: blurTextureWidth,
  90261. height: blurTextureHeight
  90262. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  90263. this._horizontalBlurPostprocess.width = blurTextureWidth;
  90264. this._horizontalBlurPostprocess.height = blurTextureHeight;
  90265. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  90266. effect.setTexture("textureSampler", _this._mainTexture);
  90267. });
  90268. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  90269. width: blurTextureWidth,
  90270. height: blurTextureHeight
  90271. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  90272. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  90273. }
  90274. this._mainTexture.onAfterUnbindObservable.add(function () {
  90275. _this.onBeforeBlurObservable.notifyObservers(_this);
  90276. var internalTexture = _this._blurTexture.getInternalTexture();
  90277. if (internalTexture) {
  90278. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  90279. }
  90280. _this.onAfterBlurObservable.notifyObservers(_this);
  90281. });
  90282. // Prevent autoClear.
  90283. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  90284. };
  90285. /**
  90286. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  90287. */
  90288. HighlightLayer.prototype.needStencil = function () {
  90289. return true;
  90290. };
  90291. /**
  90292. * Checks for the readiness of the element composing the layer.
  90293. * @param subMesh the mesh to check for
  90294. * @param useInstances specify wether or not to use instances to render the mesh
  90295. * @param emissiveTexture the associated emissive texture used to generate the glow
  90296. * @return true if ready otherwise, false
  90297. */
  90298. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  90299. var material = subMesh.getMaterial();
  90300. var mesh = subMesh.getRenderingMesh();
  90301. if (!material || !mesh || !this._meshes) {
  90302. return false;
  90303. }
  90304. var emissiveTexture = null;
  90305. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  90306. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  90307. emissiveTexture = material.emissiveTexture;
  90308. }
  90309. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  90310. };
  90311. /**
  90312. * Implementation specific of rendering the generating effect on the main canvas.
  90313. * @param effect The effect used to render through
  90314. */
  90315. HighlightLayer.prototype._internalRender = function (effect) {
  90316. // Texture
  90317. effect.setTexture("textureSampler", this._blurTexture);
  90318. // Cache
  90319. var engine = this._engine;
  90320. var previousStencilBuffer = engine.getStencilBuffer();
  90321. var previousStencilFunction = engine.getStencilFunction();
  90322. var previousStencilMask = engine.getStencilMask();
  90323. var previousStencilOperationPass = engine.getStencilOperationPass();
  90324. var previousStencilOperationFail = engine.getStencilOperationFail();
  90325. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  90326. var previousStencilReference = engine.getStencilFunctionReference();
  90327. // Stencil operations
  90328. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  90329. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  90330. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  90331. // Draw order
  90332. engine.setStencilMask(0x00);
  90333. engine.setStencilBuffer(true);
  90334. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  90335. // 2 passes inner outer
  90336. if (this.outerGlow) {
  90337. effect.setFloat("offset", 0);
  90338. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  90339. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  90340. }
  90341. if (this.innerGlow) {
  90342. effect.setFloat("offset", 1);
  90343. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  90344. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  90345. }
  90346. // Restore Cache
  90347. engine.setStencilFunction(previousStencilFunction);
  90348. engine.setStencilMask(previousStencilMask);
  90349. engine.setStencilBuffer(previousStencilBuffer);
  90350. engine.setStencilOperationPass(previousStencilOperationPass);
  90351. engine.setStencilOperationFail(previousStencilOperationFail);
  90352. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  90353. engine.setStencilFunctionReference(previousStencilReference);
  90354. };
  90355. /**
  90356. * Returns true if the layer contains information to display, otherwise false.
  90357. */
  90358. HighlightLayer.prototype.shouldRender = function () {
  90359. if (_super.prototype.shouldRender.call(this)) {
  90360. return this._meshes ? true : false;
  90361. }
  90362. return false;
  90363. };
  90364. /**
  90365. * Returns true if the mesh should render, otherwise false.
  90366. * @param mesh The mesh to render
  90367. * @returns true if it should render otherwise false
  90368. */
  90369. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  90370. // Excluded Mesh
  90371. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  90372. return false;
  90373. }
  90374. ;
  90375. return true;
  90376. };
  90377. /**
  90378. * Sets the required values for both the emissive texture and and the main color.
  90379. */
  90380. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  90381. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  90382. if (highlightLayerMesh) {
  90383. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  90384. }
  90385. else {
  90386. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  90387. }
  90388. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  90389. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  90390. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  90391. }
  90392. else {
  90393. this._emissiveTextureAndColor.texture = null;
  90394. }
  90395. };
  90396. /**
  90397. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  90398. * @param mesh The mesh to exclude from the highlight layer
  90399. */
  90400. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  90401. if (!this._excludedMeshes) {
  90402. return;
  90403. }
  90404. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  90405. if (!meshExcluded) {
  90406. this._excludedMeshes[mesh.uniqueId] = {
  90407. mesh: mesh,
  90408. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  90409. mesh.getEngine().setStencilBuffer(false);
  90410. }),
  90411. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  90412. mesh.getEngine().setStencilBuffer(true);
  90413. }),
  90414. };
  90415. }
  90416. };
  90417. /**
  90418. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  90419. * @param mesh The mesh to highlight
  90420. */
  90421. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  90422. if (!this._excludedMeshes) {
  90423. return;
  90424. }
  90425. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  90426. if (meshExcluded) {
  90427. if (meshExcluded.beforeRender) {
  90428. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  90429. }
  90430. if (meshExcluded.afterRender) {
  90431. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  90432. }
  90433. }
  90434. this._excludedMeshes[mesh.uniqueId] = null;
  90435. };
  90436. /**
  90437. * Determine if a given mesh will be highlighted by the current HighlightLayer
  90438. * @param mesh mesh to test
  90439. * @returns true if the mesh will be highlighted by the current HighlightLayer
  90440. */
  90441. HighlightLayer.prototype.hasMesh = function (mesh) {
  90442. if (!this._meshes) {
  90443. return false;
  90444. }
  90445. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  90446. };
  90447. /**
  90448. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  90449. * @param mesh The mesh to highlight
  90450. * @param color The color of the highlight
  90451. * @param glowEmissiveOnly Extract the glow from the emissive texture
  90452. */
  90453. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  90454. var _this = this;
  90455. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  90456. if (!this._meshes) {
  90457. return;
  90458. }
  90459. var meshHighlight = this._meshes[mesh.uniqueId];
  90460. if (meshHighlight) {
  90461. meshHighlight.color = color;
  90462. }
  90463. else {
  90464. this._meshes[mesh.uniqueId] = {
  90465. mesh: mesh,
  90466. color: color,
  90467. // Lambda required for capture due to Observable this context
  90468. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  90469. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  90470. _this._defaultStencilReference(mesh);
  90471. }
  90472. else {
  90473. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  90474. }
  90475. }),
  90476. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  90477. glowEmissiveOnly: glowEmissiveOnly
  90478. };
  90479. }
  90480. this._shouldRender = true;
  90481. };
  90482. /**
  90483. * Remove a mesh from the highlight layer in order to make it stop glowing.
  90484. * @param mesh The mesh to highlight
  90485. */
  90486. HighlightLayer.prototype.removeMesh = function (mesh) {
  90487. if (!this._meshes) {
  90488. return;
  90489. }
  90490. var meshHighlight = this._meshes[mesh.uniqueId];
  90491. if (meshHighlight) {
  90492. if (meshHighlight.observerHighlight) {
  90493. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  90494. }
  90495. if (meshHighlight.observerDefault) {
  90496. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  90497. }
  90498. delete this._meshes[mesh.uniqueId];
  90499. }
  90500. this._shouldRender = false;
  90501. for (var meshHighlightToCheck in this._meshes) {
  90502. if (this._meshes[meshHighlightToCheck]) {
  90503. this._shouldRender = true;
  90504. break;
  90505. }
  90506. }
  90507. };
  90508. /**
  90509. * Force the stencil to the normal expected value for none glowing parts
  90510. */
  90511. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  90512. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  90513. };
  90514. /**
  90515. * Free any resources and references associated to a mesh.
  90516. * Internal use
  90517. * @param mesh The mesh to free.
  90518. */
  90519. HighlightLayer.prototype._disposeMesh = function (mesh) {
  90520. this.removeMesh(mesh);
  90521. this.removeExcludedMesh(mesh);
  90522. };
  90523. /**
  90524. * Dispose the highlight layer and free resources.
  90525. */
  90526. HighlightLayer.prototype.dispose = function () {
  90527. if (this._meshes) {
  90528. // Clean mesh references
  90529. for (var id in this._meshes) {
  90530. var meshHighlight = this._meshes[id];
  90531. if (meshHighlight && meshHighlight.mesh) {
  90532. if (meshHighlight.observerHighlight) {
  90533. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  90534. }
  90535. if (meshHighlight.observerDefault) {
  90536. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  90537. }
  90538. }
  90539. }
  90540. this._meshes = null;
  90541. }
  90542. if (this._excludedMeshes) {
  90543. for (var id in this._excludedMeshes) {
  90544. var meshHighlight = this._excludedMeshes[id];
  90545. if (meshHighlight) {
  90546. if (meshHighlight.beforeRender) {
  90547. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  90548. }
  90549. if (meshHighlight.afterRender) {
  90550. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  90551. }
  90552. }
  90553. }
  90554. this._excludedMeshes = null;
  90555. }
  90556. _super.prototype.dispose.call(this);
  90557. };
  90558. /**
  90559. * Gets the class name of the effect layer
  90560. * @returns the string with the class name of the effect layer
  90561. */
  90562. HighlightLayer.prototype.getClassName = function () {
  90563. return "HighlightLayer";
  90564. };
  90565. /**
  90566. * Serializes this Highlight layer
  90567. * @returns a serialized Highlight layer object
  90568. */
  90569. HighlightLayer.prototype.serialize = function () {
  90570. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90571. serializationObject.customType = "BABYLON.HighlightLayer";
  90572. // Highlighted meshes
  90573. serializationObject.meshes = [];
  90574. if (this._meshes) {
  90575. for (var m in this._meshes) {
  90576. var mesh = this._meshes[m];
  90577. if (mesh) {
  90578. serializationObject.meshes.push({
  90579. glowEmissiveOnly: mesh.glowEmissiveOnly,
  90580. color: mesh.color.asArray(),
  90581. meshId: mesh.mesh.id
  90582. });
  90583. }
  90584. }
  90585. }
  90586. // Excluded meshes
  90587. serializationObject.excludedMeshes = [];
  90588. if (this._excludedMeshes) {
  90589. for (var e in this._excludedMeshes) {
  90590. var excludedMesh = this._excludedMeshes[e];
  90591. if (excludedMesh) {
  90592. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  90593. }
  90594. }
  90595. }
  90596. return serializationObject;
  90597. };
  90598. /**
  90599. * Creates a Highlight layer from parsed Highlight layer data
  90600. * @param parsedHightlightLayer defines the Highlight layer data
  90601. * @param scene defines the current scene
  90602. * @param rootUrl defines the root URL containing the Highlight layer information
  90603. * @returns a parsed Highlight layer
  90604. */
  90605. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  90606. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  90607. var index;
  90608. // Excluded meshes
  90609. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  90610. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  90611. if (mesh) {
  90612. hl.addExcludedMesh(mesh);
  90613. }
  90614. }
  90615. // Included meshes
  90616. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  90617. var highlightedMesh = parsedHightlightLayer.meshes[index];
  90618. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  90619. if (mesh) {
  90620. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  90621. }
  90622. }
  90623. return hl;
  90624. };
  90625. /**
  90626. * Effect Name of the highlight layer.
  90627. */
  90628. HighlightLayer.EffectName = "HighlightLayer";
  90629. /**
  90630. * The neutral color used during the preparation of the glow effect.
  90631. * This is black by default as the blend operation is a blend operation.
  90632. */
  90633. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  90634. /**
  90635. * Stencil value used for glowing meshes.
  90636. */
  90637. HighlightLayer.GlowingMeshStencilReference = 0x02;
  90638. /**
  90639. * Stencil value used for the other meshes in the scene.
  90640. */
  90641. HighlightLayer.NormalMeshStencilReference = 0x01;
  90642. __decorate([
  90643. BABYLON.serialize()
  90644. ], HighlightLayer.prototype, "innerGlow", void 0);
  90645. __decorate([
  90646. BABYLON.serialize()
  90647. ], HighlightLayer.prototype, "outerGlow", void 0);
  90648. __decorate([
  90649. BABYLON.serialize()
  90650. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  90651. __decorate([
  90652. BABYLON.serialize()
  90653. ], HighlightLayer.prototype, "blurVerticalSize", null);
  90654. __decorate([
  90655. BABYLON.serialize("options")
  90656. ], HighlightLayer.prototype, "_options", void 0);
  90657. return HighlightLayer;
  90658. }(BABYLON.EffectLayer));
  90659. BABYLON.HighlightLayer = HighlightLayer;
  90660. })(BABYLON || (BABYLON = {}));
  90661. //# sourceMappingURL=babylon.highlightLayer.js.map
  90662. "use strict";
  90663. var BABYLON;
  90664. (function (BABYLON) {
  90665. /**
  90666. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  90667. *
  90668. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  90669. * glowy meshes to your scene.
  90670. *
  90671. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  90672. */
  90673. var GlowLayer = /** @class */ (function (_super) {
  90674. __extends(GlowLayer, _super);
  90675. /**
  90676. * Instantiates a new glow Layer and references it to the scene.
  90677. * @param name The name of the layer
  90678. * @param scene The scene to use the layer in
  90679. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  90680. */
  90681. function GlowLayer(name, scene, options) {
  90682. var _this = _super.call(this, name, scene) || this;
  90683. _this._intensity = 1.0;
  90684. _this._includedOnlyMeshes = [];
  90685. _this._excludedMeshes = [];
  90686. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  90687. // Adapt options
  90688. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  90689. // Initialize the layer
  90690. _this._init({
  90691. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  90692. camera: _this._options.camera,
  90693. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  90694. mainTextureRatio: _this._options.mainTextureRatio
  90695. });
  90696. return _this;
  90697. }
  90698. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  90699. /**
  90700. * Gets the kernel size of the blur.
  90701. */
  90702. get: function () {
  90703. return this._horizontalBlurPostprocess1.kernel;
  90704. },
  90705. /**
  90706. * Sets the kernel size of the blur.
  90707. */
  90708. set: function (value) {
  90709. this._horizontalBlurPostprocess1.kernel = value;
  90710. this._verticalBlurPostprocess1.kernel = value;
  90711. this._horizontalBlurPostprocess2.kernel = value;
  90712. this._verticalBlurPostprocess2.kernel = value;
  90713. },
  90714. enumerable: true,
  90715. configurable: true
  90716. });
  90717. Object.defineProperty(GlowLayer.prototype, "intensity", {
  90718. /**
  90719. * Gets the glow intensity.
  90720. */
  90721. get: function () {
  90722. return this._intensity;
  90723. },
  90724. /**
  90725. * Sets the glow intensity.
  90726. */
  90727. set: function (value) {
  90728. this._intensity = value;
  90729. },
  90730. enumerable: true,
  90731. configurable: true
  90732. });
  90733. /**
  90734. * Get the effect name of the layer.
  90735. * @return The effect name
  90736. */
  90737. GlowLayer.prototype.getEffectName = function () {
  90738. return GlowLayer.EffectName;
  90739. };
  90740. /**
  90741. * Create the merge effect. This is the shader use to blit the information back
  90742. * to the main canvas at the end of the scene rendering.
  90743. */
  90744. GlowLayer.prototype._createMergeEffect = function () {
  90745. // Effect
  90746. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  90747. };
  90748. /**
  90749. * Creates the render target textures and post processes used in the glow layer.
  90750. */
  90751. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  90752. var _this = this;
  90753. var blurTextureWidth = this._mainTextureDesiredSize.width;
  90754. var blurTextureHeight = this._mainTextureDesiredSize.height;
  90755. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  90756. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  90757. var textureType = 0;
  90758. if (this._engine.getCaps().textureHalfFloatRender) {
  90759. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90760. }
  90761. else {
  90762. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90763. }
  90764. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  90765. width: blurTextureWidth,
  90766. height: blurTextureHeight
  90767. }, this._scene, false, true, textureType);
  90768. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90769. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90770. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  90771. this._blurTexture1.renderParticles = false;
  90772. this._blurTexture1.ignoreCameraViewport = true;
  90773. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  90774. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  90775. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  90776. width: blurTextureWidth2,
  90777. height: blurTextureHeight2
  90778. }, this._scene, false, true, textureType);
  90779. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90780. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90781. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  90782. this._blurTexture2.renderParticles = false;
  90783. this._blurTexture2.ignoreCameraViewport = true;
  90784. this._textures = [this._blurTexture1, this._blurTexture2];
  90785. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  90786. width: blurTextureWidth,
  90787. height: blurTextureHeight
  90788. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90789. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  90790. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  90791. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  90792. effect.setTexture("textureSampler", _this._mainTexture);
  90793. });
  90794. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  90795. width: blurTextureWidth,
  90796. height: blurTextureHeight
  90797. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90798. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  90799. width: blurTextureWidth2,
  90800. height: blurTextureHeight2
  90801. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90802. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  90803. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  90804. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  90805. effect.setTexture("textureSampler", _this._blurTexture1);
  90806. });
  90807. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  90808. width: blurTextureWidth2,
  90809. height: blurTextureHeight2
  90810. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90811. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  90812. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  90813. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  90814. this._mainTexture.samples = this._options.mainTextureSamples;
  90815. this._mainTexture.onAfterUnbindObservable.add(function () {
  90816. var internalTexture = _this._blurTexture1.getInternalTexture();
  90817. if (internalTexture) {
  90818. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  90819. internalTexture = _this._blurTexture2.getInternalTexture();
  90820. if (internalTexture) {
  90821. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  90822. }
  90823. }
  90824. });
  90825. // Prevent autoClear.
  90826. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  90827. };
  90828. /**
  90829. * Checks for the readiness of the element composing the layer.
  90830. * @param subMesh the mesh to check for
  90831. * @param useInstances specify wether or not to use instances to render the mesh
  90832. * @param emissiveTexture the associated emissive texture used to generate the glow
  90833. * @return true if ready otherwise, false
  90834. */
  90835. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  90836. var material = subMesh.getMaterial();
  90837. var mesh = subMesh.getRenderingMesh();
  90838. if (!material || !mesh) {
  90839. return false;
  90840. }
  90841. var emissiveTexture = material.emissiveTexture;
  90842. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  90843. };
  90844. /**
  90845. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  90846. */
  90847. GlowLayer.prototype.needStencil = function () {
  90848. return false;
  90849. };
  90850. /**
  90851. * Implementation specific of rendering the generating effect on the main canvas.
  90852. * @param effect The effect used to render through
  90853. */
  90854. GlowLayer.prototype._internalRender = function (effect) {
  90855. // Texture
  90856. effect.setTexture("textureSampler", this._blurTexture1);
  90857. effect.setTexture("textureSampler2", this._blurTexture2);
  90858. effect.setFloat("offset", this._intensity);
  90859. // Cache
  90860. var engine = this._engine;
  90861. var previousStencilBuffer = engine.getStencilBuffer();
  90862. // Draw order
  90863. engine.setStencilBuffer(false);
  90864. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  90865. // Draw order
  90866. engine.setStencilBuffer(previousStencilBuffer);
  90867. };
  90868. /**
  90869. * Sets the required values for both the emissive texture and and the main color.
  90870. */
  90871. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  90872. var textureLevel = 1.0;
  90873. if (this.customEmissiveTextureSelector) {
  90874. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  90875. }
  90876. else {
  90877. if (material) {
  90878. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  90879. if (this._emissiveTextureAndColor.texture) {
  90880. textureLevel = this._emissiveTextureAndColor.texture.level;
  90881. }
  90882. }
  90883. else {
  90884. this._emissiveTextureAndColor.texture = null;
  90885. }
  90886. }
  90887. if (this.customEmissiveColorSelector) {
  90888. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  90889. }
  90890. else {
  90891. if (material.emissiveColor) {
  90892. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  90893. }
  90894. else {
  90895. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  90896. }
  90897. }
  90898. };
  90899. /**
  90900. * Returns true if the mesh should render, otherwise false.
  90901. * @param mesh The mesh to render
  90902. * @returns true if it should render otherwise false
  90903. */
  90904. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  90905. return this.hasMesh(mesh);
  90906. };
  90907. /**
  90908. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  90909. * @param mesh The mesh to exclude from the glow layer
  90910. */
  90911. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  90912. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  90913. this._excludedMeshes.push(mesh.uniqueId);
  90914. }
  90915. };
  90916. /**
  90917. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  90918. * @param mesh The mesh to remove
  90919. */
  90920. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  90921. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  90922. if (index !== -1) {
  90923. this._excludedMeshes.splice(index, 1);
  90924. }
  90925. };
  90926. /**
  90927. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  90928. * @param mesh The mesh to include in the glow layer
  90929. */
  90930. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  90931. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  90932. this._includedOnlyMeshes.push(mesh.uniqueId);
  90933. }
  90934. };
  90935. /**
  90936. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  90937. * @param mesh The mesh to remove
  90938. */
  90939. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  90940. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  90941. if (index !== -1) {
  90942. this._includedOnlyMeshes.splice(index, 1);
  90943. }
  90944. };
  90945. /**
  90946. * Determine if a given mesh will be used in the glow layer
  90947. * @param mesh The mesh to test
  90948. * @returns true if the mesh will be highlighted by the current glow layer
  90949. */
  90950. GlowLayer.prototype.hasMesh = function (mesh) {
  90951. // Included Mesh
  90952. if (this._includedOnlyMeshes.length) {
  90953. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  90954. }
  90955. ;
  90956. // Excluded Mesh
  90957. if (this._excludedMeshes.length) {
  90958. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  90959. }
  90960. ;
  90961. return true;
  90962. };
  90963. /**
  90964. * Free any resources and references associated to a mesh.
  90965. * Internal use
  90966. * @param mesh The mesh to free.
  90967. */
  90968. GlowLayer.prototype._disposeMesh = function (mesh) {
  90969. this.removeIncludedOnlyMesh(mesh);
  90970. this.removeExcludedMesh(mesh);
  90971. };
  90972. /**
  90973. * Gets the class name of the effect layer
  90974. * @returns the string with the class name of the effect layer
  90975. */
  90976. GlowLayer.prototype.getClassName = function () {
  90977. return "GlowLayer";
  90978. };
  90979. /**
  90980. * Serializes this glow layer
  90981. * @returns a serialized glow layer object
  90982. */
  90983. GlowLayer.prototype.serialize = function () {
  90984. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90985. serializationObject.customType = "BABYLON.GlowLayer";
  90986. var index;
  90987. // Included meshes
  90988. serializationObject.includedMeshes = [];
  90989. if (this._includedOnlyMeshes.length) {
  90990. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  90991. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  90992. if (mesh) {
  90993. serializationObject.includedMeshes.push(mesh.id);
  90994. }
  90995. }
  90996. }
  90997. // Excluded meshes
  90998. serializationObject.excludedMeshes = [];
  90999. if (this._excludedMeshes.length) {
  91000. for (index = 0; index < this._excludedMeshes.length; index++) {
  91001. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  91002. if (mesh) {
  91003. serializationObject.excludedMeshes.push(mesh.id);
  91004. }
  91005. }
  91006. }
  91007. return serializationObject;
  91008. };
  91009. /**
  91010. * Creates a Glow Layer from parsed glow layer data
  91011. * @param parsedGlowLayer defines glow layer data
  91012. * @param scene defines the current scene
  91013. * @param rootUrl defines the root URL containing the glow layer information
  91014. * @returns a parsed Glow Layer
  91015. */
  91016. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  91017. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  91018. var index;
  91019. // Excluded meshes
  91020. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  91021. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  91022. if (mesh) {
  91023. gl.addExcludedMesh(mesh);
  91024. }
  91025. }
  91026. // Included meshes
  91027. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  91028. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  91029. if (mesh) {
  91030. gl.addIncludedOnlyMesh(mesh);
  91031. }
  91032. }
  91033. return gl;
  91034. };
  91035. /**
  91036. * Effect Name of the layer.
  91037. */
  91038. GlowLayer.EffectName = "GlowLayer";
  91039. /**
  91040. * The default blur kernel size used for the glow.
  91041. */
  91042. GlowLayer.DefaultBlurKernelSize = 32;
  91043. /**
  91044. * The default texture size ratio used for the glow.
  91045. */
  91046. GlowLayer.DefaultTextureRatio = 0.5;
  91047. __decorate([
  91048. BABYLON.serialize()
  91049. ], GlowLayer.prototype, "blurKernelSize", null);
  91050. __decorate([
  91051. BABYLON.serialize()
  91052. ], GlowLayer.prototype, "intensity", null);
  91053. __decorate([
  91054. BABYLON.serialize("options")
  91055. ], GlowLayer.prototype, "_options", void 0);
  91056. return GlowLayer;
  91057. }(BABYLON.EffectLayer));
  91058. BABYLON.GlowLayer = GlowLayer;
  91059. })(BABYLON || (BABYLON = {}));
  91060. //# sourceMappingURL=babylon.glowLayer.js.map
  91061. "use strict";
  91062. var BABYLON;
  91063. (function (BABYLON) {
  91064. /**
  91065. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  91066. */
  91067. var AssetTaskState;
  91068. (function (AssetTaskState) {
  91069. /**
  91070. * Initialization
  91071. */
  91072. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  91073. /**
  91074. * Running
  91075. */
  91076. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  91077. /**
  91078. * Done
  91079. */
  91080. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  91081. /**
  91082. * Error
  91083. */
  91084. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  91085. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  91086. /**
  91087. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  91088. */
  91089. var AbstractAssetTask = /** @class */ (function () {
  91090. /**
  91091. * Creates a new {BABYLON.AssetsManager}
  91092. * @param name defines the name of the task
  91093. */
  91094. function AbstractAssetTask(
  91095. /**
  91096. * Task name
  91097. */ name) {
  91098. this.name = name;
  91099. this._isCompleted = false;
  91100. this._taskState = AssetTaskState.INIT;
  91101. }
  91102. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  91103. /**
  91104. * Get if the task is completed
  91105. */
  91106. get: function () {
  91107. return this._isCompleted;
  91108. },
  91109. enumerable: true,
  91110. configurable: true
  91111. });
  91112. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  91113. /**
  91114. * Gets the current state of the task
  91115. */
  91116. get: function () {
  91117. return this._taskState;
  91118. },
  91119. enumerable: true,
  91120. configurable: true
  91121. });
  91122. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  91123. /**
  91124. * Gets the current error object (if task is in error)
  91125. */
  91126. get: function () {
  91127. return this._errorObject;
  91128. },
  91129. enumerable: true,
  91130. configurable: true
  91131. });
  91132. /**
  91133. * Internal only
  91134. * @ignore
  91135. */
  91136. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  91137. if (this._errorObject) {
  91138. return;
  91139. }
  91140. this._errorObject = {
  91141. message: message,
  91142. exception: exception
  91143. };
  91144. };
  91145. /**
  91146. * Execute the current task
  91147. * @param scene defines the scene where you want your assets to be loaded
  91148. * @param onSuccess is a callback called when the task is successfully executed
  91149. * @param onError is a callback called if an error occurs
  91150. */
  91151. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  91152. var _this = this;
  91153. this._taskState = AssetTaskState.RUNNING;
  91154. this.runTask(scene, function () {
  91155. _this.onDoneCallback(onSuccess, onError);
  91156. }, function (msg, exception) {
  91157. _this.onErrorCallback(onError, msg, exception);
  91158. });
  91159. };
  91160. /**
  91161. * Execute the current task
  91162. * @param scene defines the scene where you want your assets to be loaded
  91163. * @param onSuccess is a callback called when the task is successfully executed
  91164. * @param onError is a callback called if an error occurs
  91165. */
  91166. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91167. throw new Error("runTask is not implemented");
  91168. };
  91169. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  91170. this._taskState = AssetTaskState.ERROR;
  91171. this._errorObject = {
  91172. message: message,
  91173. exception: exception
  91174. };
  91175. if (this.onError) {
  91176. this.onError(this, message, exception);
  91177. }
  91178. onError();
  91179. };
  91180. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  91181. try {
  91182. this._taskState = AssetTaskState.DONE;
  91183. this._isCompleted = true;
  91184. if (this.onSuccess) {
  91185. this.onSuccess(this);
  91186. }
  91187. onSuccess();
  91188. }
  91189. catch (e) {
  91190. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  91191. }
  91192. };
  91193. return AbstractAssetTask;
  91194. }());
  91195. BABYLON.AbstractAssetTask = AbstractAssetTask;
  91196. /**
  91197. * Class used to share progress information about assets loading
  91198. */
  91199. var AssetsProgressEvent = /** @class */ (function () {
  91200. /**
  91201. * Creates a {BABYLON.AssetsProgressEvent}
  91202. * @param remainingCount defines the number of remaining tasks to process
  91203. * @param totalCount defines the total number of tasks
  91204. * @param task defines the task that was just processed
  91205. */
  91206. function AssetsProgressEvent(remainingCount, totalCount, task) {
  91207. this.remainingCount = remainingCount;
  91208. this.totalCount = totalCount;
  91209. this.task = task;
  91210. }
  91211. return AssetsProgressEvent;
  91212. }());
  91213. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  91214. /**
  91215. * Define a task used by {BABYLON.AssetsManager} to load meshes
  91216. */
  91217. var MeshAssetTask = /** @class */ (function (_super) {
  91218. __extends(MeshAssetTask, _super);
  91219. /**
  91220. * Creates a new {BABYLON.MeshAssetTask}
  91221. * @param name defines the name of the task
  91222. * @param meshesNames defines the list of mesh's names you want to load
  91223. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  91224. * @param sceneFilename defines the filename of the scene to load from
  91225. */
  91226. function MeshAssetTask(
  91227. /**
  91228. * Defines the name of the task
  91229. */
  91230. name,
  91231. /**
  91232. * Defines the list of mesh's names you want to load
  91233. */
  91234. meshesNames,
  91235. /**
  91236. * Defines the root url to use as a base to load your meshes and associated resources
  91237. */
  91238. rootUrl,
  91239. /**
  91240. * Defines the filename of the scene to load from
  91241. */
  91242. sceneFilename) {
  91243. var _this = _super.call(this, name) || this;
  91244. _this.name = name;
  91245. _this.meshesNames = meshesNames;
  91246. _this.rootUrl = rootUrl;
  91247. _this.sceneFilename = sceneFilename;
  91248. return _this;
  91249. }
  91250. /**
  91251. * Execute the current task
  91252. * @param scene defines the scene where you want your assets to be loaded
  91253. * @param onSuccess is a callback called when the task is successfully executed
  91254. * @param onError is a callback called if an error occurs
  91255. */
  91256. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91257. var _this = this;
  91258. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  91259. _this.loadedMeshes = meshes;
  91260. _this.loadedParticleSystems = particleSystems;
  91261. _this.loadedSkeletons = skeletons;
  91262. onSuccess();
  91263. }, null, function (scene, message, exception) {
  91264. onError(message, exception);
  91265. });
  91266. };
  91267. return MeshAssetTask;
  91268. }(AbstractAssetTask));
  91269. BABYLON.MeshAssetTask = MeshAssetTask;
  91270. /**
  91271. * Define a task used by {BABYLON.AssetsManager} to load text content
  91272. */
  91273. var TextFileAssetTask = /** @class */ (function (_super) {
  91274. __extends(TextFileAssetTask, _super);
  91275. /**
  91276. * Creates a new TextFileAssetTask object
  91277. * @param name defines the name of the task
  91278. * @param url defines the location of the file to load
  91279. */
  91280. function TextFileAssetTask(
  91281. /**
  91282. * Defines the name of the task
  91283. */
  91284. name,
  91285. /**
  91286. * Defines the location of the file to load
  91287. */
  91288. url) {
  91289. var _this = _super.call(this, name) || this;
  91290. _this.name = name;
  91291. _this.url = url;
  91292. return _this;
  91293. }
  91294. /**
  91295. * Execute the current task
  91296. * @param scene defines the scene where you want your assets to be loaded
  91297. * @param onSuccess is a callback called when the task is successfully executed
  91298. * @param onError is a callback called if an error occurs
  91299. */
  91300. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91301. var _this = this;
  91302. scene._loadFile(this.url, function (data) {
  91303. _this.text = data;
  91304. onSuccess();
  91305. }, undefined, false, false, function (request, exception) {
  91306. if (request) {
  91307. onError(request.status + " " + request.statusText, exception);
  91308. }
  91309. });
  91310. };
  91311. return TextFileAssetTask;
  91312. }(AbstractAssetTask));
  91313. BABYLON.TextFileAssetTask = TextFileAssetTask;
  91314. /**
  91315. * Define a task used by {BABYLON.AssetsManager} to load binary data
  91316. */
  91317. var BinaryFileAssetTask = /** @class */ (function (_super) {
  91318. __extends(BinaryFileAssetTask, _super);
  91319. /**
  91320. * Creates a new BinaryFileAssetTask object
  91321. * @param name defines the name of the new task
  91322. * @param url defines the location of the file to load
  91323. */
  91324. function BinaryFileAssetTask(
  91325. /**
  91326. * Defines the name of the task
  91327. */
  91328. name,
  91329. /**
  91330. * Defines the location of the file to load
  91331. */
  91332. url) {
  91333. var _this = _super.call(this, name) || this;
  91334. _this.name = name;
  91335. _this.url = url;
  91336. return _this;
  91337. }
  91338. /**
  91339. * Execute the current task
  91340. * @param scene defines the scene where you want your assets to be loaded
  91341. * @param onSuccess is a callback called when the task is successfully executed
  91342. * @param onError is a callback called if an error occurs
  91343. */
  91344. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91345. var _this = this;
  91346. scene._loadFile(this.url, function (data) {
  91347. _this.data = data;
  91348. onSuccess();
  91349. }, undefined, true, true, function (request, exception) {
  91350. if (request) {
  91351. onError(request.status + " " + request.statusText, exception);
  91352. }
  91353. });
  91354. };
  91355. return BinaryFileAssetTask;
  91356. }(AbstractAssetTask));
  91357. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  91358. /**
  91359. * Define a task used by {BABYLON.AssetsManager} to load images
  91360. */
  91361. var ImageAssetTask = /** @class */ (function (_super) {
  91362. __extends(ImageAssetTask, _super);
  91363. /**
  91364. * Creates a new ImageAssetTask
  91365. * @param name defines the name of the task
  91366. * @param url defines the location of the image to load
  91367. */
  91368. function ImageAssetTask(
  91369. /**
  91370. * Defines the name of the task
  91371. */
  91372. name,
  91373. /**
  91374. * Defines the location of the image to load
  91375. */
  91376. url) {
  91377. var _this = _super.call(this, name) || this;
  91378. _this.name = name;
  91379. _this.url = url;
  91380. return _this;
  91381. }
  91382. /**
  91383. * Execute the current task
  91384. * @param scene defines the scene where you want your assets to be loaded
  91385. * @param onSuccess is a callback called when the task is successfully executed
  91386. * @param onError is a callback called if an error occurs
  91387. */
  91388. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91389. var _this = this;
  91390. var img = new Image();
  91391. BABYLON.Tools.SetCorsBehavior(this.url, img);
  91392. img.onload = function () {
  91393. _this.image = img;
  91394. onSuccess();
  91395. };
  91396. img.onerror = function (err) {
  91397. onError("Error loading image", err);
  91398. };
  91399. img.src = this.url;
  91400. };
  91401. return ImageAssetTask;
  91402. }(AbstractAssetTask));
  91403. BABYLON.ImageAssetTask = ImageAssetTask;
  91404. /**
  91405. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  91406. */
  91407. var TextureAssetTask = /** @class */ (function (_super) {
  91408. __extends(TextureAssetTask, _super);
  91409. /**
  91410. * Creates a new TextureAssetTask object
  91411. * @param name defines the name of the task
  91412. * @param url defines the location of the file to load
  91413. * @param noMipmap defines if mipmap should not be generated (default is false)
  91414. * @param invertY defines if texture must be inverted on Y axis (default is false)
  91415. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  91416. */
  91417. function TextureAssetTask(
  91418. /**
  91419. * Defines the name of the task
  91420. */
  91421. name,
  91422. /**
  91423. * Defines the location of the file to load
  91424. */
  91425. url,
  91426. /**
  91427. * Defines if mipmap should not be generated (default is false)
  91428. */
  91429. noMipmap,
  91430. /**
  91431. * Defines if texture must be inverted on Y axis (default is false)
  91432. */
  91433. invertY,
  91434. /**
  91435. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  91436. */
  91437. samplingMode) {
  91438. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  91439. var _this = _super.call(this, name) || this;
  91440. _this.name = name;
  91441. _this.url = url;
  91442. _this.noMipmap = noMipmap;
  91443. _this.invertY = invertY;
  91444. _this.samplingMode = samplingMode;
  91445. return _this;
  91446. }
  91447. /**
  91448. * Execute the current task
  91449. * @param scene defines the scene where you want your assets to be loaded
  91450. * @param onSuccess is a callback called when the task is successfully executed
  91451. * @param onError is a callback called if an error occurs
  91452. */
  91453. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91454. var onload = function () {
  91455. onSuccess();
  91456. };
  91457. var onerror = function (message, exception) {
  91458. onError(message, exception);
  91459. };
  91460. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  91461. };
  91462. return TextureAssetTask;
  91463. }(AbstractAssetTask));
  91464. BABYLON.TextureAssetTask = TextureAssetTask;
  91465. /**
  91466. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  91467. */
  91468. var CubeTextureAssetTask = /** @class */ (function (_super) {
  91469. __extends(CubeTextureAssetTask, _super);
  91470. /**
  91471. * Creates a new CubeTextureAssetTask
  91472. * @param name defines the name of the task
  91473. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  91474. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  91475. * @param noMipmap defines if mipmaps should not be generated (default is false)
  91476. * @param files defines the explicit list of files (undefined by default)
  91477. */
  91478. function CubeTextureAssetTask(
  91479. /**
  91480. * Defines the name of the task
  91481. */
  91482. name,
  91483. /**
  91484. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  91485. */
  91486. url,
  91487. /**
  91488. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  91489. */
  91490. extensions,
  91491. /**
  91492. * Defines if mipmaps should not be generated (default is false)
  91493. */
  91494. noMipmap,
  91495. /**
  91496. * Defines the explicit list of files (undefined by default)
  91497. */
  91498. files) {
  91499. var _this = _super.call(this, name) || this;
  91500. _this.name = name;
  91501. _this.url = url;
  91502. _this.extensions = extensions;
  91503. _this.noMipmap = noMipmap;
  91504. _this.files = files;
  91505. return _this;
  91506. }
  91507. /**
  91508. * Execute the current task
  91509. * @param scene defines the scene where you want your assets to be loaded
  91510. * @param onSuccess is a callback called when the task is successfully executed
  91511. * @param onError is a callback called if an error occurs
  91512. */
  91513. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91514. var onload = function () {
  91515. onSuccess();
  91516. };
  91517. var onerror = function (message, exception) {
  91518. onError(message, exception);
  91519. };
  91520. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  91521. };
  91522. return CubeTextureAssetTask;
  91523. }(AbstractAssetTask));
  91524. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  91525. /**
  91526. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  91527. */
  91528. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  91529. __extends(HDRCubeTextureAssetTask, _super);
  91530. /**
  91531. * Creates a new HDRCubeTextureAssetTask object
  91532. * @param name defines the name of the task
  91533. * @param url defines the location of the file to load
  91534. * @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.
  91535. * @param noMipmap defines if mipmaps should not be generated (default is false)
  91536. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  91537. * @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)
  91538. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  91539. */
  91540. function HDRCubeTextureAssetTask(
  91541. /**
  91542. * Defines the name of the task
  91543. */
  91544. name,
  91545. /**
  91546. * Defines the location of the file to load
  91547. */
  91548. url,
  91549. /**
  91550. * 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.
  91551. */
  91552. size,
  91553. /**
  91554. * Defines if mipmaps should not be generated (default is false)
  91555. */
  91556. noMipmap,
  91557. /**
  91558. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  91559. */
  91560. generateHarmonics,
  91561. /**
  91562. * 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)
  91563. */
  91564. useInGammaSpace,
  91565. /**
  91566. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  91567. */
  91568. usePMREMGenerator) {
  91569. if (noMipmap === void 0) { noMipmap = false; }
  91570. if (generateHarmonics === void 0) { generateHarmonics = true; }
  91571. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  91572. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  91573. var _this = _super.call(this, name) || this;
  91574. _this.name = name;
  91575. _this.url = url;
  91576. _this.size = size;
  91577. _this.noMipmap = noMipmap;
  91578. _this.generateHarmonics = generateHarmonics;
  91579. _this.useInGammaSpace = useInGammaSpace;
  91580. _this.usePMREMGenerator = usePMREMGenerator;
  91581. return _this;
  91582. }
  91583. /**
  91584. * Execute the current task
  91585. * @param scene defines the scene where you want your assets to be loaded
  91586. * @param onSuccess is a callback called when the task is successfully executed
  91587. * @param onError is a callback called if an error occurs
  91588. */
  91589. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  91590. var onload = function () {
  91591. onSuccess();
  91592. };
  91593. var onerror = function (message, exception) {
  91594. onError(message, exception);
  91595. };
  91596. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  91597. };
  91598. return HDRCubeTextureAssetTask;
  91599. }(AbstractAssetTask));
  91600. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  91601. /**
  91602. * This class can be used to easily import assets into a scene
  91603. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  91604. */
  91605. var AssetsManager = /** @class */ (function () {
  91606. /**
  91607. * Creates a new AssetsManager
  91608. * @param scene defines the scene to work on
  91609. */
  91610. function AssetsManager(scene) {
  91611. this._isLoading = false;
  91612. this._tasks = new Array();
  91613. this._waitingTasksCount = 0;
  91614. this._totalTasksCount = 0;
  91615. /**
  91616. * Observable called when all tasks are processed
  91617. */
  91618. this.onTaskSuccessObservable = new BABYLON.Observable();
  91619. /**
  91620. * Observable called when a task had an error
  91621. */
  91622. this.onTaskErrorObservable = new BABYLON.Observable();
  91623. /**
  91624. * Observable called when a task is successful
  91625. */
  91626. this.onTasksDoneObservable = new BABYLON.Observable();
  91627. /**
  91628. * Observable called when a task is done (whatever the result is)
  91629. */
  91630. this.onProgressObservable = new BABYLON.Observable();
  91631. /**
  91632. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  91633. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  91634. */
  91635. this.useDefaultLoadingScreen = true;
  91636. this._scene = scene;
  91637. }
  91638. /**
  91639. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  91640. * @param taskName defines the name of the new task
  91641. * @param meshesNames defines the name of meshes to load
  91642. * @param rootUrl defines the root url to use to locate files
  91643. * @param sceneFilename defines the filename of the scene file
  91644. * @returns a new {BABYLON.MeshAssetTask} object
  91645. */
  91646. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  91647. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  91648. this._tasks.push(task);
  91649. return task;
  91650. };
  91651. /**
  91652. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  91653. * @param taskName defines the name of the new task
  91654. * @param url defines the url of the file to load
  91655. * @returns a new {BABYLON.TextFileAssetTask} object
  91656. */
  91657. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  91658. var task = new TextFileAssetTask(taskName, url);
  91659. this._tasks.push(task);
  91660. return task;
  91661. };
  91662. /**
  91663. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  91664. * @param taskName defines the name of the new task
  91665. * @param url defines the url of the file to load
  91666. * @returns a new {BABYLON.BinaryFileAssetTask} object
  91667. */
  91668. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  91669. var task = new BinaryFileAssetTask(taskName, url);
  91670. this._tasks.push(task);
  91671. return task;
  91672. };
  91673. /**
  91674. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  91675. * @param taskName defines the name of the new task
  91676. * @param url defines the url of the file to load
  91677. * @returns a new {BABYLON.ImageAssetTask} object
  91678. */
  91679. AssetsManager.prototype.addImageTask = function (taskName, url) {
  91680. var task = new ImageAssetTask(taskName, url);
  91681. this._tasks.push(task);
  91682. return task;
  91683. };
  91684. /**
  91685. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  91686. * @param taskName defines the name of the new task
  91687. * @param url defines the url of the file to load
  91688. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  91689. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  91690. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  91691. * @returns a new {BABYLON.TextureAssetTask} object
  91692. */
  91693. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  91694. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  91695. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  91696. this._tasks.push(task);
  91697. return task;
  91698. };
  91699. /**
  91700. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  91701. * @param taskName defines the name of the new task
  91702. * @param url defines the url of the file to load
  91703. * @param extensions defines the extension to use to load the cube map (can be null)
  91704. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  91705. * @param files defines the list of files to load (can be null)
  91706. * @returns a new {BABYLON.CubeTextureAssetTask} object
  91707. */
  91708. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  91709. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  91710. this._tasks.push(task);
  91711. return task;
  91712. };
  91713. /**
  91714. *
  91715. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  91716. * @param taskName defines the name of the new task
  91717. * @param url defines the url of the file to load
  91718. * @param size defines the size you want for the cubemap (can be null)
  91719. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  91720. * @param generateHarmonics defines if you want to automatically generate (true by default)
  91721. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  91722. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  91723. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  91724. */
  91725. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  91726. if (noMipmap === void 0) { noMipmap = false; }
  91727. if (generateHarmonics === void 0) { generateHarmonics = true; }
  91728. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  91729. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  91730. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  91731. this._tasks.push(task);
  91732. return task;
  91733. };
  91734. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  91735. var _this = this;
  91736. this._waitingTasksCount--;
  91737. try {
  91738. if (task.taskState === AssetTaskState.DONE) {
  91739. // Let's remove successfull tasks
  91740. BABYLON.Tools.SetImmediate(function () {
  91741. var index = _this._tasks.indexOf(task);
  91742. if (index > -1) {
  91743. _this._tasks.splice(index, 1);
  91744. }
  91745. });
  91746. }
  91747. if (this.onProgress) {
  91748. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  91749. }
  91750. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  91751. }
  91752. catch (e) {
  91753. BABYLON.Tools.Error("Error running progress callbacks.");
  91754. console.log(e);
  91755. }
  91756. if (this._waitingTasksCount === 0) {
  91757. try {
  91758. if (this.onFinish) {
  91759. this.onFinish(this._tasks);
  91760. }
  91761. this.onTasksDoneObservable.notifyObservers(this._tasks);
  91762. }
  91763. catch (e) {
  91764. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  91765. console.log(e);
  91766. }
  91767. this._isLoading = false;
  91768. this._scene.getEngine().hideLoadingUI();
  91769. }
  91770. };
  91771. AssetsManager.prototype._runTask = function (task) {
  91772. var _this = this;
  91773. var done = function () {
  91774. try {
  91775. if (_this.onTaskSuccess) {
  91776. _this.onTaskSuccess(task);
  91777. }
  91778. _this.onTaskSuccessObservable.notifyObservers(task);
  91779. _this._decreaseWaitingTasksCount(task);
  91780. }
  91781. catch (e) {
  91782. error("Error executing task success callbacks", e);
  91783. }
  91784. };
  91785. var error = function (message, exception) {
  91786. task._setErrorObject(message, exception);
  91787. if (_this.onTaskError) {
  91788. _this.onTaskError(task);
  91789. }
  91790. _this.onTaskErrorObservable.notifyObservers(task);
  91791. _this._decreaseWaitingTasksCount(task);
  91792. };
  91793. task.run(this._scene, done, error);
  91794. };
  91795. /**
  91796. * Reset the {BABYLON.AssetsManager} and remove all tasks
  91797. * @return the current instance of the {BABYLON.AssetsManager}
  91798. */
  91799. AssetsManager.prototype.reset = function () {
  91800. this._isLoading = false;
  91801. this._tasks = new Array();
  91802. return this;
  91803. };
  91804. /**
  91805. * Start the loading process
  91806. * @return the current instance of the {BABYLON.AssetsManager}
  91807. */
  91808. AssetsManager.prototype.load = function () {
  91809. if (this._isLoading) {
  91810. return this;
  91811. }
  91812. this._isLoading = true;
  91813. this._waitingTasksCount = this._tasks.length;
  91814. this._totalTasksCount = this._tasks.length;
  91815. if (this._waitingTasksCount === 0) {
  91816. this._isLoading = false;
  91817. if (this.onFinish) {
  91818. this.onFinish(this._tasks);
  91819. }
  91820. this.onTasksDoneObservable.notifyObservers(this._tasks);
  91821. return this;
  91822. }
  91823. if (this.useDefaultLoadingScreen) {
  91824. this._scene.getEngine().displayLoadingUI();
  91825. }
  91826. for (var index = 0; index < this._tasks.length; index++) {
  91827. var task = this._tasks[index];
  91828. this._runTask(task);
  91829. }
  91830. return this;
  91831. };
  91832. return AssetsManager;
  91833. }());
  91834. BABYLON.AssetsManager = AssetsManager;
  91835. })(BABYLON || (BABYLON = {}));
  91836. //# sourceMappingURL=babylon.assetsManager.js.map
  91837. "use strict";
  91838. var BABYLON;
  91839. (function (BABYLON) {
  91840. var serializedGeometries = [];
  91841. var serializeGeometry = function (geometry, serializationGeometries) {
  91842. if (serializedGeometries[geometry.id]) {
  91843. return;
  91844. }
  91845. if (geometry.doNotSerialize) {
  91846. return;
  91847. }
  91848. if (geometry instanceof BABYLON.BoxGeometry) {
  91849. serializationGeometries.boxes.push(geometry.serialize());
  91850. }
  91851. else if (geometry instanceof BABYLON.SphereGeometry) {
  91852. serializationGeometries.spheres.push(geometry.serialize());
  91853. }
  91854. else if (geometry instanceof BABYLON.CylinderGeometry) {
  91855. serializationGeometries.cylinders.push(geometry.serialize());
  91856. }
  91857. else if (geometry instanceof BABYLON.TorusGeometry) {
  91858. serializationGeometries.toruses.push(geometry.serialize());
  91859. }
  91860. else if (geometry instanceof BABYLON.GroundGeometry) {
  91861. serializationGeometries.grounds.push(geometry.serialize());
  91862. }
  91863. else if (geometry instanceof BABYLON.Plane) {
  91864. serializationGeometries.planes.push(geometry.serialize());
  91865. }
  91866. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  91867. serializationGeometries.torusKnots.push(geometry.serialize());
  91868. }
  91869. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  91870. throw new Error("Unknown primitive type");
  91871. }
  91872. else {
  91873. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  91874. }
  91875. serializedGeometries[geometry.id] = true;
  91876. };
  91877. var serializeMesh = function (mesh, serializationScene) {
  91878. var serializationObject = {};
  91879. // Geometry
  91880. var geometry = mesh._geometry;
  91881. if (geometry) {
  91882. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  91883. // 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
  91884. serializeGeometry(geometry, serializationScene.geometries);
  91885. }
  91886. }
  91887. // Custom
  91888. if (mesh.serialize) {
  91889. mesh.serialize(serializationObject);
  91890. }
  91891. return serializationObject;
  91892. };
  91893. var finalizeSingleMesh = function (mesh, serializationObject) {
  91894. //only works if the mesh is already loaded
  91895. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  91896. //serialize material
  91897. if (mesh.material) {
  91898. if (mesh.material instanceof BABYLON.StandardMaterial) {
  91899. serializationObject.materials = serializationObject.materials || [];
  91900. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  91901. serializationObject.materials.push(mesh.material.serialize());
  91902. }
  91903. }
  91904. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  91905. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  91906. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  91907. serializationObject.multiMaterials.push(mesh.material.serialize());
  91908. }
  91909. }
  91910. }
  91911. //serialize geometry
  91912. var geometry = mesh._geometry;
  91913. if (geometry) {
  91914. if (!serializationObject.geometries) {
  91915. serializationObject.geometries = {};
  91916. serializationObject.geometries.boxes = [];
  91917. serializationObject.geometries.spheres = [];
  91918. serializationObject.geometries.cylinders = [];
  91919. serializationObject.geometries.toruses = [];
  91920. serializationObject.geometries.grounds = [];
  91921. serializationObject.geometries.planes = [];
  91922. serializationObject.geometries.torusKnots = [];
  91923. serializationObject.geometries.vertexData = [];
  91924. }
  91925. serializeGeometry(geometry, serializationObject.geometries);
  91926. }
  91927. // Skeletons
  91928. if (mesh.skeleton) {
  91929. serializationObject.skeletons = serializationObject.skeletons || [];
  91930. serializationObject.skeletons.push(mesh.skeleton.serialize());
  91931. }
  91932. //serialize the actual mesh
  91933. serializationObject.meshes = serializationObject.meshes || [];
  91934. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  91935. }
  91936. };
  91937. var SceneSerializer = /** @class */ (function () {
  91938. function SceneSerializer() {
  91939. }
  91940. SceneSerializer.ClearCache = function () {
  91941. serializedGeometries = [];
  91942. };
  91943. SceneSerializer.Serialize = function (scene) {
  91944. var serializationObject = {};
  91945. SceneSerializer.ClearCache();
  91946. // Scene
  91947. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  91948. serializationObject.autoClear = scene.autoClear;
  91949. serializationObject.clearColor = scene.clearColor.asArray();
  91950. serializationObject.ambientColor = scene.ambientColor.asArray();
  91951. serializationObject.gravity = scene.gravity.asArray();
  91952. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  91953. serializationObject.workerCollisions = scene.workerCollisions;
  91954. // Fog
  91955. if (scene.fogMode && scene.fogMode !== 0) {
  91956. serializationObject.fogMode = scene.fogMode;
  91957. serializationObject.fogColor = scene.fogColor.asArray();
  91958. serializationObject.fogStart = scene.fogStart;
  91959. serializationObject.fogEnd = scene.fogEnd;
  91960. serializationObject.fogDensity = scene.fogDensity;
  91961. }
  91962. //Physics
  91963. if (scene.isPhysicsEnabled()) {
  91964. var physicEngine = scene.getPhysicsEngine();
  91965. if (physicEngine) {
  91966. serializationObject.physicsEnabled = true;
  91967. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  91968. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  91969. }
  91970. }
  91971. // Metadata
  91972. if (scene.metadata) {
  91973. serializationObject.metadata = scene.metadata;
  91974. }
  91975. // Morph targets
  91976. serializationObject.morphTargetManagers = [];
  91977. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  91978. var abstractMesh = _a[_i];
  91979. var manager = abstractMesh.morphTargetManager;
  91980. if (manager) {
  91981. serializationObject.morphTargetManagers.push(manager.serialize());
  91982. }
  91983. }
  91984. // Lights
  91985. serializationObject.lights = [];
  91986. var index;
  91987. var light;
  91988. for (index = 0; index < scene.lights.length; index++) {
  91989. light = scene.lights[index];
  91990. if (!light.doNotSerialize) {
  91991. serializationObject.lights.push(light.serialize());
  91992. }
  91993. }
  91994. // Cameras
  91995. serializationObject.cameras = [];
  91996. for (index = 0; index < scene.cameras.length; index++) {
  91997. var camera = scene.cameras[index];
  91998. if (!camera.doNotSerialize) {
  91999. serializationObject.cameras.push(camera.serialize());
  92000. }
  92001. }
  92002. if (scene.activeCamera) {
  92003. serializationObject.activeCameraID = scene.activeCamera.id;
  92004. }
  92005. // Animations
  92006. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  92007. // Materials
  92008. serializationObject.materials = [];
  92009. serializationObject.multiMaterials = [];
  92010. var material;
  92011. for (index = 0; index < scene.materials.length; index++) {
  92012. material = scene.materials[index];
  92013. if (!material.doNotSerialize) {
  92014. serializationObject.materials.push(material.serialize());
  92015. }
  92016. }
  92017. // MultiMaterials
  92018. serializationObject.multiMaterials = [];
  92019. for (index = 0; index < scene.multiMaterials.length; index++) {
  92020. var multiMaterial = scene.multiMaterials[index];
  92021. serializationObject.multiMaterials.push(multiMaterial.serialize());
  92022. }
  92023. // Environment texture
  92024. if (scene.environmentTexture) {
  92025. serializationObject.environmentTexture = scene.environmentTexture.name;
  92026. }
  92027. // Skeletons
  92028. serializationObject.skeletons = [];
  92029. for (index = 0; index < scene.skeletons.length; index++) {
  92030. var skeleton = scene.skeletons[index];
  92031. if (!skeleton.doNotSerialize) {
  92032. serializationObject.skeletons.push(skeleton.serialize());
  92033. }
  92034. }
  92035. // Transform nodes
  92036. serializationObject.transformNodes = [];
  92037. for (index = 0; index < scene.transformNodes.length; index++) {
  92038. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  92039. }
  92040. // Geometries
  92041. serializationObject.geometries = {};
  92042. serializationObject.geometries.boxes = [];
  92043. serializationObject.geometries.spheres = [];
  92044. serializationObject.geometries.cylinders = [];
  92045. serializationObject.geometries.toruses = [];
  92046. serializationObject.geometries.grounds = [];
  92047. serializationObject.geometries.planes = [];
  92048. serializationObject.geometries.torusKnots = [];
  92049. serializationObject.geometries.vertexData = [];
  92050. serializedGeometries = [];
  92051. var geometries = scene.getGeometries();
  92052. for (index = 0; index < geometries.length; index++) {
  92053. var geometry = geometries[index];
  92054. if (geometry.isReady()) {
  92055. serializeGeometry(geometry, serializationObject.geometries);
  92056. }
  92057. }
  92058. // Meshes
  92059. serializationObject.meshes = [];
  92060. for (index = 0; index < scene.meshes.length; index++) {
  92061. var abstractMesh = scene.meshes[index];
  92062. if (abstractMesh instanceof BABYLON.Mesh) {
  92063. var mesh = abstractMesh;
  92064. if (!mesh.doNotSerialize) {
  92065. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  92066. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  92067. }
  92068. }
  92069. }
  92070. }
  92071. // Particles Systems
  92072. serializationObject.particleSystems = [];
  92073. for (index = 0; index < scene.particleSystems.length; index++) {
  92074. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  92075. }
  92076. // Lens flares
  92077. serializationObject.lensFlareSystems = [];
  92078. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  92079. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  92080. }
  92081. // Shadows
  92082. serializationObject.shadowGenerators = [];
  92083. for (index = 0; index < scene.lights.length; index++) {
  92084. light = scene.lights[index];
  92085. var shadowGenerator = light.getShadowGenerator();
  92086. if (shadowGenerator) {
  92087. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  92088. }
  92089. }
  92090. // Action Manager
  92091. if (scene.actionManager) {
  92092. serializationObject.actions = scene.actionManager.serialize("scene");
  92093. }
  92094. // Audio
  92095. serializationObject.sounds = [];
  92096. for (index = 0; index < scene.soundTracks.length; index++) {
  92097. var soundtrack = scene.soundTracks[index];
  92098. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  92099. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  92100. }
  92101. }
  92102. // Effect layers
  92103. serializationObject.effectLayers = [];
  92104. for (index = 0; index < scene.effectLayers.length; index++) {
  92105. var layer = scene.effectLayers[index];
  92106. if (layer.serialize) {
  92107. serializationObject.effectLayers.push(layer.serialize());
  92108. }
  92109. }
  92110. return serializationObject;
  92111. };
  92112. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  92113. if (withParents === void 0) { withParents = false; }
  92114. if (withChildren === void 0) { withChildren = false; }
  92115. var serializationObject = {};
  92116. SceneSerializer.ClearCache();
  92117. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  92118. if (withParents || withChildren) {
  92119. //deliberate for loop! not for each, appended should be processed as well.
  92120. for (var i = 0; i < toSerialize.length; ++i) {
  92121. if (withChildren) {
  92122. toSerialize[i].getDescendants().forEach(function (node) {
  92123. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  92124. toSerialize.push(node);
  92125. }
  92126. });
  92127. }
  92128. //make sure the array doesn't contain the object already
  92129. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  92130. toSerialize.push(toSerialize[i].parent);
  92131. }
  92132. }
  92133. }
  92134. toSerialize.forEach(function (mesh) {
  92135. finalizeSingleMesh(mesh, serializationObject);
  92136. });
  92137. return serializationObject;
  92138. };
  92139. return SceneSerializer;
  92140. }());
  92141. BABYLON.SceneSerializer = SceneSerializer;
  92142. })(BABYLON || (BABYLON = {}));
  92143. //# sourceMappingURL=babylon.sceneSerializer.js.map
  92144. "use strict";
  92145. var BABYLON;
  92146. (function (BABYLON) {
  92147. var ReflectionProbe = /** @class */ (function () {
  92148. function ReflectionProbe(name, size, scene, generateMipMaps) {
  92149. if (generateMipMaps === void 0) { generateMipMaps = true; }
  92150. var _this = this;
  92151. this.name = name;
  92152. this._viewMatrix = BABYLON.Matrix.Identity();
  92153. this._target = BABYLON.Vector3.Zero();
  92154. this._add = BABYLON.Vector3.Zero();
  92155. this._invertYAxis = false;
  92156. this.position = BABYLON.Vector3.Zero();
  92157. this._scene = scene;
  92158. this._scene.reflectionProbes.push(this);
  92159. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  92160. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  92161. switch (faceIndex) {
  92162. case 0:
  92163. _this._add.copyFromFloats(1, 0, 0);
  92164. break;
  92165. case 1:
  92166. _this._add.copyFromFloats(-1, 0, 0);
  92167. break;
  92168. case 2:
  92169. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  92170. break;
  92171. case 3:
  92172. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  92173. break;
  92174. case 4:
  92175. _this._add.copyFromFloats(0, 0, 1);
  92176. break;
  92177. case 5:
  92178. _this._add.copyFromFloats(0, 0, -1);
  92179. break;
  92180. }
  92181. if (_this._attachedMesh) {
  92182. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  92183. }
  92184. _this.position.addToRef(_this._add, _this._target);
  92185. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  92186. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  92187. scene._forcedViewPosition = _this.position;
  92188. });
  92189. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  92190. scene._forcedViewPosition = null;
  92191. scene.updateTransformMatrix(true);
  92192. });
  92193. if (scene.activeCamera) {
  92194. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  92195. }
  92196. }
  92197. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  92198. get: function () {
  92199. return this._renderTargetTexture.samples;
  92200. },
  92201. set: function (value) {
  92202. this._renderTargetTexture.samples = value;
  92203. },
  92204. enumerable: true,
  92205. configurable: true
  92206. });
  92207. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  92208. get: function () {
  92209. return this._renderTargetTexture.refreshRate;
  92210. },
  92211. set: function (value) {
  92212. this._renderTargetTexture.refreshRate = value;
  92213. },
  92214. enumerable: true,
  92215. configurable: true
  92216. });
  92217. ReflectionProbe.prototype.getScene = function () {
  92218. return this._scene;
  92219. };
  92220. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  92221. get: function () {
  92222. return this._renderTargetTexture;
  92223. },
  92224. enumerable: true,
  92225. configurable: true
  92226. });
  92227. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  92228. get: function () {
  92229. return this._renderTargetTexture.renderList;
  92230. },
  92231. enumerable: true,
  92232. configurable: true
  92233. });
  92234. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  92235. this._attachedMesh = mesh;
  92236. };
  92237. /**
  92238. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  92239. *
  92240. * @param renderingGroupId The rendering group id corresponding to its index
  92241. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  92242. */
  92243. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  92244. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  92245. };
  92246. ReflectionProbe.prototype.dispose = function () {
  92247. var index = this._scene.reflectionProbes.indexOf(this);
  92248. if (index !== -1) {
  92249. // Remove from the scene if found
  92250. this._scene.reflectionProbes.splice(index, 1);
  92251. }
  92252. if (this._renderTargetTexture) {
  92253. this._renderTargetTexture.dispose();
  92254. this._renderTargetTexture = null;
  92255. }
  92256. };
  92257. return ReflectionProbe;
  92258. }());
  92259. BABYLON.ReflectionProbe = ReflectionProbe;
  92260. })(BABYLON || (BABYLON = {}));
  92261. //# sourceMappingURL=babylon.reflectionProbe.js.map
  92262. "use strict";
  92263. var BABYLON;
  92264. (function (BABYLON) {
  92265. var Layer = /** @class */ (function () {
  92266. function Layer(name, imgUrl, scene, isBackground, color) {
  92267. this.name = name;
  92268. this.scale = new BABYLON.Vector2(1, 1);
  92269. this.offset = new BABYLON.Vector2(0, 0);
  92270. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  92271. this.layerMask = 0x0FFFFFFF;
  92272. this._vertexBuffers = {};
  92273. // Events
  92274. /**
  92275. * An event triggered when the layer is disposed.
  92276. */
  92277. this.onDisposeObservable = new BABYLON.Observable();
  92278. /**
  92279. * An event triggered before rendering the scene
  92280. */
  92281. this.onBeforeRenderObservable = new BABYLON.Observable();
  92282. /**
  92283. * An event triggered after rendering the scene
  92284. */
  92285. this.onAfterRenderObservable = new BABYLON.Observable();
  92286. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  92287. this.isBackground = isBackground === undefined ? true : isBackground;
  92288. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  92289. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  92290. this._scene.layers.push(this);
  92291. var engine = this._scene.getEngine();
  92292. // VBO
  92293. var vertices = [];
  92294. vertices.push(1, 1);
  92295. vertices.push(-1, 1);
  92296. vertices.push(-1, -1);
  92297. vertices.push(1, -1);
  92298. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  92299. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  92300. this._createIndexBuffer();
  92301. // Effects
  92302. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  92303. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  92304. }
  92305. Object.defineProperty(Layer.prototype, "onDispose", {
  92306. set: function (callback) {
  92307. if (this._onDisposeObserver) {
  92308. this.onDisposeObservable.remove(this._onDisposeObserver);
  92309. }
  92310. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  92311. },
  92312. enumerable: true,
  92313. configurable: true
  92314. });
  92315. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  92316. set: function (callback) {
  92317. if (this._onBeforeRenderObserver) {
  92318. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  92319. }
  92320. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  92321. },
  92322. enumerable: true,
  92323. configurable: true
  92324. });
  92325. Object.defineProperty(Layer.prototype, "onAfterRender", {
  92326. set: function (callback) {
  92327. if (this._onAfterRenderObserver) {
  92328. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  92329. }
  92330. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  92331. },
  92332. enumerable: true,
  92333. configurable: true
  92334. });
  92335. Layer.prototype._createIndexBuffer = function () {
  92336. var engine = this._scene.getEngine();
  92337. // Indices
  92338. var indices = [];
  92339. indices.push(0);
  92340. indices.push(1);
  92341. indices.push(2);
  92342. indices.push(0);
  92343. indices.push(2);
  92344. indices.push(3);
  92345. this._indexBuffer = engine.createIndexBuffer(indices);
  92346. };
  92347. Layer.prototype._rebuild = function () {
  92348. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92349. if (vb) {
  92350. vb._rebuild();
  92351. }
  92352. this._createIndexBuffer();
  92353. };
  92354. Layer.prototype.render = function () {
  92355. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  92356. // Check
  92357. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  92358. return;
  92359. var engine = this._scene.getEngine();
  92360. this.onBeforeRenderObservable.notifyObservers(this);
  92361. // Render
  92362. engine.enableEffect(currentEffect);
  92363. engine.setState(false);
  92364. // Texture
  92365. currentEffect.setTexture("textureSampler", this.texture);
  92366. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  92367. // Color
  92368. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  92369. // Scale / offset
  92370. currentEffect.setVector2("offset", this.offset);
  92371. currentEffect.setVector2("scale", this.scale);
  92372. // VBOs
  92373. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  92374. // Draw order
  92375. if (!this.alphaTest) {
  92376. engine.setAlphaMode(this.alphaBlendingMode);
  92377. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92378. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  92379. }
  92380. else {
  92381. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92382. }
  92383. this.onAfterRenderObservable.notifyObservers(this);
  92384. };
  92385. Layer.prototype.dispose = function () {
  92386. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92387. if (vertexBuffer) {
  92388. vertexBuffer.dispose();
  92389. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  92390. }
  92391. if (this._indexBuffer) {
  92392. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  92393. this._indexBuffer = null;
  92394. }
  92395. if (this.texture) {
  92396. this.texture.dispose();
  92397. this.texture = null;
  92398. }
  92399. // Remove from scene
  92400. var index = this._scene.layers.indexOf(this);
  92401. this._scene.layers.splice(index, 1);
  92402. // Callback
  92403. this.onDisposeObservable.notifyObservers(this);
  92404. this.onDisposeObservable.clear();
  92405. this.onAfterRenderObservable.clear();
  92406. this.onBeforeRenderObservable.clear();
  92407. };
  92408. return Layer;
  92409. }());
  92410. BABYLON.Layer = Layer;
  92411. })(BABYLON || (BABYLON = {}));
  92412. //# sourceMappingURL=babylon.layer.js.map
  92413. "use strict";
  92414. var BABYLON;
  92415. (function (BABYLON) {
  92416. var TextureTools = /** @class */ (function () {
  92417. function TextureTools() {
  92418. }
  92419. /**
  92420. * Uses the GPU to create a copy texture rescaled at a given size
  92421. * @param texture Texture to copy from
  92422. * @param width Desired width
  92423. * @param height Desired height
  92424. * @return Generated texture
  92425. */
  92426. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  92427. if (useBilinearMode === void 0) { useBilinearMode = true; }
  92428. var scene = texture.getScene();
  92429. var engine = scene.getEngine();
  92430. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  92431. rtt.wrapU = texture.wrapU;
  92432. rtt.wrapV = texture.wrapV;
  92433. rtt.uOffset = texture.uOffset;
  92434. rtt.vOffset = texture.vOffset;
  92435. rtt.uScale = texture.uScale;
  92436. rtt.vScale = texture.vScale;
  92437. rtt.uAng = texture.uAng;
  92438. rtt.vAng = texture.vAng;
  92439. rtt.wAng = texture.wAng;
  92440. rtt.coordinatesIndex = texture.coordinatesIndex;
  92441. rtt.level = texture.level;
  92442. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  92443. rtt._texture.isReady = false;
  92444. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92445. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92446. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  92447. passPostProcess.getEffect().executeWhenCompiled(function () {
  92448. passPostProcess.onApply = function (effect) {
  92449. effect.setTexture("textureSampler", texture);
  92450. };
  92451. var internalTexture = rtt.getInternalTexture();
  92452. if (internalTexture) {
  92453. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  92454. engine.unBindFramebuffer(internalTexture);
  92455. rtt.disposeFramebufferObjects();
  92456. passPostProcess.dispose();
  92457. internalTexture.isReady = true;
  92458. }
  92459. });
  92460. return rtt;
  92461. };
  92462. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  92463. if (!scene._environmentBRDFTexture) {
  92464. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92465. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92466. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92467. scene._environmentBRDFTexture = texture;
  92468. }
  92469. return scene._environmentBRDFTexture;
  92470. };
  92471. 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=";
  92472. return TextureTools;
  92473. }());
  92474. BABYLON.TextureTools = TextureTools;
  92475. })(BABYLON || (BABYLON = {}));
  92476. //# sourceMappingURL=babylon.textureTools.js.map
  92477. "use strict";
  92478. var BABYLON;
  92479. (function (BABYLON) {
  92480. var FramingBehavior = /** @class */ (function () {
  92481. function FramingBehavior() {
  92482. this._mode = FramingBehavior.FitFrustumSidesMode;
  92483. this._radiusScale = 1.0;
  92484. this._positionScale = 0.5;
  92485. this._defaultElevation = 0.3;
  92486. this._elevationReturnTime = 1500;
  92487. this._elevationReturnWaitTime = 1000;
  92488. this._zoomStopsAnimation = false;
  92489. this._framingTime = 1500;
  92490. this._isPointerDown = false;
  92491. this._lastInteractionTime = -Infinity;
  92492. // Framing control
  92493. this._animatables = new Array();
  92494. this._betaIsAnimating = false;
  92495. }
  92496. Object.defineProperty(FramingBehavior.prototype, "name", {
  92497. get: function () {
  92498. return "Framing";
  92499. },
  92500. enumerable: true,
  92501. configurable: true
  92502. });
  92503. Object.defineProperty(FramingBehavior.prototype, "mode", {
  92504. /**
  92505. * Gets current mode used by the behavior.
  92506. */
  92507. get: function () {
  92508. return this._mode;
  92509. },
  92510. /**
  92511. * Sets the current mode used by the behavior
  92512. */
  92513. set: function (mode) {
  92514. this._mode = mode;
  92515. },
  92516. enumerable: true,
  92517. configurable: true
  92518. });
  92519. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  92520. /**
  92521. * Gets the scale applied to the radius
  92522. */
  92523. get: function () {
  92524. return this._radiusScale;
  92525. },
  92526. /**
  92527. * Sets the scale applied to the radius (1 by default)
  92528. */
  92529. set: function (radius) {
  92530. this._radiusScale = radius;
  92531. },
  92532. enumerable: true,
  92533. configurable: true
  92534. });
  92535. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  92536. /**
  92537. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  92538. */
  92539. get: function () {
  92540. return this._positionScale;
  92541. },
  92542. /**
  92543. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  92544. */
  92545. set: function (scale) {
  92546. this._positionScale = scale;
  92547. },
  92548. enumerable: true,
  92549. configurable: true
  92550. });
  92551. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  92552. /**
  92553. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  92554. * behaviour is triggered, in radians.
  92555. */
  92556. get: function () {
  92557. return this._defaultElevation;
  92558. },
  92559. /**
  92560. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  92561. * behaviour is triggered, in radians.
  92562. */
  92563. set: function (elevation) {
  92564. this._defaultElevation = elevation;
  92565. },
  92566. enumerable: true,
  92567. configurable: true
  92568. });
  92569. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  92570. /**
  92571. * Gets the time (in milliseconds) taken to return to the default beta position.
  92572. * Negative value indicates camera should not return to default.
  92573. */
  92574. get: function () {
  92575. return this._elevationReturnTime;
  92576. },
  92577. /**
  92578. * Sets the time (in milliseconds) taken to return to the default beta position.
  92579. * Negative value indicates camera should not return to default.
  92580. */
  92581. set: function (speed) {
  92582. this._elevationReturnTime = speed;
  92583. },
  92584. enumerable: true,
  92585. configurable: true
  92586. });
  92587. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  92588. /**
  92589. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  92590. */
  92591. get: function () {
  92592. return this._elevationReturnWaitTime;
  92593. },
  92594. /**
  92595. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  92596. */
  92597. set: function (time) {
  92598. this._elevationReturnWaitTime = time;
  92599. },
  92600. enumerable: true,
  92601. configurable: true
  92602. });
  92603. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  92604. /**
  92605. * Gets the flag that indicates if user zooming should stop animation.
  92606. */
  92607. get: function () {
  92608. return this._zoomStopsAnimation;
  92609. },
  92610. /**
  92611. * Sets the flag that indicates if user zooming should stop animation.
  92612. */
  92613. set: function (flag) {
  92614. this._zoomStopsAnimation = flag;
  92615. },
  92616. enumerable: true,
  92617. configurable: true
  92618. });
  92619. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  92620. /**
  92621. * Gets the transition time when framing the mesh, in milliseconds
  92622. */
  92623. get: function () {
  92624. return this._framingTime;
  92625. },
  92626. /**
  92627. * Sets the transition time when framing the mesh, in milliseconds
  92628. */
  92629. set: function (time) {
  92630. this._framingTime = time;
  92631. },
  92632. enumerable: true,
  92633. configurable: true
  92634. });
  92635. FramingBehavior.prototype.init = function () {
  92636. // Do notihng
  92637. };
  92638. FramingBehavior.prototype.attach = function (camera) {
  92639. var _this = this;
  92640. this._attachedCamera = camera;
  92641. var scene = this._attachedCamera.getScene();
  92642. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  92643. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  92644. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  92645. _this._isPointerDown = true;
  92646. return;
  92647. }
  92648. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  92649. _this._isPointerDown = false;
  92650. }
  92651. });
  92652. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  92653. if (mesh) {
  92654. _this.zoomOnMesh(mesh);
  92655. }
  92656. });
  92657. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  92658. // Stop the animation if there is user interaction and the animation should stop for this interaction
  92659. _this._applyUserInteraction();
  92660. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  92661. // back to the default position after a given timeout
  92662. _this._maintainCameraAboveGround();
  92663. });
  92664. };
  92665. FramingBehavior.prototype.detach = function () {
  92666. if (!this._attachedCamera) {
  92667. return;
  92668. }
  92669. var scene = this._attachedCamera.getScene();
  92670. if (this._onPrePointerObservableObserver) {
  92671. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  92672. }
  92673. if (this._onAfterCheckInputsObserver) {
  92674. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  92675. }
  92676. if (this._onMeshTargetChangedObserver) {
  92677. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  92678. }
  92679. this._attachedCamera = null;
  92680. };
  92681. /**
  92682. * Targets the given mesh and updates zoom level accordingly.
  92683. * @param mesh The mesh to target.
  92684. * @param radius Optional. If a cached radius position already exists, overrides default.
  92685. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92686. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92687. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92688. */
  92689. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  92690. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92691. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92692. mesh.computeWorldMatrix(true);
  92693. var boundingBox = mesh.getBoundingInfo().boundingBox;
  92694. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  92695. };
  92696. /**
  92697. * Targets the given mesh with its children and updates zoom level accordingly.
  92698. * @param mesh The mesh to target.
  92699. * @param radius Optional. If a cached radius position already exists, overrides default.
  92700. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92701. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92702. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92703. */
  92704. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  92705. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92706. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92707. mesh.computeWorldMatrix(true);
  92708. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  92709. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  92710. };
  92711. /**
  92712. * Targets the given meshes with their children and updates zoom level accordingly.
  92713. * @param meshes The mesh to target.
  92714. * @param radius Optional. If a cached radius position already exists, overrides default.
  92715. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92716. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92717. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92718. */
  92719. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  92720. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92721. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92722. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  92723. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  92724. for (var i = 0; i < meshes.length; i++) {
  92725. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  92726. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  92727. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  92728. }
  92729. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  92730. };
  92731. /**
  92732. * Targets the given mesh and updates zoom level accordingly.
  92733. * @param mesh The mesh to target.
  92734. * @param radius Optional. If a cached radius position already exists, overrides default.
  92735. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92736. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92737. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92738. */
  92739. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  92740. var _this = this;
  92741. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92742. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92743. var zoomTarget;
  92744. if (!this._attachedCamera) {
  92745. return;
  92746. }
  92747. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  92748. var bottom = minimumWorld.y;
  92749. var top = maximumWorld.y;
  92750. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  92751. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  92752. if (focusOnOriginXZ) {
  92753. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  92754. }
  92755. else {
  92756. var centerWorld = minimumWorld.add(radiusWorld);
  92757. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  92758. }
  92759. if (!this._vectorTransition) {
  92760. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  92761. }
  92762. this._betaIsAnimating = true;
  92763. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  92764. if (animatable) {
  92765. this._animatables.push(animatable);
  92766. }
  92767. // sets the radius and lower radius bounds
  92768. // Small delta ensures camera is not always at lower zoom limit.
  92769. var radius = 0;
  92770. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  92771. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  92772. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  92773. radius = position;
  92774. }
  92775. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  92776. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  92777. if (this._attachedCamera.lowerRadiusLimit === null) {
  92778. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  92779. }
  92780. }
  92781. // Set sensibilities
  92782. var extend = maximumWorld.subtract(minimumWorld).length();
  92783. this._attachedCamera.panningSensibility = 5000 / extend;
  92784. this._attachedCamera.wheelPrecision = 100 / radius;
  92785. // transition to new radius
  92786. if (!this._radiusTransition) {
  92787. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  92788. }
  92789. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  92790. _this.stopAllAnimations();
  92791. if (onAnimationEnd) {
  92792. onAnimationEnd();
  92793. }
  92794. if (_this._attachedCamera) {
  92795. _this._attachedCamera.storeState();
  92796. }
  92797. });
  92798. if (animatable) {
  92799. this._animatables.push(animatable);
  92800. }
  92801. };
  92802. /**
  92803. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  92804. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  92805. * frustum width.
  92806. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  92807. * to fully enclose the mesh in the viewing frustum.
  92808. */
  92809. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  92810. var size = maximumWorld.subtract(minimumWorld);
  92811. var boxVectorGlobalDiagonal = size.length();
  92812. var frustumSlope = this._getFrustumSlope();
  92813. // Formula for setting distance
  92814. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  92815. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  92816. // Horizon distance
  92817. var radius = radiusWithoutFraming * this._radiusScale;
  92818. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  92819. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  92820. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  92821. var camera = this._attachedCamera;
  92822. if (!camera) {
  92823. return 0;
  92824. }
  92825. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  92826. // Don't exceed the requested limit
  92827. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  92828. }
  92829. // Don't exceed the upper radius limit
  92830. if (camera.upperRadiusLimit) {
  92831. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  92832. }
  92833. return distance;
  92834. };
  92835. /**
  92836. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  92837. * is automatically returned to its default position (expected to be above ground plane).
  92838. */
  92839. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  92840. var _this = this;
  92841. if (this._elevationReturnTime < 0) {
  92842. return;
  92843. }
  92844. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  92845. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  92846. var limitBeta = Math.PI * 0.5;
  92847. // Bring the camera back up if below the ground plane
  92848. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  92849. this._betaIsAnimating = true;
  92850. //Transition to new position
  92851. this.stopAllAnimations();
  92852. if (!this._betaTransition) {
  92853. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  92854. }
  92855. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  92856. _this._clearAnimationLocks();
  92857. _this.stopAllAnimations();
  92858. });
  92859. if (animatabe) {
  92860. this._animatables.push(animatabe);
  92861. }
  92862. }
  92863. };
  92864. /**
  92865. * Returns the frustum slope based on the canvas ratio and camera FOV
  92866. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  92867. */
  92868. FramingBehavior.prototype._getFrustumSlope = function () {
  92869. // Calculate the viewport ratio
  92870. // Aspect Ratio is Height/Width.
  92871. var camera = this._attachedCamera;
  92872. if (!camera) {
  92873. return BABYLON.Vector2.Zero();
  92874. }
  92875. var engine = camera.getScene().getEngine();
  92876. var aspectRatio = engine.getAspectRatio(camera);
  92877. // Camera FOV is the vertical field of view (top-bottom) in radians.
  92878. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  92879. var frustumSlopeY = Math.tan(camera.fov / 2);
  92880. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  92881. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  92882. // along the forward vector.
  92883. var frustumSlopeX = frustumSlopeY * aspectRatio;
  92884. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  92885. };
  92886. /**
  92887. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  92888. */
  92889. FramingBehavior.prototype._clearAnimationLocks = function () {
  92890. this._betaIsAnimating = false;
  92891. };
  92892. /**
  92893. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  92894. */
  92895. FramingBehavior.prototype._applyUserInteraction = function () {
  92896. if (this.isUserIsMoving) {
  92897. this._lastInteractionTime = BABYLON.Tools.Now;
  92898. this.stopAllAnimations();
  92899. this._clearAnimationLocks();
  92900. }
  92901. };
  92902. /**
  92903. * Stops and removes all animations that have been applied to the camera
  92904. */
  92905. FramingBehavior.prototype.stopAllAnimations = function () {
  92906. if (this._attachedCamera) {
  92907. this._attachedCamera.animations = [];
  92908. }
  92909. while (this._animatables.length) {
  92910. if (this._animatables[0]) {
  92911. this._animatables[0].onAnimationEnd = null;
  92912. this._animatables[0].stop();
  92913. }
  92914. this._animatables.shift();
  92915. }
  92916. };
  92917. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  92918. /**
  92919. * Gets a value indicating if the user is moving the camera
  92920. */
  92921. get: function () {
  92922. if (!this._attachedCamera) {
  92923. return false;
  92924. }
  92925. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  92926. this._attachedCamera.inertialBetaOffset !== 0 ||
  92927. this._attachedCamera.inertialRadiusOffset !== 0 ||
  92928. this._attachedCamera.inertialPanningX !== 0 ||
  92929. this._attachedCamera.inertialPanningY !== 0 ||
  92930. this._isPointerDown;
  92931. },
  92932. enumerable: true,
  92933. configurable: true
  92934. });
  92935. /**
  92936. * The easing function used by animations
  92937. */
  92938. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  92939. /**
  92940. * The easing mode used by animations
  92941. */
  92942. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  92943. // Statics
  92944. /**
  92945. * The camera can move all the way towards the mesh.
  92946. */
  92947. FramingBehavior.IgnoreBoundsSizeMode = 0;
  92948. /**
  92949. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  92950. */
  92951. FramingBehavior.FitFrustumSidesMode = 1;
  92952. return FramingBehavior;
  92953. }());
  92954. BABYLON.FramingBehavior = FramingBehavior;
  92955. })(BABYLON || (BABYLON = {}));
  92956. //# sourceMappingURL=babylon.framingBehavior.js.map
  92957. "use strict";
  92958. var BABYLON;
  92959. (function (BABYLON) {
  92960. /**
  92961. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  92962. */
  92963. var BouncingBehavior = /** @class */ (function () {
  92964. function BouncingBehavior() {
  92965. /**
  92966. * The duration of the animation, in milliseconds
  92967. */
  92968. this.transitionDuration = 450;
  92969. /**
  92970. * Length of the distance animated by the transition when lower radius is reached
  92971. */
  92972. this.lowerRadiusTransitionRange = 2;
  92973. /**
  92974. * Length of the distance animated by the transition when upper radius is reached
  92975. */
  92976. this.upperRadiusTransitionRange = -2;
  92977. this._autoTransitionRange = false;
  92978. // Animations
  92979. this._radiusIsAnimating = false;
  92980. this._radiusBounceTransition = null;
  92981. this._animatables = new Array();
  92982. }
  92983. Object.defineProperty(BouncingBehavior.prototype, "name", {
  92984. get: function () {
  92985. return "Bouncing";
  92986. },
  92987. enumerable: true,
  92988. configurable: true
  92989. });
  92990. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  92991. /**
  92992. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  92993. */
  92994. get: function () {
  92995. return this._autoTransitionRange;
  92996. },
  92997. /**
  92998. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  92999. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  93000. */
  93001. set: function (value) {
  93002. var _this = this;
  93003. if (this._autoTransitionRange === value) {
  93004. return;
  93005. }
  93006. this._autoTransitionRange = value;
  93007. var camera = this._attachedCamera;
  93008. if (!camera) {
  93009. return;
  93010. }
  93011. if (value) {
  93012. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  93013. if (!mesh) {
  93014. return;
  93015. }
  93016. mesh.computeWorldMatrix(true);
  93017. var diagonal = mesh.getBoundingInfo().diagonalLength;
  93018. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  93019. _this.upperRadiusTransitionRange = diagonal * 0.05;
  93020. });
  93021. }
  93022. else if (this._onMeshTargetChangedObserver) {
  93023. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93024. }
  93025. },
  93026. enumerable: true,
  93027. configurable: true
  93028. });
  93029. BouncingBehavior.prototype.init = function () {
  93030. // Do notihng
  93031. };
  93032. BouncingBehavior.prototype.attach = function (camera) {
  93033. var _this = this;
  93034. this._attachedCamera = camera;
  93035. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  93036. if (!_this._attachedCamera) {
  93037. return;
  93038. }
  93039. // Add the bounce animation to the lower radius limit
  93040. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  93041. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  93042. }
  93043. // Add the bounce animation to the upper radius limit
  93044. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  93045. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  93046. }
  93047. });
  93048. };
  93049. BouncingBehavior.prototype.detach = function () {
  93050. if (!this._attachedCamera) {
  93051. return;
  93052. }
  93053. if (this._onAfterCheckInputsObserver) {
  93054. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  93055. }
  93056. if (this._onMeshTargetChangedObserver) {
  93057. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93058. }
  93059. this._attachedCamera = null;
  93060. };
  93061. /**
  93062. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  93063. * @param radiusLimit The limit to check against.
  93064. * @return Bool to indicate if at limit.
  93065. */
  93066. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  93067. if (!this._attachedCamera) {
  93068. return false;
  93069. }
  93070. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  93071. return true;
  93072. }
  93073. return false;
  93074. };
  93075. /**
  93076. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  93077. * @param radiusDelta The delta by which to animate to. Can be negative.
  93078. */
  93079. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  93080. var _this = this;
  93081. if (!this._attachedCamera) {
  93082. return;
  93083. }
  93084. if (!this._radiusBounceTransition) {
  93085. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  93086. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  93087. }
  93088. // Prevent zoom until bounce has completed
  93089. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  93090. this._attachedCamera.wheelPrecision = Infinity;
  93091. this._attachedCamera.inertialRadiusOffset = 0;
  93092. // Animate to the radius limit
  93093. this.stopAllAnimations();
  93094. this._radiusIsAnimating = true;
  93095. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  93096. if (animatable) {
  93097. this._animatables.push(animatable);
  93098. }
  93099. };
  93100. /**
  93101. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  93102. */
  93103. BouncingBehavior.prototype._clearAnimationLocks = function () {
  93104. this._radiusIsAnimating = false;
  93105. if (this._attachedCamera) {
  93106. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  93107. }
  93108. };
  93109. /**
  93110. * Stops and removes all animations that have been applied to the camera
  93111. */
  93112. BouncingBehavior.prototype.stopAllAnimations = function () {
  93113. if (this._attachedCamera) {
  93114. this._attachedCamera.animations = [];
  93115. }
  93116. while (this._animatables.length) {
  93117. this._animatables[0].onAnimationEnd = null;
  93118. this._animatables[0].stop();
  93119. this._animatables.shift();
  93120. }
  93121. };
  93122. /**
  93123. * The easing function used by animations
  93124. */
  93125. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  93126. /**
  93127. * The easing mode used by animations
  93128. */
  93129. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  93130. return BouncingBehavior;
  93131. }());
  93132. BABYLON.BouncingBehavior = BouncingBehavior;
  93133. })(BABYLON || (BABYLON = {}));
  93134. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  93135. "use strict";
  93136. var BABYLON;
  93137. (function (BABYLON) {
  93138. var AutoRotationBehavior = /** @class */ (function () {
  93139. function AutoRotationBehavior() {
  93140. this._zoomStopsAnimation = false;
  93141. this._idleRotationSpeed = 0.05;
  93142. this._idleRotationWaitTime = 2000;
  93143. this._idleRotationSpinupTime = 2000;
  93144. this._isPointerDown = false;
  93145. this._lastFrameTime = null;
  93146. this._lastInteractionTime = -Infinity;
  93147. this._cameraRotationSpeed = 0;
  93148. this._lastFrameRadius = 0;
  93149. }
  93150. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  93151. get: function () {
  93152. return "AutoRotation";
  93153. },
  93154. enumerable: true,
  93155. configurable: true
  93156. });
  93157. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  93158. /**
  93159. * Gets the flag that indicates if user zooming should stop animation.
  93160. */
  93161. get: function () {
  93162. return this._zoomStopsAnimation;
  93163. },
  93164. /**
  93165. * Sets the flag that indicates if user zooming should stop animation.
  93166. */
  93167. set: function (flag) {
  93168. this._zoomStopsAnimation = flag;
  93169. },
  93170. enumerable: true,
  93171. configurable: true
  93172. });
  93173. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  93174. /**
  93175. * Gets the default speed at which the camera rotates around the model.
  93176. */
  93177. get: function () {
  93178. return this._idleRotationSpeed;
  93179. },
  93180. /**
  93181. * Sets the default speed at which the camera rotates around the model.
  93182. */
  93183. set: function (speed) {
  93184. this._idleRotationSpeed = speed;
  93185. },
  93186. enumerable: true,
  93187. configurable: true
  93188. });
  93189. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  93190. /**
  93191. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  93192. */
  93193. get: function () {
  93194. return this._idleRotationWaitTime;
  93195. },
  93196. /**
  93197. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  93198. */
  93199. set: function (time) {
  93200. this._idleRotationWaitTime = time;
  93201. },
  93202. enumerable: true,
  93203. configurable: true
  93204. });
  93205. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  93206. /**
  93207. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  93208. */
  93209. get: function () {
  93210. return this._idleRotationSpinupTime;
  93211. },
  93212. /**
  93213. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  93214. */
  93215. set: function (time) {
  93216. this._idleRotationSpinupTime = time;
  93217. },
  93218. enumerable: true,
  93219. configurable: true
  93220. });
  93221. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  93222. /**
  93223. * Gets a value indicating if the camera is currently rotating because of this behavior
  93224. */
  93225. get: function () {
  93226. return Math.abs(this._cameraRotationSpeed) > 0;
  93227. },
  93228. enumerable: true,
  93229. configurable: true
  93230. });
  93231. AutoRotationBehavior.prototype.init = function () {
  93232. // Do notihng
  93233. };
  93234. AutoRotationBehavior.prototype.attach = function (camera) {
  93235. var _this = this;
  93236. this._attachedCamera = camera;
  93237. var scene = this._attachedCamera.getScene();
  93238. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  93239. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  93240. _this._isPointerDown = true;
  93241. return;
  93242. }
  93243. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  93244. _this._isPointerDown = false;
  93245. }
  93246. });
  93247. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  93248. var now = BABYLON.Tools.Now;
  93249. var dt = 0;
  93250. if (_this._lastFrameTime != null) {
  93251. dt = now - _this._lastFrameTime;
  93252. }
  93253. _this._lastFrameTime = now;
  93254. // Stop the animation if there is user interaction and the animation should stop for this interaction
  93255. _this._applyUserInteraction();
  93256. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  93257. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  93258. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  93259. // Step camera rotation by rotation speed
  93260. if (_this._attachedCamera) {
  93261. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  93262. }
  93263. });
  93264. };
  93265. AutoRotationBehavior.prototype.detach = function () {
  93266. if (!this._attachedCamera) {
  93267. return;
  93268. }
  93269. var scene = this._attachedCamera.getScene();
  93270. if (this._onPrePointerObservableObserver) {
  93271. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  93272. }
  93273. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  93274. this._attachedCamera = null;
  93275. };
  93276. /**
  93277. * Returns true if user is scrolling.
  93278. * @return true if user is scrolling.
  93279. */
  93280. AutoRotationBehavior.prototype._userIsZooming = function () {
  93281. if (!this._attachedCamera) {
  93282. return false;
  93283. }
  93284. return this._attachedCamera.inertialRadiusOffset !== 0;
  93285. };
  93286. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  93287. if (!this._attachedCamera) {
  93288. return false;
  93289. }
  93290. var zoomHasHitLimit = false;
  93291. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  93292. zoomHasHitLimit = true;
  93293. }
  93294. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  93295. this._lastFrameRadius = this._attachedCamera.radius;
  93296. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  93297. };
  93298. /**
  93299. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  93300. */
  93301. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  93302. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  93303. this._lastInteractionTime = BABYLON.Tools.Now;
  93304. }
  93305. };
  93306. // Tools
  93307. AutoRotationBehavior.prototype._userIsMoving = function () {
  93308. if (!this._attachedCamera) {
  93309. return false;
  93310. }
  93311. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  93312. this._attachedCamera.inertialBetaOffset !== 0 ||
  93313. this._attachedCamera.inertialRadiusOffset !== 0 ||
  93314. this._attachedCamera.inertialPanningX !== 0 ||
  93315. this._attachedCamera.inertialPanningY !== 0 ||
  93316. this._isPointerDown;
  93317. };
  93318. return AutoRotationBehavior;
  93319. }());
  93320. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  93321. })(BABYLON || (BABYLON = {}));
  93322. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  93323. "use strict";
  93324. var BABYLON;
  93325. (function (BABYLON) {
  93326. var NullEngineOptions = /** @class */ (function () {
  93327. function NullEngineOptions() {
  93328. this.renderWidth = 512;
  93329. this.renderHeight = 256;
  93330. this.textureSize = 512;
  93331. this.deterministicLockstep = false;
  93332. this.lockstepMaxSteps = 4;
  93333. }
  93334. return NullEngineOptions;
  93335. }());
  93336. BABYLON.NullEngineOptions = NullEngineOptions;
  93337. /**
  93338. * The null engine class provides support for headless version of babylon.js.
  93339. * This can be used in server side scenario or for testing purposes
  93340. */
  93341. var NullEngine = /** @class */ (function (_super) {
  93342. __extends(NullEngine, _super);
  93343. function NullEngine(options) {
  93344. if (options === void 0) { options = new NullEngineOptions(); }
  93345. var _this = _super.call(this, null) || this;
  93346. if (options.deterministicLockstep === undefined) {
  93347. options.deterministicLockstep = false;
  93348. }
  93349. if (options.lockstepMaxSteps === undefined) {
  93350. options.lockstepMaxSteps = 4;
  93351. }
  93352. _this._options = options;
  93353. // Init caps
  93354. // We consider we are on a webgl1 capable device
  93355. _this._caps = new BABYLON.EngineCapabilities();
  93356. _this._caps.maxTexturesImageUnits = 16;
  93357. _this._caps.maxVertexTextureImageUnits = 16;
  93358. _this._caps.maxTextureSize = 512;
  93359. _this._caps.maxCubemapTextureSize = 512;
  93360. _this._caps.maxRenderTextureSize = 512;
  93361. _this._caps.maxVertexAttribs = 16;
  93362. _this._caps.maxVaryingVectors = 16;
  93363. _this._caps.maxFragmentUniformVectors = 16;
  93364. _this._caps.maxVertexUniformVectors = 16;
  93365. // Extensions
  93366. _this._caps.standardDerivatives = false;
  93367. _this._caps.astc = null;
  93368. _this._caps.s3tc = null;
  93369. _this._caps.pvrtc = null;
  93370. _this._caps.etc1 = null;
  93371. _this._caps.etc2 = null;
  93372. _this._caps.textureAnisotropicFilterExtension = null;
  93373. _this._caps.maxAnisotropy = 0;
  93374. _this._caps.uintIndices = false;
  93375. _this._caps.fragmentDepthSupported = false;
  93376. _this._caps.highPrecisionShaderSupported = true;
  93377. _this._caps.colorBufferFloat = false;
  93378. _this._caps.textureFloat = false;
  93379. _this._caps.textureFloatLinearFiltering = false;
  93380. _this._caps.textureFloatRender = false;
  93381. _this._caps.textureHalfFloat = false;
  93382. _this._caps.textureHalfFloatLinearFiltering = false;
  93383. _this._caps.textureHalfFloatRender = false;
  93384. _this._caps.textureLOD = false;
  93385. _this._caps.drawBuffersExtension = false;
  93386. _this._caps.depthTextureExtension = false;
  93387. _this._caps.vertexArrayObject = false;
  93388. _this._caps.instancedArrays = false;
  93389. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  93390. // Wrappers
  93391. if (typeof URL === "undefined") {
  93392. URL = {
  93393. createObjectURL: function () { },
  93394. revokeObjectURL: function () { }
  93395. };
  93396. }
  93397. if (typeof Blob === "undefined") {
  93398. Blob = function () { };
  93399. }
  93400. return _this;
  93401. }
  93402. NullEngine.prototype.isDeterministicLockStep = function () {
  93403. return this._options.deterministicLockstep;
  93404. };
  93405. NullEngine.prototype.getLockstepMaxSteps = function () {
  93406. return this._options.lockstepMaxSteps;
  93407. };
  93408. NullEngine.prototype.getHardwareScalingLevel = function () {
  93409. return 1.0;
  93410. };
  93411. NullEngine.prototype.createVertexBuffer = function (vertices) {
  93412. return {
  93413. capacity: 0,
  93414. references: 1,
  93415. is32Bits: false
  93416. };
  93417. };
  93418. NullEngine.prototype.createIndexBuffer = function (indices) {
  93419. return {
  93420. capacity: 0,
  93421. references: 1,
  93422. is32Bits: false
  93423. };
  93424. };
  93425. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  93426. if (stencil === void 0) { stencil = false; }
  93427. };
  93428. NullEngine.prototype.getRenderWidth = function (useScreen) {
  93429. if (useScreen === void 0) { useScreen = false; }
  93430. if (!useScreen && this._currentRenderTarget) {
  93431. return this._currentRenderTarget.width;
  93432. }
  93433. return this._options.renderWidth;
  93434. };
  93435. NullEngine.prototype.getRenderHeight = function (useScreen) {
  93436. if (useScreen === void 0) { useScreen = false; }
  93437. if (!useScreen && this._currentRenderTarget) {
  93438. return this._currentRenderTarget.height;
  93439. }
  93440. return this._options.renderHeight;
  93441. };
  93442. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  93443. this._cachedViewport = viewport;
  93444. };
  93445. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  93446. return {
  93447. transformFeedback: null,
  93448. __SPECTOR_rebuildProgram: null
  93449. };
  93450. };
  93451. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  93452. return [];
  93453. };
  93454. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  93455. return [];
  93456. };
  93457. NullEngine.prototype.bindSamplers = function (effect) {
  93458. this._currentEffect = null;
  93459. };
  93460. NullEngine.prototype.enableEffect = function (effect) {
  93461. this._currentEffect = effect;
  93462. if (effect.onBind) {
  93463. effect.onBind(effect);
  93464. }
  93465. effect.onBindObservable.notifyObservers(effect);
  93466. };
  93467. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  93468. if (zOffset === void 0) { zOffset = 0; }
  93469. if (reverseSide === void 0) { reverseSide = false; }
  93470. };
  93471. NullEngine.prototype.setIntArray = function (uniform, array) {
  93472. };
  93473. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  93474. };
  93475. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  93476. };
  93477. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  93478. };
  93479. NullEngine.prototype.setFloatArray = function (uniform, array) {
  93480. };
  93481. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  93482. };
  93483. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  93484. };
  93485. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  93486. };
  93487. NullEngine.prototype.setArray = function (uniform, array) {
  93488. };
  93489. NullEngine.prototype.setArray2 = function (uniform, array) {
  93490. };
  93491. NullEngine.prototype.setArray3 = function (uniform, array) {
  93492. };
  93493. NullEngine.prototype.setArray4 = function (uniform, array) {
  93494. };
  93495. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  93496. };
  93497. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  93498. };
  93499. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  93500. };
  93501. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  93502. };
  93503. NullEngine.prototype.setFloat = function (uniform, value) {
  93504. };
  93505. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  93506. };
  93507. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  93508. };
  93509. NullEngine.prototype.setBool = function (uniform, bool) {
  93510. };
  93511. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  93512. };
  93513. NullEngine.prototype.setColor3 = function (uniform, color3) {
  93514. };
  93515. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  93516. };
  93517. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  93518. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  93519. if (this._alphaMode === mode) {
  93520. return;
  93521. }
  93522. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  93523. if (!noDepthWriteChange) {
  93524. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  93525. }
  93526. this._alphaMode = mode;
  93527. };
  93528. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  93529. };
  93530. NullEngine.prototype.wipeCaches = function (bruteForce) {
  93531. if (this.preventCacheWipeBetweenFrames) {
  93532. return;
  93533. }
  93534. this.resetTextureCache();
  93535. this._currentEffect = null;
  93536. if (bruteForce) {
  93537. this._currentProgram = null;
  93538. this._stencilState.reset();
  93539. this._depthCullingState.reset();
  93540. this._alphaState.reset();
  93541. }
  93542. this._cachedVertexBuffers = null;
  93543. this._cachedIndexBuffer = null;
  93544. this._cachedEffectForVertexBuffers = null;
  93545. };
  93546. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  93547. };
  93548. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  93549. };
  93550. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  93551. };
  93552. NullEngine.prototype._createTexture = function () {
  93553. return {};
  93554. };
  93555. NullEngine.prototype._releaseTexture = function (texture) {
  93556. };
  93557. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  93558. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93559. if (onLoad === void 0) { onLoad = null; }
  93560. if (onError === void 0) { onError = null; }
  93561. if (buffer === void 0) { buffer = null; }
  93562. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  93563. var url = String(urlArg);
  93564. texture.url = url;
  93565. texture.generateMipMaps = !noMipmap;
  93566. texture.samplingMode = samplingMode;
  93567. texture.invertY = invertY;
  93568. texture.baseWidth = this._options.textureSize;
  93569. texture.baseHeight = this._options.textureSize;
  93570. texture.width = this._options.textureSize;
  93571. texture.height = this._options.textureSize;
  93572. if (format) {
  93573. texture.format = format;
  93574. }
  93575. texture.isReady = true;
  93576. if (onLoad) {
  93577. onLoad();
  93578. }
  93579. return texture;
  93580. };
  93581. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  93582. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  93583. if (options !== undefined && typeof options === "object") {
  93584. fullOptions.generateMipMaps = options.generateMipMaps;
  93585. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  93586. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  93587. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  93588. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  93589. }
  93590. else {
  93591. fullOptions.generateMipMaps = options;
  93592. fullOptions.generateDepthBuffer = true;
  93593. fullOptions.generateStencilBuffer = false;
  93594. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93595. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  93596. }
  93597. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  93598. var width = size.width || size;
  93599. var height = size.height || size;
  93600. texture._depthStencilBuffer = {};
  93601. texture._framebuffer = {};
  93602. texture.baseWidth = width;
  93603. texture.baseHeight = height;
  93604. texture.width = width;
  93605. texture.height = height;
  93606. texture.isReady = true;
  93607. texture.samples = 1;
  93608. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  93609. texture.samplingMode = fullOptions.samplingMode;
  93610. texture.type = fullOptions.type;
  93611. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  93612. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  93613. return texture;
  93614. };
  93615. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  93616. texture.samplingMode = samplingMode;
  93617. };
  93618. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  93619. if (this._currentRenderTarget) {
  93620. this.unBindFramebuffer(this._currentRenderTarget);
  93621. }
  93622. this._currentRenderTarget = texture;
  93623. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  93624. if (this._cachedViewport && !forceFullscreenViewport) {
  93625. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  93626. }
  93627. };
  93628. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  93629. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  93630. this._currentRenderTarget = null;
  93631. if (onBeforeUnbind) {
  93632. if (texture._MSAAFramebuffer) {
  93633. this._currentFramebuffer = texture._framebuffer;
  93634. }
  93635. onBeforeUnbind();
  93636. }
  93637. this._currentFramebuffer = null;
  93638. };
  93639. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  93640. var vbo = {
  93641. capacity: 1,
  93642. references: 1,
  93643. is32Bits: false
  93644. };
  93645. return vbo;
  93646. };
  93647. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  93648. if (offset === void 0) { offset = 0; }
  93649. };
  93650. /**
  93651. * Updates a dynamic vertex buffer.
  93652. * @param vertexBuffer the vertex buffer to update
  93653. * @param data the data used to update the vertex buffer
  93654. * @param byteOffset the byte offset of the data (optional)
  93655. * @param byteLength the byte length of the data (optional)
  93656. */
  93657. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  93658. };
  93659. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  93660. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  93661. this._boundTexturesCache[this._activeChannel] = texture;
  93662. }
  93663. };
  93664. NullEngine.prototype._bindTexture = function (channel, texture) {
  93665. if (channel < 0) {
  93666. return;
  93667. }
  93668. this._bindTextureDirectly(0, texture);
  93669. };
  93670. NullEngine.prototype._releaseBuffer = function (buffer) {
  93671. buffer.references--;
  93672. if (buffer.references === 0) {
  93673. return true;
  93674. }
  93675. return false;
  93676. };
  93677. return NullEngine;
  93678. }(BABYLON.Engine));
  93679. BABYLON.NullEngine = NullEngine;
  93680. })(BABYLON || (BABYLON = {}));
  93681. //# sourceMappingURL=babylon.nullEngine.js.map
  93682. "use strict";
  93683. var BABYLON;
  93684. (function (BABYLON) {
  93685. /**
  93686. * This class can be used to get instrumentation data from a Babylon engine
  93687. */
  93688. var EngineInstrumentation = /** @class */ (function () {
  93689. function EngineInstrumentation(engine) {
  93690. this.engine = engine;
  93691. this._captureGPUFrameTime = false;
  93692. this._gpuFrameTime = new BABYLON.PerfCounter();
  93693. this._captureShaderCompilationTime = false;
  93694. this._shaderCompilationTime = new BABYLON.PerfCounter();
  93695. // Observers
  93696. this._onBeginFrameObserver = null;
  93697. this._onEndFrameObserver = null;
  93698. this._onBeforeShaderCompilationObserver = null;
  93699. this._onAfterShaderCompilationObserver = null;
  93700. }
  93701. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  93702. // Properties
  93703. /**
  93704. * Gets the perf counter used for GPU frame time
  93705. */
  93706. get: function () {
  93707. return this._gpuFrameTime;
  93708. },
  93709. enumerable: true,
  93710. configurable: true
  93711. });
  93712. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  93713. /**
  93714. * Gets the GPU frame time capture status
  93715. */
  93716. get: function () {
  93717. return this._captureGPUFrameTime;
  93718. },
  93719. /**
  93720. * Enable or disable the GPU frame time capture
  93721. */
  93722. set: function (value) {
  93723. var _this = this;
  93724. if (value === this._captureGPUFrameTime) {
  93725. return;
  93726. }
  93727. this._captureGPUFrameTime = value;
  93728. if (value) {
  93729. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  93730. if (!_this._gpuFrameTimeToken) {
  93731. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  93732. }
  93733. });
  93734. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  93735. if (!_this._gpuFrameTimeToken) {
  93736. return;
  93737. }
  93738. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  93739. if (time > -1) {
  93740. _this._gpuFrameTimeToken = null;
  93741. _this._gpuFrameTime.fetchNewFrame();
  93742. _this._gpuFrameTime.addCount(time, true);
  93743. }
  93744. });
  93745. }
  93746. else {
  93747. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  93748. this._onBeginFrameObserver = null;
  93749. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  93750. this._onEndFrameObserver = null;
  93751. }
  93752. },
  93753. enumerable: true,
  93754. configurable: true
  93755. });
  93756. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  93757. /**
  93758. * Gets the perf counter used for shader compilation time
  93759. */
  93760. get: function () {
  93761. return this._shaderCompilationTime;
  93762. },
  93763. enumerable: true,
  93764. configurable: true
  93765. });
  93766. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  93767. /**
  93768. * Gets the shader compilation time capture status
  93769. */
  93770. get: function () {
  93771. return this._captureShaderCompilationTime;
  93772. },
  93773. /**
  93774. * Enable or disable the shader compilation time capture
  93775. */
  93776. set: function (value) {
  93777. var _this = this;
  93778. if (value === this._captureShaderCompilationTime) {
  93779. return;
  93780. }
  93781. this._captureShaderCompilationTime = value;
  93782. if (value) {
  93783. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  93784. _this._shaderCompilationTime.fetchNewFrame();
  93785. _this._shaderCompilationTime.beginMonitoring();
  93786. });
  93787. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  93788. _this._shaderCompilationTime.endMonitoring();
  93789. });
  93790. }
  93791. else {
  93792. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  93793. this._onBeforeShaderCompilationObserver = null;
  93794. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  93795. this._onAfterShaderCompilationObserver = null;
  93796. }
  93797. },
  93798. enumerable: true,
  93799. configurable: true
  93800. });
  93801. EngineInstrumentation.prototype.dispose = function () {
  93802. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  93803. this._onBeginFrameObserver = null;
  93804. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  93805. this._onEndFrameObserver = null;
  93806. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  93807. this._onBeforeShaderCompilationObserver = null;
  93808. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  93809. this._onAfterShaderCompilationObserver = null;
  93810. this.engine = null;
  93811. };
  93812. return EngineInstrumentation;
  93813. }());
  93814. BABYLON.EngineInstrumentation = EngineInstrumentation;
  93815. })(BABYLON || (BABYLON = {}));
  93816. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  93817. "use strict";
  93818. var BABYLON;
  93819. (function (BABYLON) {
  93820. /**
  93821. * This class can be used to get instrumentation data from a Babylon engine
  93822. */
  93823. var SceneInstrumentation = /** @class */ (function () {
  93824. function SceneInstrumentation(scene) {
  93825. var _this = this;
  93826. this.scene = scene;
  93827. this._captureActiveMeshesEvaluationTime = false;
  93828. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  93829. this._captureRenderTargetsRenderTime = false;
  93830. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  93831. this._captureFrameTime = false;
  93832. this._frameTime = new BABYLON.PerfCounter();
  93833. this._captureRenderTime = false;
  93834. this._renderTime = new BABYLON.PerfCounter();
  93835. this._captureInterFrameTime = false;
  93836. this._interFrameTime = new BABYLON.PerfCounter();
  93837. this._captureParticlesRenderTime = false;
  93838. this._particlesRenderTime = new BABYLON.PerfCounter();
  93839. this._captureSpritesRenderTime = false;
  93840. this._spritesRenderTime = new BABYLON.PerfCounter();
  93841. this._capturePhysicsTime = false;
  93842. this._physicsTime = new BABYLON.PerfCounter();
  93843. this._captureAnimationsTime = false;
  93844. this._animationsTime = new BABYLON.PerfCounter();
  93845. // Observers
  93846. this._onBeforeActiveMeshesEvaluationObserver = null;
  93847. this._onAfterActiveMeshesEvaluationObserver = null;
  93848. this._onBeforeRenderTargetsRenderObserver = null;
  93849. this._onAfterRenderTargetsRenderObserver = null;
  93850. this._onAfterRenderObserver = null;
  93851. this._onBeforeDrawPhaseObserver = null;
  93852. this._onAfterDrawPhaseObserver = null;
  93853. this._onBeforeAnimationsObserver = null;
  93854. this._onBeforeParticlesRenderingObserver = null;
  93855. this._onAfterParticlesRenderingObserver = null;
  93856. this._onBeforeSpritesRenderingObserver = null;
  93857. this._onAfterSpritesRenderingObserver = null;
  93858. this._onBeforePhysicsObserver = null;
  93859. this._onAfterPhysicsObserver = null;
  93860. this._onAfterAnimationsObserver = null;
  93861. // Before render
  93862. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  93863. if (_this._captureActiveMeshesEvaluationTime) {
  93864. _this._activeMeshesEvaluationTime.fetchNewFrame();
  93865. }
  93866. if (_this._captureRenderTargetsRenderTime) {
  93867. _this._renderTargetsRenderTime.fetchNewFrame();
  93868. }
  93869. if (_this._captureFrameTime) {
  93870. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  93871. _this._frameTime.beginMonitoring();
  93872. }
  93873. if (_this._captureInterFrameTime) {
  93874. _this._interFrameTime.endMonitoring();
  93875. }
  93876. if (_this._captureParticlesRenderTime) {
  93877. _this._particlesRenderTime.fetchNewFrame();
  93878. }
  93879. if (_this._captureSpritesRenderTime) {
  93880. _this._spritesRenderTime.fetchNewFrame();
  93881. }
  93882. if (_this._captureAnimationsTime) {
  93883. _this._animationsTime.beginMonitoring();
  93884. }
  93885. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  93886. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  93887. });
  93888. // After render
  93889. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  93890. if (_this._captureFrameTime) {
  93891. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  93892. _this._frameTime.endMonitoring();
  93893. }
  93894. if (_this._captureRenderTime) {
  93895. _this._renderTime.endMonitoring(false);
  93896. }
  93897. if (_this._captureInterFrameTime) {
  93898. _this._interFrameTime.beginMonitoring();
  93899. }
  93900. });
  93901. }
  93902. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  93903. // Properties
  93904. /**
  93905. * Gets the perf counter used for active meshes evaluation time
  93906. */
  93907. get: function () {
  93908. return this._activeMeshesEvaluationTime;
  93909. },
  93910. enumerable: true,
  93911. configurable: true
  93912. });
  93913. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  93914. /**
  93915. * Gets the active meshes evaluation time capture status
  93916. */
  93917. get: function () {
  93918. return this._captureActiveMeshesEvaluationTime;
  93919. },
  93920. /**
  93921. * Enable or disable the active meshes evaluation time capture
  93922. */
  93923. set: function (value) {
  93924. var _this = this;
  93925. if (value === this._captureActiveMeshesEvaluationTime) {
  93926. return;
  93927. }
  93928. this._captureActiveMeshesEvaluationTime = value;
  93929. if (value) {
  93930. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  93931. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  93932. _this._activeMeshesEvaluationTime.beginMonitoring();
  93933. });
  93934. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  93935. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  93936. _this._activeMeshesEvaluationTime.endMonitoring();
  93937. });
  93938. }
  93939. else {
  93940. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  93941. this._onBeforeActiveMeshesEvaluationObserver = null;
  93942. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  93943. this._onAfterActiveMeshesEvaluationObserver = null;
  93944. }
  93945. },
  93946. enumerable: true,
  93947. configurable: true
  93948. });
  93949. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  93950. /**
  93951. * Gets the perf counter used for render targets render time
  93952. */
  93953. get: function () {
  93954. return this._renderTargetsRenderTime;
  93955. },
  93956. enumerable: true,
  93957. configurable: true
  93958. });
  93959. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  93960. /**
  93961. * Gets the render targets render time capture status
  93962. */
  93963. get: function () {
  93964. return this._captureRenderTargetsRenderTime;
  93965. },
  93966. /**
  93967. * Enable or disable the render targets render time capture
  93968. */
  93969. set: function (value) {
  93970. var _this = this;
  93971. if (value === this._captureRenderTargetsRenderTime) {
  93972. return;
  93973. }
  93974. this._captureRenderTargetsRenderTime = value;
  93975. if (value) {
  93976. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  93977. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  93978. _this._renderTargetsRenderTime.beginMonitoring();
  93979. });
  93980. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  93981. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  93982. _this._renderTargetsRenderTime.endMonitoring(false);
  93983. });
  93984. }
  93985. else {
  93986. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  93987. this._onBeforeRenderTargetsRenderObserver = null;
  93988. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  93989. this._onAfterRenderTargetsRenderObserver = null;
  93990. }
  93991. },
  93992. enumerable: true,
  93993. configurable: true
  93994. });
  93995. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  93996. /**
  93997. * Gets the perf counter used for particles render time
  93998. */
  93999. get: function () {
  94000. return this._particlesRenderTime;
  94001. },
  94002. enumerable: true,
  94003. configurable: true
  94004. });
  94005. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  94006. /**
  94007. * Gets the particles render time capture status
  94008. */
  94009. get: function () {
  94010. return this._captureParticlesRenderTime;
  94011. },
  94012. /**
  94013. * Enable or disable the particles render time capture
  94014. */
  94015. set: function (value) {
  94016. var _this = this;
  94017. if (value === this._captureParticlesRenderTime) {
  94018. return;
  94019. }
  94020. this._captureParticlesRenderTime = value;
  94021. if (value) {
  94022. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  94023. BABYLON.Tools.StartPerformanceCounter("Particles");
  94024. _this._particlesRenderTime.beginMonitoring();
  94025. });
  94026. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  94027. BABYLON.Tools.EndPerformanceCounter("Particles");
  94028. _this._particlesRenderTime.endMonitoring(false);
  94029. });
  94030. }
  94031. else {
  94032. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  94033. this._onBeforeParticlesRenderingObserver = null;
  94034. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  94035. this._onAfterParticlesRenderingObserver = null;
  94036. }
  94037. },
  94038. enumerable: true,
  94039. configurable: true
  94040. });
  94041. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  94042. /**
  94043. * Gets the perf counter used for sprites render time
  94044. */
  94045. get: function () {
  94046. return this._spritesRenderTime;
  94047. },
  94048. enumerable: true,
  94049. configurable: true
  94050. });
  94051. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  94052. /**
  94053. * Gets the sprites render time capture status
  94054. */
  94055. get: function () {
  94056. return this._captureSpritesRenderTime;
  94057. },
  94058. /**
  94059. * Enable or disable the sprites render time capture
  94060. */
  94061. set: function (value) {
  94062. var _this = this;
  94063. if (value === this._captureSpritesRenderTime) {
  94064. return;
  94065. }
  94066. this._captureSpritesRenderTime = value;
  94067. if (value) {
  94068. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  94069. BABYLON.Tools.StartPerformanceCounter("Sprites");
  94070. _this._spritesRenderTime.beginMonitoring();
  94071. });
  94072. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  94073. BABYLON.Tools.EndPerformanceCounter("Sprites");
  94074. _this._spritesRenderTime.endMonitoring(false);
  94075. });
  94076. }
  94077. else {
  94078. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  94079. this._onBeforeSpritesRenderingObserver = null;
  94080. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  94081. this._onAfterSpritesRenderingObserver = null;
  94082. }
  94083. },
  94084. enumerable: true,
  94085. configurable: true
  94086. });
  94087. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  94088. /**
  94089. * Gets the perf counter used for physics time
  94090. */
  94091. get: function () {
  94092. return this._physicsTime;
  94093. },
  94094. enumerable: true,
  94095. configurable: true
  94096. });
  94097. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  94098. /**
  94099. * Gets the physics time capture status
  94100. */
  94101. get: function () {
  94102. return this._capturePhysicsTime;
  94103. },
  94104. /**
  94105. * Enable or disable the physics time capture
  94106. */
  94107. set: function (value) {
  94108. var _this = this;
  94109. if (value === this._capturePhysicsTime) {
  94110. return;
  94111. }
  94112. this._capturePhysicsTime = value;
  94113. if (value) {
  94114. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  94115. BABYLON.Tools.StartPerformanceCounter("Physics");
  94116. _this._physicsTime.beginMonitoring();
  94117. });
  94118. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  94119. BABYLON.Tools.EndPerformanceCounter("Physics");
  94120. _this._physicsTime.endMonitoring();
  94121. });
  94122. }
  94123. else {
  94124. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  94125. this._onBeforePhysicsObserver = null;
  94126. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  94127. this._onAfterPhysicsObserver = null;
  94128. }
  94129. },
  94130. enumerable: true,
  94131. configurable: true
  94132. });
  94133. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  94134. /**
  94135. * Gets the perf counter used for animations time
  94136. */
  94137. get: function () {
  94138. return this._animationsTime;
  94139. },
  94140. enumerable: true,
  94141. configurable: true
  94142. });
  94143. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  94144. /**
  94145. * Gets the animations time capture status
  94146. */
  94147. get: function () {
  94148. return this._captureAnimationsTime;
  94149. },
  94150. /**
  94151. * Enable or disable the animations time capture
  94152. */
  94153. set: function (value) {
  94154. var _this = this;
  94155. if (value === this._captureAnimationsTime) {
  94156. return;
  94157. }
  94158. this._captureAnimationsTime = value;
  94159. if (value) {
  94160. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  94161. _this._animationsTime.endMonitoring();
  94162. });
  94163. }
  94164. else {
  94165. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  94166. this._onAfterAnimationsObserver = null;
  94167. }
  94168. },
  94169. enumerable: true,
  94170. configurable: true
  94171. });
  94172. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  94173. /**
  94174. * Gets the perf counter used for frame time capture
  94175. */
  94176. get: function () {
  94177. return this._frameTime;
  94178. },
  94179. enumerable: true,
  94180. configurable: true
  94181. });
  94182. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  94183. /**
  94184. * Gets the frame time capture status
  94185. */
  94186. get: function () {
  94187. return this._captureFrameTime;
  94188. },
  94189. /**
  94190. * Enable or disable the frame time capture
  94191. */
  94192. set: function (value) {
  94193. this._captureFrameTime = value;
  94194. },
  94195. enumerable: true,
  94196. configurable: true
  94197. });
  94198. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  94199. /**
  94200. * Gets the perf counter used for inter-frames time capture
  94201. */
  94202. get: function () {
  94203. return this._interFrameTime;
  94204. },
  94205. enumerable: true,
  94206. configurable: true
  94207. });
  94208. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  94209. /**
  94210. * Gets the inter-frames time capture status
  94211. */
  94212. get: function () {
  94213. return this._captureInterFrameTime;
  94214. },
  94215. /**
  94216. * Enable or disable the inter-frames time capture
  94217. */
  94218. set: function (value) {
  94219. this._captureInterFrameTime = value;
  94220. },
  94221. enumerable: true,
  94222. configurable: true
  94223. });
  94224. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  94225. /**
  94226. * Gets the perf counter used for render time capture
  94227. */
  94228. get: function () {
  94229. return this._renderTime;
  94230. },
  94231. enumerable: true,
  94232. configurable: true
  94233. });
  94234. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  94235. /**
  94236. * Gets the render time capture status
  94237. */
  94238. get: function () {
  94239. return this._captureRenderTime;
  94240. },
  94241. /**
  94242. * Enable or disable the render time capture
  94243. */
  94244. set: function (value) {
  94245. var _this = this;
  94246. if (value === this._captureRenderTime) {
  94247. return;
  94248. }
  94249. this._captureRenderTime = value;
  94250. if (value) {
  94251. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  94252. _this._renderTime.beginMonitoring();
  94253. BABYLON.Tools.StartPerformanceCounter("Main render");
  94254. });
  94255. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  94256. _this._renderTime.endMonitoring(false);
  94257. BABYLON.Tools.EndPerformanceCounter("Main render");
  94258. });
  94259. }
  94260. else {
  94261. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  94262. this._onBeforeDrawPhaseObserver = null;
  94263. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  94264. this._onAfterDrawPhaseObserver = null;
  94265. }
  94266. },
  94267. enumerable: true,
  94268. configurable: true
  94269. });
  94270. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  94271. /**
  94272. * Gets the perf counter used for draw calls
  94273. */
  94274. get: function () {
  94275. return this.scene.getEngine()._drawCalls;
  94276. },
  94277. enumerable: true,
  94278. configurable: true
  94279. });
  94280. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  94281. /**
  94282. * Gets the perf counter used for texture collisions
  94283. */
  94284. get: function () {
  94285. return this.scene.getEngine()._textureCollisions;
  94286. },
  94287. enumerable: true,
  94288. configurable: true
  94289. });
  94290. SceneInstrumentation.prototype.dispose = function () {
  94291. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  94292. this._onAfterRenderObserver = null;
  94293. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  94294. this._onBeforeActiveMeshesEvaluationObserver = null;
  94295. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  94296. this._onAfterActiveMeshesEvaluationObserver = null;
  94297. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  94298. this._onBeforeRenderTargetsRenderObserver = null;
  94299. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  94300. this._onAfterRenderTargetsRenderObserver = null;
  94301. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  94302. this._onBeforeAnimationsObserver = null;
  94303. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  94304. this._onBeforeParticlesRenderingObserver = null;
  94305. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  94306. this._onAfterParticlesRenderingObserver = null;
  94307. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  94308. this._onBeforeSpritesRenderingObserver = null;
  94309. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  94310. this._onAfterSpritesRenderingObserver = null;
  94311. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  94312. this._onBeforeDrawPhaseObserver = null;
  94313. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  94314. this._onAfterDrawPhaseObserver = null;
  94315. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  94316. this._onBeforePhysicsObserver = null;
  94317. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  94318. this._onAfterPhysicsObserver = null;
  94319. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  94320. this._onAfterAnimationsObserver = null;
  94321. this.scene = null;
  94322. };
  94323. return SceneInstrumentation;
  94324. }());
  94325. BABYLON.SceneInstrumentation = SceneInstrumentation;
  94326. })(BABYLON || (BABYLON = {}));
  94327. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  94328. "use strict";
  94329. var BABYLON;
  94330. (function (BABYLON) {
  94331. var _TimeToken = /** @class */ (function () {
  94332. function _TimeToken() {
  94333. this._timeElapsedQueryEnded = false;
  94334. }
  94335. return _TimeToken;
  94336. }());
  94337. BABYLON._TimeToken = _TimeToken;
  94338. })(BABYLON || (BABYLON = {}));
  94339. //# sourceMappingURL=babylon.timeToken.js.map
  94340. "use strict";
  94341. var BABYLON;
  94342. (function (BABYLON) {
  94343. /**
  94344. * Background material defines definition.
  94345. * @ignore Mainly internal Use
  94346. */
  94347. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  94348. __extends(BackgroundMaterialDefines, _super);
  94349. /**
  94350. * Constructor of the defines.
  94351. */
  94352. function BackgroundMaterialDefines() {
  94353. var _this = _super.call(this) || this;
  94354. /**
  94355. * True if the diffuse texture is in use.
  94356. */
  94357. _this.DIFFUSE = false;
  94358. /**
  94359. * The direct UV channel to use.
  94360. */
  94361. _this.DIFFUSEDIRECTUV = 0;
  94362. /**
  94363. * True if the diffuse texture is in gamma space.
  94364. */
  94365. _this.GAMMADIFFUSE = false;
  94366. /**
  94367. * True if the diffuse texture has opacity in the alpha channel.
  94368. */
  94369. _this.DIFFUSEHASALPHA = false;
  94370. /**
  94371. * True if you want the material to fade to transparent at grazing angle.
  94372. */
  94373. _this.OPACITYFRESNEL = false;
  94374. /**
  94375. * True if an extra blur needs to be added in the reflection.
  94376. */
  94377. _this.REFLECTIONBLUR = false;
  94378. /**
  94379. * True if you want the material to fade to reflection at grazing angle.
  94380. */
  94381. _this.REFLECTIONFRESNEL = false;
  94382. /**
  94383. * True if you want the material to falloff as far as you move away from the scene center.
  94384. */
  94385. _this.REFLECTIONFALLOFF = false;
  94386. /**
  94387. * False if the current Webgl implementation does not support the texture lod extension.
  94388. */
  94389. _this.TEXTURELODSUPPORT = false;
  94390. /**
  94391. * True to ensure the data are premultiplied.
  94392. */
  94393. _this.PREMULTIPLYALPHA = false;
  94394. /**
  94395. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  94396. */
  94397. _this.USERGBCOLOR = false;
  94398. /**
  94399. * True to add noise in order to reduce the banding effect.
  94400. */
  94401. _this.NOISE = false;
  94402. /**
  94403. * is the reflection texture in BGR color scheme?
  94404. * Mainly used to solve a bug in ios10 video tag
  94405. */
  94406. _this.REFLECTIONBGR = false;
  94407. _this.IMAGEPROCESSING = false;
  94408. _this.VIGNETTE = false;
  94409. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  94410. _this.VIGNETTEBLENDMODEOPAQUE = false;
  94411. _this.TONEMAPPING = false;
  94412. _this.CONTRAST = false;
  94413. _this.COLORCURVES = false;
  94414. _this.COLORGRADING = false;
  94415. _this.COLORGRADING3D = false;
  94416. _this.SAMPLER3DGREENDEPTH = false;
  94417. _this.SAMPLER3DBGRMAP = false;
  94418. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  94419. _this.EXPOSURE = false;
  94420. // Reflection.
  94421. _this.REFLECTION = false;
  94422. _this.REFLECTIONMAP_3D = false;
  94423. _this.REFLECTIONMAP_SPHERICAL = false;
  94424. _this.REFLECTIONMAP_PLANAR = false;
  94425. _this.REFLECTIONMAP_CUBIC = false;
  94426. _this.REFLECTIONMAP_PROJECTION = false;
  94427. _this.REFLECTIONMAP_SKYBOX = false;
  94428. _this.REFLECTIONMAP_EXPLICIT = false;
  94429. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  94430. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  94431. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  94432. _this.INVERTCUBICMAP = false;
  94433. _this.REFLECTIONMAP_OPPOSITEZ = false;
  94434. _this.LODINREFLECTIONALPHA = false;
  94435. _this.GAMMAREFLECTION = false;
  94436. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  94437. // Default BJS.
  94438. _this.MAINUV1 = false;
  94439. _this.MAINUV2 = false;
  94440. _this.UV1 = false;
  94441. _this.UV2 = false;
  94442. _this.CLIPPLANE = false;
  94443. _this.POINTSIZE = false;
  94444. _this.FOG = false;
  94445. _this.NORMAL = false;
  94446. _this.NUM_BONE_INFLUENCERS = 0;
  94447. _this.BonesPerMesh = 0;
  94448. _this.INSTANCES = false;
  94449. _this.SHADOWFLOAT = false;
  94450. _this.rebuild();
  94451. return _this;
  94452. }
  94453. return BackgroundMaterialDefines;
  94454. }(BABYLON.MaterialDefines));
  94455. /**
  94456. * Background material used to create an efficient environement around your scene.
  94457. */
  94458. var BackgroundMaterial = /** @class */ (function (_super) {
  94459. __extends(BackgroundMaterial, _super);
  94460. /**
  94461. * Instantiates a Background Material in the given scene
  94462. * @param name The friendly name of the material
  94463. * @param scene The scene to add the material to
  94464. */
  94465. function BackgroundMaterial(name, scene) {
  94466. var _this = _super.call(this, name, scene) || this;
  94467. /**
  94468. * Key light Color (multiply against the R channel of the environement texture)
  94469. */
  94470. _this.primaryColor = BABYLON.Color3.White();
  94471. /**
  94472. * Key light Level (allowing HDR output of the background)
  94473. */
  94474. _this.primaryLevel = 1;
  94475. /**
  94476. * Secondary light Color (multiply against the G channel of the environement texture)
  94477. */
  94478. _this.secondaryColor = BABYLON.Color3.Gray();
  94479. /**
  94480. * Secondary light Level (allowing HDR output of the background)
  94481. */
  94482. _this.secondaryLevel = 1;
  94483. /**
  94484. * Tertiary light Color (multiply against the B channel of the environement texture)
  94485. */
  94486. _this.tertiaryColor = BABYLON.Color3.Black();
  94487. /**
  94488. * Tertiary light Level (allowing HDR output of the background)
  94489. */
  94490. _this.tertiaryLevel = 1;
  94491. /**
  94492. * Reflection Texture used in the material.
  94493. * Should be author in a specific way for the best result (refer to the documentation).
  94494. */
  94495. _this.reflectionTexture = null;
  94496. /**
  94497. * Reflection Texture level of blur.
  94498. *
  94499. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  94500. * texture twice.
  94501. */
  94502. _this.reflectionBlur = 0;
  94503. /**
  94504. * Diffuse Texture used in the material.
  94505. * Should be author in a specific way for the best result (refer to the documentation).
  94506. */
  94507. _this.diffuseTexture = null;
  94508. _this._shadowLights = null;
  94509. /**
  94510. * Specify the list of lights casting shadow on the material.
  94511. * All scene shadow lights will be included if null.
  94512. */
  94513. _this.shadowLights = null;
  94514. /**
  94515. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  94516. * soft lighting on the background.
  94517. */
  94518. _this.shadowBlurScale = 1;
  94519. /**
  94520. * Helps adjusting the shadow to a softer level if required.
  94521. * 0 means black shadows and 1 means no shadows.
  94522. */
  94523. _this.shadowLevel = 0;
  94524. /**
  94525. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  94526. * It is usually zero but might be interesting to modify according to your setup.
  94527. */
  94528. _this.sceneCenter = BABYLON.Vector3.Zero();
  94529. /**
  94530. * This helps specifying that the material is falling off to the sky box at grazing angle.
  94531. * This helps ensuring a nice transition when the camera goes under the ground.
  94532. */
  94533. _this.opacityFresnel = true;
  94534. /**
  94535. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  94536. * This helps adding a mirror texture on the ground.
  94537. */
  94538. _this.reflectionFresnel = false;
  94539. /**
  94540. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  94541. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  94542. */
  94543. _this.reflectionFalloffDistance = 0.0;
  94544. /**
  94545. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  94546. */
  94547. _this.reflectionAmount = 1.0;
  94548. /**
  94549. * This specifies the weight of the reflection at grazing angle.
  94550. */
  94551. _this.reflectionReflectance0 = 0.05;
  94552. /**
  94553. * This specifies the weight of the reflection at a perpendicular point of view.
  94554. */
  94555. _this.reflectionReflectance90 = 0.5;
  94556. /**
  94557. * Helps to directly use the maps channels instead of their level.
  94558. */
  94559. _this.useRGBColor = true;
  94560. /**
  94561. * This helps reducing the banding effect that could occur on the background.
  94562. */
  94563. _this.enableNoise = false;
  94564. _this._fovMultiplier = 1.0;
  94565. /**
  94566. * Enable the FOV adjustment feature controlled by fovMultiplier.
  94567. */
  94568. _this.useEquirectangularFOV = false;
  94569. _this._maxSimultaneousLights = 4;
  94570. /**
  94571. * Number of Simultaneous lights allowed on the material.
  94572. */
  94573. _this.maxSimultaneousLights = 4;
  94574. /**
  94575. * Keep track of the image processing observer to allow dispose and replace.
  94576. */
  94577. _this._imageProcessingObserver = null;
  94578. /**
  94579. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  94580. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  94581. */
  94582. _this.switchToBGR = false;
  94583. // Temp values kept as cache in the material.
  94584. _this._renderTargets = new BABYLON.SmartArray(16);
  94585. _this._reflectionControls = BABYLON.Vector4.Zero();
  94586. // Setup the default processing configuration to the scene.
  94587. _this._attachImageProcessingConfiguration(null);
  94588. _this.getRenderTargetTextures = function () {
  94589. _this._renderTargets.reset();
  94590. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  94591. _this._renderTargets.push(_this._diffuseTexture);
  94592. }
  94593. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  94594. _this._renderTargets.push(_this._reflectionTexture);
  94595. }
  94596. return _this._renderTargets;
  94597. };
  94598. return _this;
  94599. }
  94600. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  94601. /**
  94602. * Sets the reflection reflectance fresnel values according to the default standard
  94603. * empirically know to work well :-)
  94604. */
  94605. set: function (value) {
  94606. var reflectionWeight = value;
  94607. if (reflectionWeight < 0.5) {
  94608. reflectionWeight = reflectionWeight * 2.0;
  94609. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  94610. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  94611. }
  94612. else {
  94613. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  94614. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  94615. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  94616. }
  94617. },
  94618. enumerable: true,
  94619. configurable: true
  94620. });
  94621. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  94622. /**
  94623. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  94624. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  94625. * Recommended to be keep at 1.0 except for special cases.
  94626. */
  94627. get: function () {
  94628. return this._fovMultiplier;
  94629. },
  94630. set: function (value) {
  94631. if (isNaN(value)) {
  94632. value = 1.0;
  94633. }
  94634. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  94635. },
  94636. enumerable: true,
  94637. configurable: true
  94638. });
  94639. /**
  94640. * Attaches a new image processing configuration to the PBR Material.
  94641. * @param configuration (if null the scene configuration will be use)
  94642. */
  94643. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  94644. var _this = this;
  94645. if (configuration === this._imageProcessingConfiguration) {
  94646. return;
  94647. }
  94648. // Detaches observer.
  94649. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  94650. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  94651. }
  94652. // Pick the scene configuration if needed.
  94653. if (!configuration) {
  94654. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  94655. }
  94656. else {
  94657. this._imageProcessingConfiguration = configuration;
  94658. }
  94659. // Attaches observer.
  94660. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  94661. _this._markAllSubMeshesAsImageProcessingDirty();
  94662. });
  94663. };
  94664. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  94665. /**
  94666. * Gets the image processing configuration used either in this material.
  94667. */
  94668. get: function () {
  94669. return this._imageProcessingConfiguration;
  94670. },
  94671. /**
  94672. * Sets the Default image processing configuration used either in the this material.
  94673. *
  94674. * If sets to null, the scene one is in use.
  94675. */
  94676. set: function (value) {
  94677. this._attachImageProcessingConfiguration(value);
  94678. // Ensure the effect will be rebuilt.
  94679. this._markAllSubMeshesAsTexturesDirty();
  94680. },
  94681. enumerable: true,
  94682. configurable: true
  94683. });
  94684. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  94685. /**
  94686. * Gets wether the color curves effect is enabled.
  94687. */
  94688. get: function () {
  94689. return this.imageProcessingConfiguration.colorCurvesEnabled;
  94690. },
  94691. /**
  94692. * Sets wether the color curves effect is enabled.
  94693. */
  94694. set: function (value) {
  94695. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  94696. },
  94697. enumerable: true,
  94698. configurable: true
  94699. });
  94700. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  94701. /**
  94702. * Gets wether the color grading effect is enabled.
  94703. */
  94704. get: function () {
  94705. return this.imageProcessingConfiguration.colorGradingEnabled;
  94706. },
  94707. /**
  94708. * Gets wether the color grading effect is enabled.
  94709. */
  94710. set: function (value) {
  94711. this.imageProcessingConfiguration.colorGradingEnabled = value;
  94712. },
  94713. enumerable: true,
  94714. configurable: true
  94715. });
  94716. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  94717. /**
  94718. * Gets wether tonemapping is enabled or not.
  94719. */
  94720. get: function () {
  94721. return this._imageProcessingConfiguration.toneMappingEnabled;
  94722. },
  94723. /**
  94724. * Sets wether tonemapping is enabled or not
  94725. */
  94726. set: function (value) {
  94727. this._imageProcessingConfiguration.toneMappingEnabled = value;
  94728. },
  94729. enumerable: true,
  94730. configurable: true
  94731. });
  94732. ;
  94733. ;
  94734. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  94735. /**
  94736. * The camera exposure used on this material.
  94737. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  94738. * This corresponds to a photographic exposure.
  94739. */
  94740. get: function () {
  94741. return this._imageProcessingConfiguration.exposure;
  94742. },
  94743. /**
  94744. * The camera exposure used on this material.
  94745. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  94746. * This corresponds to a photographic exposure.
  94747. */
  94748. set: function (value) {
  94749. this._imageProcessingConfiguration.exposure = value;
  94750. },
  94751. enumerable: true,
  94752. configurable: true
  94753. });
  94754. ;
  94755. ;
  94756. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  94757. /**
  94758. * Gets The camera contrast used on this material.
  94759. */
  94760. get: function () {
  94761. return this._imageProcessingConfiguration.contrast;
  94762. },
  94763. /**
  94764. * Sets The camera contrast used on this material.
  94765. */
  94766. set: function (value) {
  94767. this._imageProcessingConfiguration.contrast = value;
  94768. },
  94769. enumerable: true,
  94770. configurable: true
  94771. });
  94772. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  94773. /**
  94774. * Gets the Color Grading 2D Lookup Texture.
  94775. */
  94776. get: function () {
  94777. return this._imageProcessingConfiguration.colorGradingTexture;
  94778. },
  94779. /**
  94780. * Sets the Color Grading 2D Lookup Texture.
  94781. */
  94782. set: function (value) {
  94783. this.imageProcessingConfiguration.colorGradingTexture = value;
  94784. },
  94785. enumerable: true,
  94786. configurable: true
  94787. });
  94788. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  94789. /**
  94790. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  94791. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  94792. * 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;
  94793. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  94794. */
  94795. get: function () {
  94796. return this.imageProcessingConfiguration.colorCurves;
  94797. },
  94798. /**
  94799. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  94800. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  94801. * 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;
  94802. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  94803. */
  94804. set: function (value) {
  94805. this.imageProcessingConfiguration.colorCurves = value;
  94806. },
  94807. enumerable: true,
  94808. configurable: true
  94809. });
  94810. /**
  94811. * The entire material has been created in order to prevent overdraw.
  94812. * @returns false
  94813. */
  94814. BackgroundMaterial.prototype.needAlphaTesting = function () {
  94815. return true;
  94816. };
  94817. /**
  94818. * The entire material has been created in order to prevent overdraw.
  94819. * @returns true if blending is enable
  94820. */
  94821. BackgroundMaterial.prototype.needAlphaBlending = function () {
  94822. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  94823. };
  94824. /**
  94825. * Checks wether the material is ready to be rendered for a given mesh.
  94826. * @param mesh The mesh to render
  94827. * @param subMesh The submesh to check against
  94828. * @param useInstances Specify wether or not the material is used with instances
  94829. * @returns true if all the dependencies are ready (Textures, Effects...)
  94830. */
  94831. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  94832. var _this = this;
  94833. if (useInstances === void 0) { useInstances = false; }
  94834. if (subMesh.effect && this.isFrozen) {
  94835. if (this._wasPreviouslyReady) {
  94836. return true;
  94837. }
  94838. }
  94839. if (!subMesh._materialDefines) {
  94840. subMesh._materialDefines = new BackgroundMaterialDefines();
  94841. }
  94842. var scene = this.getScene();
  94843. var defines = subMesh._materialDefines;
  94844. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  94845. if (defines._renderId === scene.getRenderId()) {
  94846. return true;
  94847. }
  94848. }
  94849. var engine = scene.getEngine();
  94850. // Lights
  94851. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  94852. defines._needNormals = true;
  94853. // Textures
  94854. if (defines._areTexturesDirty) {
  94855. defines._needUVs = false;
  94856. if (scene.texturesEnabled) {
  94857. if (scene.getEngine().getCaps().textureLOD) {
  94858. defines.TEXTURELODSUPPORT = true;
  94859. }
  94860. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  94861. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  94862. return false;
  94863. }
  94864. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  94865. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  94866. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  94867. defines.OPACITYFRESNEL = this._opacityFresnel;
  94868. }
  94869. else {
  94870. defines.DIFFUSE = false;
  94871. defines.DIFFUSEHASALPHA = false;
  94872. defines.GAMMADIFFUSE = false;
  94873. defines.OPACITYFRESNEL = false;
  94874. }
  94875. var reflectionTexture = this._reflectionTexture;
  94876. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  94877. if (!reflectionTexture.isReadyOrNotBlocking()) {
  94878. return false;
  94879. }
  94880. defines.REFLECTION = true;
  94881. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  94882. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  94883. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  94884. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  94885. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  94886. defines.REFLECTIONBGR = this.switchToBGR;
  94887. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  94888. defines.INVERTCUBICMAP = true;
  94889. }
  94890. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  94891. switch (reflectionTexture.coordinatesMode) {
  94892. case BABYLON.Texture.CUBIC_MODE:
  94893. case BABYLON.Texture.INVCUBIC_MODE:
  94894. defines.REFLECTIONMAP_CUBIC = true;
  94895. break;
  94896. case BABYLON.Texture.EXPLICIT_MODE:
  94897. defines.REFLECTIONMAP_EXPLICIT = true;
  94898. break;
  94899. case BABYLON.Texture.PLANAR_MODE:
  94900. defines.REFLECTIONMAP_PLANAR = true;
  94901. break;
  94902. case BABYLON.Texture.PROJECTION_MODE:
  94903. defines.REFLECTIONMAP_PROJECTION = true;
  94904. break;
  94905. case BABYLON.Texture.SKYBOX_MODE:
  94906. defines.REFLECTIONMAP_SKYBOX = true;
  94907. break;
  94908. case BABYLON.Texture.SPHERICAL_MODE:
  94909. defines.REFLECTIONMAP_SPHERICAL = true;
  94910. break;
  94911. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  94912. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  94913. break;
  94914. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  94915. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  94916. break;
  94917. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  94918. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  94919. break;
  94920. }
  94921. if (this.reflectionFresnel) {
  94922. defines.REFLECTIONFRESNEL = true;
  94923. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  94924. this._reflectionControls.x = this.reflectionAmount;
  94925. this._reflectionControls.y = this.reflectionReflectance0;
  94926. this._reflectionControls.z = this.reflectionReflectance90;
  94927. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  94928. }
  94929. else {
  94930. defines.REFLECTIONFRESNEL = false;
  94931. defines.REFLECTIONFALLOFF = false;
  94932. }
  94933. }
  94934. else {
  94935. defines.REFLECTION = false;
  94936. defines.REFLECTIONFALLOFF = false;
  94937. defines.REFLECTIONBLUR = false;
  94938. defines.REFLECTIONMAP_3D = false;
  94939. defines.REFLECTIONMAP_SPHERICAL = false;
  94940. defines.REFLECTIONMAP_PLANAR = false;
  94941. defines.REFLECTIONMAP_CUBIC = false;
  94942. defines.REFLECTIONMAP_PROJECTION = false;
  94943. defines.REFLECTIONMAP_SKYBOX = false;
  94944. defines.REFLECTIONMAP_EXPLICIT = false;
  94945. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  94946. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  94947. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  94948. defines.INVERTCUBICMAP = false;
  94949. defines.REFLECTIONMAP_OPPOSITEZ = false;
  94950. defines.LODINREFLECTIONALPHA = false;
  94951. defines.GAMMAREFLECTION = false;
  94952. }
  94953. }
  94954. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  94955. defines.USERGBCOLOR = this._useRGBColor;
  94956. defines.NOISE = this._enableNoise;
  94957. }
  94958. if (defines._areImageProcessingDirty) {
  94959. if (!this._imageProcessingConfiguration.isReady()) {
  94960. return false;
  94961. }
  94962. this._imageProcessingConfiguration.prepareDefines(defines);
  94963. }
  94964. // Misc.
  94965. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  94966. // Values that need to be evaluated on every frame
  94967. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  94968. // Attribs
  94969. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  94970. if (mesh) {
  94971. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  94972. mesh.createNormals(true);
  94973. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  94974. }
  94975. }
  94976. }
  94977. // Get correct effect
  94978. if (defines.isDirty) {
  94979. defines.markAsProcessed();
  94980. scene.resetCachedMaterial();
  94981. // Fallbacks
  94982. var fallbacks = new BABYLON.EffectFallbacks();
  94983. if (defines.FOG) {
  94984. fallbacks.addFallback(0, "FOG");
  94985. }
  94986. if (defines.POINTSIZE) {
  94987. fallbacks.addFallback(1, "POINTSIZE");
  94988. }
  94989. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  94990. if (defines.NUM_BONE_INFLUENCERS > 0) {
  94991. fallbacks.addCPUSkinningFallback(0, mesh);
  94992. }
  94993. //Attributes
  94994. var attribs = [BABYLON.VertexBuffer.PositionKind];
  94995. if (defines.NORMAL) {
  94996. attribs.push(BABYLON.VertexBuffer.NormalKind);
  94997. }
  94998. if (defines.UV1) {
  94999. attribs.push(BABYLON.VertexBuffer.UVKind);
  95000. }
  95001. if (defines.UV2) {
  95002. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95003. }
  95004. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  95005. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  95006. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  95007. "vFogInfos", "vFogColor", "pointSize",
  95008. "vClipPlane", "mBones",
  95009. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  95010. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  95011. "shadowLevel", "alpha",
  95012. "vBackgroundCenter", "vReflectionControl",
  95013. "vDiffuseInfos", "diffuseMatrix",
  95014. ];
  95015. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  95016. var uniformBuffers = ["Material", "Scene"];
  95017. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  95018. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  95019. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  95020. uniformsNames: uniforms,
  95021. uniformBuffersNames: uniformBuffers,
  95022. samplers: samplers,
  95023. defines: defines,
  95024. maxSimultaneousLights: this._maxSimultaneousLights
  95025. });
  95026. var onCompiled = function (effect) {
  95027. if (_this.onCompiled) {
  95028. _this.onCompiled(effect);
  95029. }
  95030. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  95031. };
  95032. var join = defines.toString();
  95033. subMesh.setEffect(scene.getEngine().createEffect("background", {
  95034. attributes: attribs,
  95035. uniformsNames: uniforms,
  95036. uniformBuffersNames: uniformBuffers,
  95037. samplers: samplers,
  95038. defines: join,
  95039. fallbacks: fallbacks,
  95040. onCompiled: onCompiled,
  95041. onError: this.onError,
  95042. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  95043. }, engine), defines);
  95044. this.buildUniformLayout();
  95045. }
  95046. if (!subMesh.effect || !subMesh.effect.isReady()) {
  95047. return false;
  95048. }
  95049. defines._renderId = scene.getRenderId();
  95050. this._wasPreviouslyReady = true;
  95051. return true;
  95052. };
  95053. /**
  95054. * Build the uniform buffer used in the material.
  95055. */
  95056. BackgroundMaterial.prototype.buildUniformLayout = function () {
  95057. // Order is important !
  95058. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  95059. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  95060. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  95061. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  95062. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  95063. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  95064. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  95065. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  95066. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  95067. this._uniformBuffer.addUniform("pointSize", 1);
  95068. this._uniformBuffer.addUniform("shadowLevel", 1);
  95069. this._uniformBuffer.addUniform("alpha", 1);
  95070. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  95071. this._uniformBuffer.addUniform("vReflectionControl", 4);
  95072. this._uniformBuffer.create();
  95073. };
  95074. /**
  95075. * Unbind the material.
  95076. */
  95077. BackgroundMaterial.prototype.unbind = function () {
  95078. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  95079. this._uniformBuffer.setTexture("diffuseSampler", null);
  95080. }
  95081. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  95082. this._uniformBuffer.setTexture("reflectionSampler", null);
  95083. }
  95084. _super.prototype.unbind.call(this);
  95085. };
  95086. /**
  95087. * Bind only the world matrix to the material.
  95088. * @param world The world matrix to bind.
  95089. */
  95090. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  95091. this._activeEffect.setMatrix("world", world);
  95092. };
  95093. /**
  95094. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  95095. * @param world The world matrix to bind.
  95096. * @param subMesh The submesh to bind for.
  95097. */
  95098. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  95099. var scene = this.getScene();
  95100. var defines = subMesh._materialDefines;
  95101. if (!defines) {
  95102. return;
  95103. }
  95104. var effect = subMesh.effect;
  95105. if (!effect) {
  95106. return;
  95107. }
  95108. this._activeEffect = effect;
  95109. // Matrices
  95110. this.bindOnlyWorldMatrix(world);
  95111. // Bones
  95112. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  95113. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  95114. if (mustRebind) {
  95115. this._uniformBuffer.bindToEffect(effect, "Material");
  95116. this.bindViewProjection(effect);
  95117. var reflectionTexture = this._reflectionTexture;
  95118. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  95119. // Texture uniforms
  95120. if (scene.texturesEnabled) {
  95121. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  95122. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  95123. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  95124. }
  95125. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  95126. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  95127. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  95128. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  95129. }
  95130. }
  95131. if (this.shadowLevel > 0) {
  95132. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  95133. }
  95134. this._uniformBuffer.updateFloat("alpha", this.alpha);
  95135. // Point size
  95136. if (this.pointsCloud) {
  95137. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  95138. }
  95139. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  95140. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  95141. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  95142. }
  95143. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  95144. // Textures
  95145. if (scene.texturesEnabled) {
  95146. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  95147. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  95148. }
  95149. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  95150. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  95151. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  95152. }
  95153. else if (!defines.REFLECTIONBLUR) {
  95154. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  95155. }
  95156. else {
  95157. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  95158. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  95159. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  95160. }
  95161. if (defines.REFLECTIONFRESNEL) {
  95162. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  95163. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  95164. }
  95165. }
  95166. }
  95167. // Clip plane
  95168. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  95169. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  95170. }
  95171. if (mustRebind || !this.isFrozen) {
  95172. if (scene.lightsEnabled) {
  95173. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  95174. }
  95175. // View
  95176. this.bindView(effect);
  95177. // Fog
  95178. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  95179. // image processing
  95180. this._imageProcessingConfiguration.bind(this._activeEffect);
  95181. }
  95182. this._uniformBuffer.update();
  95183. this._afterBind(mesh);
  95184. };
  95185. /**
  95186. * Dispose the material.
  95187. * @param forceDisposeEffect Force disposal of the associated effect.
  95188. * @param forceDisposeTextures Force disposal of the associated textures.
  95189. */
  95190. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  95191. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  95192. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  95193. if (forceDisposeTextures) {
  95194. if (this.diffuseTexture) {
  95195. this.diffuseTexture.dispose();
  95196. }
  95197. if (this.reflectionTexture) {
  95198. this.reflectionTexture.dispose();
  95199. }
  95200. }
  95201. this._renderTargets.dispose();
  95202. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  95203. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  95204. }
  95205. _super.prototype.dispose.call(this, forceDisposeEffect);
  95206. };
  95207. /**
  95208. * Clones the material.
  95209. * @param name The cloned name.
  95210. * @returns The cloned material.
  95211. */
  95212. BackgroundMaterial.prototype.clone = function (name) {
  95213. var _this = this;
  95214. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  95215. };
  95216. /**
  95217. * Serializes the current material to its JSON representation.
  95218. * @returns The JSON representation.
  95219. */
  95220. BackgroundMaterial.prototype.serialize = function () {
  95221. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  95222. serializationObject.customType = "BABYLON.BackgroundMaterial";
  95223. return serializationObject;
  95224. };
  95225. /**
  95226. * Gets the class name of the material
  95227. * @returns "BackgroundMaterial"
  95228. */
  95229. BackgroundMaterial.prototype.getClassName = function () {
  95230. return "BackgroundMaterial";
  95231. };
  95232. /**
  95233. * Parse a JSON input to create back a background material.
  95234. * @param source The JSON data to parse
  95235. * @param scene The scene to create the parsed material in
  95236. * @param rootUrl The root url of the assets the material depends upon
  95237. * @returns the instantiated BackgroundMaterial.
  95238. */
  95239. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  95240. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  95241. };
  95242. /**
  95243. * Standard reflectance value at parallel view angle.
  95244. */
  95245. BackgroundMaterial.StandardReflectance0 = 0.05;
  95246. /**
  95247. * Standard reflectance value at grazing angle.
  95248. */
  95249. BackgroundMaterial.StandardReflectance90 = 0.5;
  95250. __decorate([
  95251. BABYLON.serializeAsColor3()
  95252. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  95253. __decorate([
  95254. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  95255. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  95256. __decorate([
  95257. BABYLON.serialize()
  95258. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  95259. __decorate([
  95260. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  95261. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  95262. __decorate([
  95263. BABYLON.serializeAsColor3()
  95264. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  95265. __decorate([
  95266. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  95267. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  95268. __decorate([
  95269. BABYLON.serialize()
  95270. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  95271. __decorate([
  95272. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  95273. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  95274. __decorate([
  95275. BABYLON.serializeAsColor3()
  95276. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  95277. __decorate([
  95278. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  95279. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  95280. __decorate([
  95281. BABYLON.serialize()
  95282. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  95283. __decorate([
  95284. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  95285. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  95286. __decorate([
  95287. BABYLON.serializeAsTexture()
  95288. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  95289. __decorate([
  95290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95291. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  95292. __decorate([
  95293. BABYLON.serialize()
  95294. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  95295. __decorate([
  95296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95297. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  95298. __decorate([
  95299. BABYLON.serializeAsTexture()
  95300. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  95301. __decorate([
  95302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95303. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  95304. __decorate([
  95305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95306. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  95307. __decorate([
  95308. BABYLON.serialize()
  95309. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  95310. __decorate([
  95311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95312. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  95313. __decorate([
  95314. BABYLON.serialize()
  95315. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  95316. __decorate([
  95317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95318. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  95319. __decorate([
  95320. BABYLON.serializeAsVector3()
  95321. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  95322. __decorate([
  95323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95324. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  95325. __decorate([
  95326. BABYLON.serialize()
  95327. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  95328. __decorate([
  95329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95330. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  95331. __decorate([
  95332. BABYLON.serialize()
  95333. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  95334. __decorate([
  95335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95336. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  95337. __decorate([
  95338. BABYLON.serialize()
  95339. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  95340. __decorate([
  95341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95342. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  95343. __decorate([
  95344. BABYLON.serialize()
  95345. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  95346. __decorate([
  95347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95348. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  95349. __decorate([
  95350. BABYLON.serialize()
  95351. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  95352. __decorate([
  95353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95354. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  95355. __decorate([
  95356. BABYLON.serialize()
  95357. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  95358. __decorate([
  95359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95360. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  95361. __decorate([
  95362. BABYLON.serialize()
  95363. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  95364. __decorate([
  95365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95366. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  95367. __decorate([
  95368. BABYLON.serialize()
  95369. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  95370. __decorate([
  95371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95372. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  95373. __decorate([
  95374. BABYLON.serialize()
  95375. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  95376. __decorate([
  95377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95378. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  95379. __decorate([
  95380. BABYLON.serializeAsImageProcessingConfiguration()
  95381. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  95382. return BackgroundMaterial;
  95383. }(BABYLON.PushMaterial));
  95384. BABYLON.BackgroundMaterial = BackgroundMaterial;
  95385. })(BABYLON || (BABYLON = {}));
  95386. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  95387. "use strict";
  95388. var __assign = (this && this.__assign) || Object.assign || function(t) {
  95389. for (var s, i = 1, n = arguments.length; i < n; i++) {
  95390. s = arguments[i];
  95391. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  95392. t[p] = s[p];
  95393. }
  95394. return t;
  95395. };
  95396. var BABYLON;
  95397. (function (BABYLON) {
  95398. /**
  95399. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  95400. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  95401. * It also helps with the default setup of your imageProcessing configuration.
  95402. */
  95403. var EnvironmentHelper = /** @class */ (function () {
  95404. /**
  95405. * constructor
  95406. * @param options
  95407. * @param scene The scene to add the material to
  95408. */
  95409. function EnvironmentHelper(options, scene) {
  95410. var _this = this;
  95411. this._errorHandler = function (message, exception) {
  95412. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  95413. };
  95414. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  95415. this._scene = scene;
  95416. this.onErrorObservable = new BABYLON.Observable();
  95417. this._setupBackground();
  95418. this._setupImageProcessing();
  95419. }
  95420. /**
  95421. * Creates the default options for the helper.
  95422. */
  95423. EnvironmentHelper._getDefaultOptions = function () {
  95424. return {
  95425. createGround: true,
  95426. groundSize: 15,
  95427. groundTexture: this._groundTextureCDNUrl,
  95428. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  95429. groundOpacity: 0.9,
  95430. enableGroundShadow: true,
  95431. groundShadowLevel: 0.5,
  95432. enableGroundMirror: false,
  95433. groundMirrorSizeRatio: 0.3,
  95434. groundMirrorBlurKernel: 64,
  95435. groundMirrorAmount: 1,
  95436. groundMirrorFresnelWeight: 1,
  95437. groundMirrorFallOffDistance: 0,
  95438. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  95439. groundYBias: 0.00001,
  95440. createSkybox: true,
  95441. skyboxSize: 20,
  95442. skyboxTexture: this._skyboxTextureCDNUrl,
  95443. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  95444. backgroundYRotation: 0,
  95445. sizeAuto: true,
  95446. rootPosition: BABYLON.Vector3.Zero(),
  95447. setupImageProcessing: true,
  95448. environmentTexture: this._environmentTextureCDNUrl,
  95449. cameraExposure: 0.8,
  95450. cameraContrast: 1.2,
  95451. toneMappingEnabled: true,
  95452. };
  95453. };
  95454. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  95455. /**
  95456. * Gets the root mesh created by the helper.
  95457. */
  95458. get: function () {
  95459. return this._rootMesh;
  95460. },
  95461. enumerable: true,
  95462. configurable: true
  95463. });
  95464. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  95465. /**
  95466. * Gets the skybox created by the helper.
  95467. */
  95468. get: function () {
  95469. return this._skybox;
  95470. },
  95471. enumerable: true,
  95472. configurable: true
  95473. });
  95474. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  95475. /**
  95476. * Gets the skybox texture created by the helper.
  95477. */
  95478. get: function () {
  95479. return this._skyboxTexture;
  95480. },
  95481. enumerable: true,
  95482. configurable: true
  95483. });
  95484. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  95485. /**
  95486. * Gets the skybox material created by the helper.
  95487. */
  95488. get: function () {
  95489. return this._skyboxMaterial;
  95490. },
  95491. enumerable: true,
  95492. configurable: true
  95493. });
  95494. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  95495. /**
  95496. * Gets the ground mesh created by the helper.
  95497. */
  95498. get: function () {
  95499. return this._ground;
  95500. },
  95501. enumerable: true,
  95502. configurable: true
  95503. });
  95504. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  95505. /**
  95506. * Gets the ground texture created by the helper.
  95507. */
  95508. get: function () {
  95509. return this._groundTexture;
  95510. },
  95511. enumerable: true,
  95512. configurable: true
  95513. });
  95514. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  95515. /**
  95516. * Gets the ground mirror created by the helper.
  95517. */
  95518. get: function () {
  95519. return this._groundMirror;
  95520. },
  95521. enumerable: true,
  95522. configurable: true
  95523. });
  95524. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  95525. /**
  95526. * Gets the ground mirror render list to helps pushing the meshes
  95527. * you wish in the ground reflection.
  95528. */
  95529. get: function () {
  95530. if (this._groundMirror) {
  95531. return this._groundMirror.renderList;
  95532. }
  95533. return null;
  95534. },
  95535. enumerable: true,
  95536. configurable: true
  95537. });
  95538. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  95539. /**
  95540. * Gets the ground material created by the helper.
  95541. */
  95542. get: function () {
  95543. return this._groundMaterial;
  95544. },
  95545. enumerable: true,
  95546. configurable: true
  95547. });
  95548. /**
  95549. * Updates the background according to the new options
  95550. * @param options
  95551. */
  95552. EnvironmentHelper.prototype.updateOptions = function (options) {
  95553. var newOptions = __assign({}, this._options, options);
  95554. if (this._ground && !newOptions.createGround) {
  95555. this._ground.dispose();
  95556. this._ground = null;
  95557. }
  95558. if (this._groundMaterial && !newOptions.createGround) {
  95559. this._groundMaterial.dispose();
  95560. this._groundMaterial = null;
  95561. }
  95562. if (this._groundTexture) {
  95563. if (this._options.groundTexture != newOptions.groundTexture) {
  95564. this._groundTexture.dispose();
  95565. this._groundTexture = null;
  95566. }
  95567. }
  95568. if (this._skybox && !newOptions.createSkybox) {
  95569. this._skybox.dispose();
  95570. this._skybox = null;
  95571. }
  95572. if (this._skyboxMaterial && !newOptions.createSkybox) {
  95573. this._skyboxMaterial.dispose();
  95574. this._skyboxMaterial = null;
  95575. }
  95576. if (this._skyboxTexture) {
  95577. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  95578. this._skyboxTexture.dispose();
  95579. this._skyboxTexture = null;
  95580. }
  95581. }
  95582. if (this._groundMirror && !newOptions.enableGroundMirror) {
  95583. this._groundMirror.dispose();
  95584. this._groundMirror = null;
  95585. }
  95586. if (this._scene.environmentTexture) {
  95587. if (this._options.environmentTexture != newOptions.environmentTexture) {
  95588. this._scene.environmentTexture.dispose();
  95589. }
  95590. }
  95591. this._options = newOptions;
  95592. this._setupBackground();
  95593. this._setupImageProcessing();
  95594. };
  95595. /**
  95596. * Sets the primary color of all the available elements.
  95597. * @param color
  95598. */
  95599. EnvironmentHelper.prototype.setMainColor = function (color) {
  95600. if (this.groundMaterial) {
  95601. this.groundMaterial.primaryColor = color;
  95602. }
  95603. if (this.skyboxMaterial) {
  95604. this.skyboxMaterial.primaryColor = color;
  95605. }
  95606. if (this.groundMirror) {
  95607. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  95608. }
  95609. };
  95610. /**
  95611. * Setup the image processing according to the specified options.
  95612. */
  95613. EnvironmentHelper.prototype._setupImageProcessing = function () {
  95614. if (this._options.setupImageProcessing) {
  95615. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  95616. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  95617. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  95618. this._setupEnvironmentTexture();
  95619. }
  95620. };
  95621. /**
  95622. * Setup the environment texture according to the specified options.
  95623. */
  95624. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  95625. if (this._scene.environmentTexture) {
  95626. return;
  95627. }
  95628. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  95629. this._scene.environmentTexture = this._options.environmentTexture;
  95630. return;
  95631. }
  95632. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  95633. this._scene.environmentTexture = environmentTexture;
  95634. };
  95635. /**
  95636. * Setup the background according to the specified options.
  95637. */
  95638. EnvironmentHelper.prototype._setupBackground = function () {
  95639. if (!this._rootMesh) {
  95640. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  95641. }
  95642. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  95643. var sceneSize = this._getSceneSize();
  95644. if (this._options.createGround) {
  95645. this._setupGround(sceneSize);
  95646. this._setupGroundMaterial();
  95647. this._setupGroundDiffuseTexture();
  95648. if (this._options.enableGroundMirror) {
  95649. this._setupGroundMirrorTexture(sceneSize);
  95650. }
  95651. this._setupMirrorInGroundMaterial();
  95652. }
  95653. if (this._options.createSkybox) {
  95654. this._setupSkybox(sceneSize);
  95655. this._setupSkyboxMaterial();
  95656. this._setupSkyboxReflectionTexture();
  95657. }
  95658. this._rootMesh.position.x = sceneSize.rootPosition.x;
  95659. this._rootMesh.position.z = sceneSize.rootPosition.z;
  95660. this._rootMesh.position.y = sceneSize.rootPosition.y;
  95661. };
  95662. /**
  95663. * Get the scene sizes according to the setup.
  95664. */
  95665. EnvironmentHelper.prototype._getSceneSize = function () {
  95666. var _this = this;
  95667. var groundSize = this._options.groundSize;
  95668. var skyboxSize = this._options.skyboxSize;
  95669. var rootPosition = this._options.rootPosition;
  95670. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  95671. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  95672. }
  95673. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  95674. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  95675. });
  95676. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  95677. if (this._options.sizeAuto) {
  95678. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  95679. this._scene.activeCamera.upperRadiusLimit) {
  95680. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  95681. skyboxSize = groundSize;
  95682. }
  95683. var sceneDiagonalLenght = sceneDiagonal.length();
  95684. if (sceneDiagonalLenght > groundSize) {
  95685. groundSize = sceneDiagonalLenght * 2;
  95686. skyboxSize = groundSize;
  95687. }
  95688. // 10 % bigger.
  95689. groundSize *= 1.1;
  95690. skyboxSize *= 1.5;
  95691. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  95692. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  95693. }
  95694. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  95695. };
  95696. /**
  95697. * Setup the ground according to the specified options.
  95698. */
  95699. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  95700. var _this = this;
  95701. if (!this._ground) {
  95702. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  95703. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  95704. this._ground.parent = this._rootMesh;
  95705. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  95706. }
  95707. this._ground.receiveShadows = this._options.enableGroundShadow;
  95708. };
  95709. /**
  95710. * Setup the ground material according to the specified options.
  95711. */
  95712. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  95713. if (!this._groundMaterial) {
  95714. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  95715. }
  95716. this._groundMaterial.alpha = this._options.groundOpacity;
  95717. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  95718. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  95719. this._groundMaterial.primaryLevel = 1;
  95720. this._groundMaterial.primaryColor = this._options.groundColor;
  95721. this._groundMaterial.secondaryLevel = 0;
  95722. this._groundMaterial.tertiaryLevel = 0;
  95723. this._groundMaterial.useRGBColor = false;
  95724. this._groundMaterial.enableNoise = true;
  95725. if (this._ground) {
  95726. this._ground.material = this._groundMaterial;
  95727. }
  95728. };
  95729. /**
  95730. * Setup the ground diffuse texture according to the specified options.
  95731. */
  95732. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  95733. if (!this._groundMaterial) {
  95734. return;
  95735. }
  95736. if (this._groundTexture) {
  95737. return;
  95738. }
  95739. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  95740. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  95741. return;
  95742. }
  95743. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  95744. diffuseTexture.gammaSpace = false;
  95745. diffuseTexture.hasAlpha = true;
  95746. this._groundMaterial.diffuseTexture = diffuseTexture;
  95747. };
  95748. /**
  95749. * Setup the ground mirror texture according to the specified options.
  95750. */
  95751. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  95752. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95753. if (!this._groundMirror) {
  95754. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  95755. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  95756. this._groundMirror.anisotropicFilteringLevel = 1;
  95757. this._groundMirror.wrapU = wrapping;
  95758. this._groundMirror.wrapV = wrapping;
  95759. this._groundMirror.gammaSpace = false;
  95760. if (this._groundMirror.renderList) {
  95761. for (var i = 0; i < this._scene.meshes.length; i++) {
  95762. var mesh = this._scene.meshes[i];
  95763. if (mesh !== this._ground &&
  95764. mesh !== this._skybox &&
  95765. mesh !== this._rootMesh) {
  95766. this._groundMirror.renderList.push(mesh);
  95767. }
  95768. }
  95769. }
  95770. }
  95771. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  95772. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  95773. };
  95774. /**
  95775. * Setup the ground to receive the mirror texture.
  95776. */
  95777. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  95778. if (this._groundMaterial) {
  95779. this._groundMaterial.reflectionTexture = this._groundMirror;
  95780. this._groundMaterial.reflectionFresnel = true;
  95781. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  95782. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  95783. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  95784. }
  95785. };
  95786. /**
  95787. * Setup the skybox according to the specified options.
  95788. */
  95789. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  95790. var _this = this;
  95791. if (!this._skybox) {
  95792. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  95793. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  95794. }
  95795. this._skybox.parent = this._rootMesh;
  95796. };
  95797. /**
  95798. * Setup the skybox material according to the specified options.
  95799. */
  95800. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  95801. if (!this._skybox) {
  95802. return;
  95803. }
  95804. if (!this._skyboxMaterial) {
  95805. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  95806. }
  95807. this._skyboxMaterial.useRGBColor = false;
  95808. this._skyboxMaterial.primaryLevel = 1;
  95809. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  95810. this._skyboxMaterial.secondaryLevel = 0;
  95811. this._skyboxMaterial.tertiaryLevel = 0;
  95812. this._skyboxMaterial.enableNoise = true;
  95813. this._skybox.material = this._skyboxMaterial;
  95814. };
  95815. /**
  95816. * Setup the skybox reflection texture according to the specified options.
  95817. */
  95818. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  95819. if (!this._skyboxMaterial) {
  95820. return;
  95821. }
  95822. if (this._skyboxTexture) {
  95823. return;
  95824. }
  95825. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  95826. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  95827. return;
  95828. }
  95829. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  95830. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  95831. this._skyboxTexture.gammaSpace = false;
  95832. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  95833. };
  95834. /**
  95835. * Dispose all the elements created by the Helper.
  95836. */
  95837. EnvironmentHelper.prototype.dispose = function () {
  95838. if (this._groundMaterial) {
  95839. this._groundMaterial.dispose(true, true);
  95840. }
  95841. if (this._skyboxMaterial) {
  95842. this._skyboxMaterial.dispose(true, true);
  95843. }
  95844. this._rootMesh.dispose(false);
  95845. };
  95846. /**
  95847. * Default ground texture URL.
  95848. */
  95849. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  95850. /**
  95851. * Default skybox texture URL.
  95852. */
  95853. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  95854. /**
  95855. * Default environment texture URL.
  95856. */
  95857. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  95858. return EnvironmentHelper;
  95859. }());
  95860. BABYLON.EnvironmentHelper = EnvironmentHelper;
  95861. })(BABYLON || (BABYLON = {}));
  95862. //# sourceMappingURL=babylon.environmentHelper.js.map
  95863. "use strict";
  95864. var BABYLON;
  95865. (function (BABYLON) {
  95866. /**
  95867. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  95868. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  95869. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  95870. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  95871. */
  95872. var VideoDome = /** @class */ (function (_super) {
  95873. __extends(VideoDome, _super);
  95874. /**
  95875. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  95876. * @param name Element's name, child elements will append suffixes for their own names.
  95877. * @param urlsOrVideo
  95878. * @param options An object containing optional or exposed sub element properties:
  95879. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  95880. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  95881. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  95882. * @param options **loop=true** Automatically loop video on end.
  95883. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  95884. */
  95885. function VideoDome(name, urlsOrVideo, options, scene) {
  95886. var _this = _super.call(this, name, scene) || this;
  95887. // set defaults and manage values
  95888. name = name || "videoDome";
  95889. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  95890. options.clickToPlay = Boolean(options.clickToPlay);
  95891. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  95892. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  95893. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  95894. // create
  95895. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  95896. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  95897. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  95898. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  95899. flat: false,
  95900. radius: options.size,
  95901. subdivisions: options.resolution,
  95902. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  95903. }, scene);
  95904. // configure material
  95905. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  95906. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  95907. material.reflectionTexture = _this._videoTexture;
  95908. material.useEquirectangularFOV = true;
  95909. material.fovMultiplier = 1.0;
  95910. // configure mesh
  95911. _this._mesh.material = material;
  95912. _this._mesh.parent = _this;
  95913. // optional configuration
  95914. if (options.clickToPlay) {
  95915. scene.onPointerUp = function () {
  95916. _this._videoTexture.video.play();
  95917. };
  95918. }
  95919. return _this;
  95920. }
  95921. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  95922. /**
  95923. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  95924. * Also see the options.resolution property.
  95925. */
  95926. get: function () {
  95927. return this._material.fovMultiplier;
  95928. },
  95929. set: function (value) {
  95930. this._material.fovMultiplier = value;
  95931. },
  95932. enumerable: true,
  95933. configurable: true
  95934. });
  95935. /**
  95936. * Releases resources associated with this node.
  95937. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  95938. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  95939. */
  95940. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  95941. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  95942. this._videoTexture.dispose();
  95943. this._mesh.dispose();
  95944. this._material.dispose();
  95945. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  95946. };
  95947. return VideoDome;
  95948. }(BABYLON.Node));
  95949. BABYLON.VideoDome = VideoDome;
  95950. })(BABYLON || (BABYLON = {}));
  95951. //# sourceMappingURL=babylon.videoDome.js.map
  95952. 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"};
  95953. 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};"};var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  95954. globalObject["BABYLON"] = BABYLON;
  95955. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var serializeAsCameraReference = BABYLON.serializeAsCameraReference;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var WorkerPool = BABYLON.WorkerPool;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var DepthTextureCreationOptions = BABYLON.DepthTextureCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationPropertiesOverride = BABYLON.AnimationPropertiesOverride;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var GPUParticleSystem = BABYLON.GPUParticleSystem;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var DracoCompression = BABYLON.DracoCompression;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var RawTexture3D = BABYLON.RawTexture3D;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var DaydreamController = BABYLON.DaydreamController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var ChromaticAberrationPostProcess = BABYLON.ChromaticAberrationPostProcess;var GrainPostProcess = BABYLON.GrainPostProcess;var SharpenPostProcess = BABYLON.SharpenPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var DepthOfFieldMergePostProcessOptions = BABYLON.DepthOfFieldMergePostProcessOptions;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var BloomMergePostProcess = BABYLON.BloomMergePostProcess;var ExtractHighlightsPostProcess = BABYLON.ExtractHighlightsPostProcess;var BloomEffect = BABYLON.BloomEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var NullEngineOptions = BABYLON.NullEngineOptions;var NullEngine = BABYLON.NullEngine;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var VideoDome = BABYLON.VideoDome;var Space = BABYLON.Space ;var Orientation = BABYLON.Orientation ;var AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation ;var WorkerTaskType = BABYLON.WorkerTaskType ;var WorkerReplyType = BABYLON.WorkerReplyType ;var Xbox360Button = BABYLON.Xbox360Button ;var Xbox360Dpad = BABYLON.Xbox360Dpad ;var PoseEnabledControllerType = BABYLON.PoseEnabledControllerType ;var DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel ;var TonemappingOperator = BABYLON.TonemappingOperator ;var PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff ;var PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode ;var Debug = BABYLON.Debug ;var JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;
  95956. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,serializeAsCameraReference,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,WorkerPool,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,DepthTextureCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationPropertiesOverride,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,GPUParticleSystem,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,DracoCompression,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,RawTexture3D,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,DaydreamController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,ChromaticAberrationPostProcess,GrainPostProcess,SharpenPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,DepthOfFieldMergePostProcessOptions,DepthOfFieldMergePostProcess,CircleOfConfusionPostProcess,DepthOfFieldEffect,BloomMergePostProcess,ExtractHighlightsPostProcess,BloomEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,VideoDome,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,Debug ,JoystickAxis ,SimplificationType ,AssetTaskState };