es6.js 4.5 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413
  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;
  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;
  189. this._attributesNames = attributesNamesOrOptions;
  190. this.onError = onError;
  191. this.onCompiled = onCompiled;
  192. this._indexParameters = indexParameters;
  193. this._fallbacks = fallbacks;
  194. }
  195. this.uniqueId = Effect._uniqueIdSeed++;
  196. var vertexSource;
  197. var fragmentSource;
  198. if (baseName.vertexElement) {
  199. vertexSource = document.getElementById(baseName.vertexElement);
  200. if (!vertexSource) {
  201. vertexSource = baseName.vertexElement;
  202. }
  203. }
  204. else {
  205. vertexSource = baseName.vertex || baseName;
  206. }
  207. if (baseName.fragmentElement) {
  208. fragmentSource = document.getElementById(baseName.fragmentElement);
  209. if (!fragmentSource) {
  210. fragmentSource = baseName.fragmentElement;
  211. }
  212. }
  213. else {
  214. fragmentSource = baseName.fragment || baseName;
  215. }
  216. this._loadVertexShader(vertexSource, function (vertexCode) {
  217. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  218. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  219. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  220. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  221. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  222. if (baseName) {
  223. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  224. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  225. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  226. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  227. }
  228. else {
  229. _this._vertexSourceCode = migratedVertexCode;
  230. _this._fragmentSourceCode = migratedFragmentCode;
  231. }
  232. _this._prepareEffect();
  233. });
  234. });
  235. });
  236. });
  237. });
  238. });
  239. }
  240. Object.defineProperty(Effect.prototype, "key", {
  241. /**
  242. * Unique key for this effect
  243. */
  244. get: function () {
  245. return this._key;
  246. },
  247. enumerable: true,
  248. configurable: true
  249. });
  250. /**
  251. * If the effect has been compiled and prepared.
  252. * @returns if the effect is compiled and prepared.
  253. */
  254. Effect.prototype.isReady = function () {
  255. return this._isReady;
  256. };
  257. /**
  258. * The engine the effect was initialized with.
  259. * @returns the engine.
  260. */
  261. Effect.prototype.getEngine = function () {
  262. return this._engine;
  263. };
  264. /**
  265. * The compiled webGL program for the effect
  266. * @returns the webGL program.
  267. */
  268. Effect.prototype.getProgram = function () {
  269. return this._program;
  270. };
  271. /**
  272. * The set of names of attribute variables for the shader.
  273. * @returns An array of attribute names.
  274. */
  275. Effect.prototype.getAttributesNames = function () {
  276. return this._attributesNames;
  277. };
  278. /**
  279. * Returns the attribute at the given index.
  280. * @param index The index of the attribute.
  281. * @returns The location of the attribute.
  282. */
  283. Effect.prototype.getAttributeLocation = function (index) {
  284. return this._attributes[index];
  285. };
  286. /**
  287. * Returns the attribute based on the name of the variable.
  288. * @param name of the attribute to look up.
  289. * @returns the attribute location.
  290. */
  291. Effect.prototype.getAttributeLocationByName = function (name) {
  292. var index = this._attributesNames.indexOf(name);
  293. return this._attributes[index];
  294. };
  295. /**
  296. * The number of attributes.
  297. * @returns the numnber of attributes.
  298. */
  299. Effect.prototype.getAttributesCount = function () {
  300. return this._attributes.length;
  301. };
  302. /**
  303. * Gets the index of a uniform variable.
  304. * @param uniformName of the uniform to look up.
  305. * @returns the index.
  306. */
  307. Effect.prototype.getUniformIndex = function (uniformName) {
  308. return this._uniformsNames.indexOf(uniformName);
  309. };
  310. /**
  311. * Returns the attribute based on the name of the variable.
  312. * @param uniformName of the uniform to look up.
  313. * @returns the location of the uniform.
  314. */
  315. Effect.prototype.getUniform = function (uniformName) {
  316. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  317. };
  318. /**
  319. * Returns an array of sampler variable names
  320. * @returns The array of sampler variable neames.
  321. */
  322. Effect.prototype.getSamplers = function () {
  323. return this._samplers;
  324. };
  325. /**
  326. * The error from the last compilation.
  327. * @returns the error string.
  328. */
  329. Effect.prototype.getCompilationError = function () {
  330. return this._compilationError;
  331. };
  332. /**
  333. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  334. * @param func The callback to be used.
  335. */
  336. Effect.prototype.executeWhenCompiled = function (func) {
  337. if (this.isReady()) {
  338. func(this);
  339. return;
  340. }
  341. this.onCompileObservable.add(function (effect) {
  342. func(effect);
  343. });
  344. };
  345. /** @ignore */
  346. Effect.prototype._loadVertexShader = function (vertex, callback) {
  347. if (BABYLON.Tools.IsWindowObjectExist()) {
  348. // DOM element ?
  349. if (vertex instanceof HTMLElement) {
  350. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  351. callback(vertexCode);
  352. return;
  353. }
  354. }
  355. // Base64 encoded ?
  356. if (vertex.substr(0, 7) === "base64:") {
  357. var vertexBinary = window.atob(vertex.substr(7));
  358. callback(vertexBinary);
  359. return;
  360. }
  361. // Is in local store ?
  362. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  363. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  364. return;
  365. }
  366. var vertexShaderUrl;
  367. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  368. vertexShaderUrl = vertex;
  369. }
  370. else {
  371. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  372. }
  373. // Vertex shader
  374. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  375. };
  376. /** @ignore */
  377. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  378. if (BABYLON.Tools.IsWindowObjectExist()) {
  379. // DOM element ?
  380. if (fragment instanceof HTMLElement) {
  381. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  382. callback(fragmentCode);
  383. return;
  384. }
  385. }
  386. // Base64 encoded ?
  387. if (fragment.substr(0, 7) === "base64:") {
  388. var fragmentBinary = window.atob(fragment.substr(7));
  389. callback(fragmentBinary);
  390. return;
  391. }
  392. // Is in local store ?
  393. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  394. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  395. return;
  396. }
  397. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  398. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  399. return;
  400. }
  401. var fragmentShaderUrl;
  402. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  403. fragmentShaderUrl = fragment;
  404. }
  405. else {
  406. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  407. }
  408. // Fragment shader
  409. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  410. };
  411. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  412. // Rebuild shaders source code
  413. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  414. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  415. vertexCode = prefix + vertexCode;
  416. fragmentCode = prefix + fragmentCode;
  417. // Number lines of shaders source code
  418. var i = 2;
  419. var regex = /\n/gm;
  420. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  421. i = 2;
  422. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  423. // Dump shaders name and formatted source code
  424. if (this.name.vertexElement) {
  425. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  426. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  427. }
  428. else if (this.name.vertex) {
  429. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  430. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  431. }
  432. else {
  433. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  434. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  435. }
  436. };
  437. ;
  438. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  439. var preparedSourceCode = this._processPrecision(sourceCode);
  440. if (this._engine.webGLVersion == 1) {
  441. callback(preparedSourceCode);
  442. return;
  443. }
  444. // Already converted
  445. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  446. callback(preparedSourceCode.replace("#version 300 es", ""));
  447. return;
  448. }
  449. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  450. // Remove extensions
  451. // #extension GL_OES_standard_derivatives : enable
  452. // #extension GL_EXT_shader_texture_lod : enable
  453. // #extension GL_EXT_frag_depth : enable
  454. // #extension GL_EXT_draw_buffers : require
  455. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  456. var result = preparedSourceCode.replace(regex, "");
  457. // Migrate to GLSL v300
  458. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  459. result = result.replace(/attribute[ \t]/g, "in ");
  460. result = result.replace(/[ \t]attribute/g, " in");
  461. if (isFragment) {
  462. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  463. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  464. result = result.replace(/texture2D\s*\(/g, "texture(");
  465. result = result.replace(/textureCube\s*\(/g, "texture(");
  466. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  467. result = result.replace(/gl_FragColor/g, "glFragColor");
  468. result = result.replace(/gl_FragData/g, "glFragData");
  469. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  470. }
  471. callback(result);
  472. };
  473. Effect.prototype._processIncludes = function (sourceCode, callback) {
  474. var _this = this;
  475. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  476. var match = regex.exec(sourceCode);
  477. var returnValue = new String(sourceCode);
  478. while (match != null) {
  479. var includeFile = match[1];
  480. // Uniform declaration
  481. if (includeFile.indexOf("__decl__") !== -1) {
  482. includeFile = includeFile.replace(/__decl__/, "");
  483. if (this._engine.supportsUniformBuffers) {
  484. includeFile = includeFile.replace(/Vertex/, "Ubo");
  485. includeFile = includeFile.replace(/Fragment/, "Ubo");
  486. }
  487. includeFile = includeFile + "Declaration";
  488. }
  489. if (Effect.IncludesShadersStore[includeFile]) {
  490. // Substitution
  491. var includeContent = Effect.IncludesShadersStore[includeFile];
  492. if (match[2]) {
  493. var splits = match[3].split(",");
  494. for (var index = 0; index < splits.length; index += 2) {
  495. var source = new RegExp(splits[index], "g");
  496. var dest = splits[index + 1];
  497. includeContent = includeContent.replace(source, dest);
  498. }
  499. }
  500. if (match[4]) {
  501. var indexString = match[5];
  502. if (indexString.indexOf("..") !== -1) {
  503. var indexSplits = indexString.split("..");
  504. var minIndex = parseInt(indexSplits[0]);
  505. var maxIndex = parseInt(indexSplits[1]);
  506. var sourceIncludeContent = includeContent.slice(0);
  507. includeContent = "";
  508. if (isNaN(maxIndex)) {
  509. maxIndex = this._indexParameters[indexSplits[1]];
  510. }
  511. for (var i = minIndex; i < maxIndex; i++) {
  512. if (!this._engine.supportsUniformBuffers) {
  513. // Ubo replacement
  514. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  515. return p1 + "{X}";
  516. });
  517. }
  518. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  519. }
  520. }
  521. else {
  522. if (!this._engine.supportsUniformBuffers) {
  523. // Ubo replacement
  524. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  525. return p1 + "{X}";
  526. });
  527. }
  528. includeContent = includeContent.replace(/\{X\}/g, indexString);
  529. }
  530. }
  531. // Replace
  532. returnValue = returnValue.replace(match[0], includeContent);
  533. }
  534. else {
  535. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  536. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  537. Effect.IncludesShadersStore[includeFile] = fileContent;
  538. _this._processIncludes(returnValue, callback);
  539. });
  540. return;
  541. }
  542. match = regex.exec(sourceCode);
  543. }
  544. callback(returnValue);
  545. };
  546. Effect.prototype._processPrecision = function (source) {
  547. if (source.indexOf("precision highp float") === -1) {
  548. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  549. source = "precision mediump float;\n" + source;
  550. }
  551. else {
  552. source = "precision highp float;\n" + source;
  553. }
  554. }
  555. else {
  556. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  557. source = source.replace("precision highp float", "precision mediump float");
  558. }
  559. }
  560. return source;
  561. };
  562. /**
  563. * Recompiles the webGL program
  564. * @param vertexSourceCode The source code for the vertex shader.
  565. * @param fragmentSourceCode The source code for the fragment shader.
  566. * @param onCompiled Callback called when completed.
  567. * @param onError Callback called on error.
  568. */
  569. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  570. var _this = this;
  571. this._isReady = false;
  572. this._vertexSourceCodeOverride = vertexSourceCode;
  573. this._fragmentSourceCodeOverride = fragmentSourceCode;
  574. this.onError = function (effect, error) {
  575. if (onError) {
  576. onError(error);
  577. }
  578. };
  579. this.onCompiled = function () {
  580. var scenes = _this.getEngine().scenes;
  581. for (var i = 0; i < scenes.length; i++) {
  582. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  583. }
  584. if (onCompiled) {
  585. onCompiled(_this._program);
  586. }
  587. };
  588. this._fallbacks = null;
  589. this._prepareEffect();
  590. };
  591. /**
  592. * Gets the uniform locations of the the specified variable names
  593. * @param names THe names of the variables to lookup.
  594. * @returns Array of locations in the same order as variable names.
  595. */
  596. Effect.prototype.getSpecificUniformLocations = function (names) {
  597. var engine = this._engine;
  598. return engine.getUniforms(this._program, names);
  599. };
  600. /**
  601. * Prepares the effect
  602. */
  603. Effect.prototype._prepareEffect = function () {
  604. var attributesNames = this._attributesNames;
  605. var defines = this.defines;
  606. var fallbacks = this._fallbacks;
  607. this._valueCache = {};
  608. var previousProgram = this._program;
  609. try {
  610. var engine = this._engine;
  611. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  612. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  613. }
  614. else {
  615. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  616. }
  617. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  618. if (engine.supportsUniformBuffers) {
  619. for (var name in this._uniformBuffersNames) {
  620. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  621. }
  622. }
  623. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  624. this._attributes = engine.getAttributes(this._program, attributesNames);
  625. var index;
  626. for (index = 0; index < this._samplers.length; index++) {
  627. var sampler = this.getUniform(this._samplers[index]);
  628. if (sampler == null) {
  629. this._samplers.splice(index, 1);
  630. index--;
  631. }
  632. }
  633. engine.bindSamplers(this);
  634. this._compilationError = "";
  635. this._isReady = true;
  636. if (this.onCompiled) {
  637. this.onCompiled(this);
  638. }
  639. this.onCompileObservable.notifyObservers(this);
  640. this.onCompileObservable.clear();
  641. // Unbind mesh reference in fallbacks
  642. if (this._fallbacks) {
  643. this._fallbacks.unBindMesh();
  644. }
  645. if (previousProgram) {
  646. this.getEngine()._deleteProgram(previousProgram);
  647. }
  648. }
  649. catch (e) {
  650. this._compilationError = e.message;
  651. // Let's go through fallbacks then
  652. BABYLON.Tools.Error("Unable to compile effect:");
  653. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  654. return " " + uniform;
  655. }));
  656. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  657. return " " + attribute;
  658. }));
  659. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  660. BABYLON.Tools.Error("Error: " + this._compilationError);
  661. if (previousProgram) {
  662. this._program = previousProgram;
  663. this._isReady = true;
  664. if (this.onError) {
  665. this.onError(this, this._compilationError);
  666. }
  667. this.onErrorObservable.notifyObservers(this);
  668. }
  669. if (fallbacks && fallbacks.isMoreFallbacks) {
  670. BABYLON.Tools.Error("Trying next fallback.");
  671. this.defines = fallbacks.reduce(this.defines, this);
  672. this._prepareEffect();
  673. }
  674. else {
  675. if (this.onError) {
  676. this.onError(this, this._compilationError);
  677. }
  678. this.onErrorObservable.notifyObservers(this);
  679. this.onErrorObservable.clear();
  680. // Unbind mesh reference in fallbacks
  681. if (this._fallbacks) {
  682. this._fallbacks.unBindMesh();
  683. }
  684. }
  685. }
  686. };
  687. Object.defineProperty(Effect.prototype, "isSupported", {
  688. /**
  689. * Checks if the effect is supported. (Must be called after compilation)
  690. */
  691. get: function () {
  692. return this._compilationError === "";
  693. },
  694. enumerable: true,
  695. configurable: true
  696. });
  697. /**
  698. * Binds a texture to the engine to be used as output of the shader.
  699. * @param channel Name of the output variable.
  700. * @param texture Texture to bind.
  701. */
  702. Effect.prototype._bindTexture = function (channel, texture) {
  703. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  704. };
  705. /**
  706. * Sets a texture on the engine to be used in the shader.
  707. * @param channel Name of the sampler variable.
  708. * @param texture Texture to set.
  709. */
  710. Effect.prototype.setTexture = function (channel, texture) {
  711. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  712. };
  713. /**
  714. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  715. * @param channel Name of the sampler variable.
  716. * @param texture Texture to set.
  717. */
  718. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  719. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  720. };
  721. /**
  722. * Sets an array of textures on the engine to be used in the shader.
  723. * @param channel Name of the variable.
  724. * @param textures Textures to set.
  725. */
  726. Effect.prototype.setTextureArray = function (channel, textures) {
  727. if (this._samplers.indexOf(channel + "Ex") === -1) {
  728. var initialPos = this._samplers.indexOf(channel);
  729. for (var index = 1; index < textures.length; index++) {
  730. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  731. }
  732. }
  733. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  734. };
  735. /**
  736. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  737. * @param channel Name of the sampler variable.
  738. * @param postProcess Post process to get the input texture from.
  739. */
  740. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  741. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  742. };
  743. /**
  744. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  745. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  746. * @param channel Name of the sampler variable.
  747. * @param postProcess Post process to get the output texture from.
  748. */
  749. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  750. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  751. };
  752. /** @ignore */
  753. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  754. var cache = this._valueCache[uniformName];
  755. var flag = matrix.updateFlag;
  756. if (cache !== undefined && cache === flag) {
  757. return false;
  758. }
  759. this._valueCache[uniformName] = flag;
  760. return true;
  761. };
  762. /** @ignore */
  763. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  764. var cache = this._valueCache[uniformName];
  765. if (!cache) {
  766. cache = [x, y];
  767. this._valueCache[uniformName] = cache;
  768. return true;
  769. }
  770. var changed = false;
  771. if (cache[0] !== x) {
  772. cache[0] = x;
  773. changed = true;
  774. }
  775. if (cache[1] !== y) {
  776. cache[1] = y;
  777. changed = true;
  778. }
  779. return changed;
  780. };
  781. /** @ignore */
  782. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  783. var cache = this._valueCache[uniformName];
  784. if (!cache) {
  785. cache = [x, y, z];
  786. this._valueCache[uniformName] = cache;
  787. return true;
  788. }
  789. var changed = false;
  790. if (cache[0] !== x) {
  791. cache[0] = x;
  792. changed = true;
  793. }
  794. if (cache[1] !== y) {
  795. cache[1] = y;
  796. changed = true;
  797. }
  798. if (cache[2] !== z) {
  799. cache[2] = z;
  800. changed = true;
  801. }
  802. return changed;
  803. };
  804. /** @ignore */
  805. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  806. var cache = this._valueCache[uniformName];
  807. if (!cache) {
  808. cache = [x, y, z, w];
  809. this._valueCache[uniformName] = cache;
  810. return true;
  811. }
  812. var changed = false;
  813. if (cache[0] !== x) {
  814. cache[0] = x;
  815. changed = true;
  816. }
  817. if (cache[1] !== y) {
  818. cache[1] = y;
  819. changed = true;
  820. }
  821. if (cache[2] !== z) {
  822. cache[2] = z;
  823. changed = true;
  824. }
  825. if (cache[3] !== w) {
  826. cache[3] = w;
  827. changed = true;
  828. }
  829. return changed;
  830. };
  831. /**
  832. * Binds a buffer to a uniform.
  833. * @param buffer Buffer to bind.
  834. * @param name Name of the uniform variable to bind to.
  835. */
  836. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  837. var bufferName = this._uniformBuffersNames[name];
  838. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  839. return;
  840. }
  841. Effect._baseCache[bufferName] = buffer;
  842. this._engine.bindUniformBufferBase(buffer, bufferName);
  843. };
  844. /**
  845. * Binds block to a uniform.
  846. * @param blockName Name of the block to bind.
  847. * @param index Index to bind.
  848. */
  849. Effect.prototype.bindUniformBlock = function (blockName, index) {
  850. this._engine.bindUniformBlock(this._program, blockName, index);
  851. };
  852. /**
  853. * Sets an interger value on a uniform variable.
  854. * @param uniformName Name of the variable.
  855. * @param value Value to be set.
  856. * @returns this effect.
  857. */
  858. Effect.prototype.setInt = function (uniformName, value) {
  859. var cache = this._valueCache[uniformName];
  860. if (cache !== undefined && cache === value)
  861. return this;
  862. this._valueCache[uniformName] = value;
  863. this._engine.setInt(this.getUniform(uniformName), value);
  864. return this;
  865. };
  866. /**
  867. * Sets an int array on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param array array to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setIntArray = function (uniformName, array) {
  873. this._valueCache[uniformName] = null;
  874. this._engine.setIntArray(this.getUniform(uniformName), array);
  875. return this;
  876. };
  877. /**
  878. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  879. * @param uniformName Name of the variable.
  880. * @param array array to be set.
  881. * @returns this effect.
  882. */
  883. Effect.prototype.setIntArray2 = function (uniformName, array) {
  884. this._valueCache[uniformName] = null;
  885. this._engine.setIntArray2(this.getUniform(uniformName), array);
  886. return this;
  887. };
  888. /**
  889. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  890. * @param uniformName Name of the variable.
  891. * @param array array to be set.
  892. * @returns this effect.
  893. */
  894. Effect.prototype.setIntArray3 = function (uniformName, array) {
  895. this._valueCache[uniformName] = null;
  896. this._engine.setIntArray3(this.getUniform(uniformName), array);
  897. return this;
  898. };
  899. /**
  900. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  901. * @param uniformName Name of the variable.
  902. * @param array array to be set.
  903. * @returns this effect.
  904. */
  905. Effect.prototype.setIntArray4 = function (uniformName, array) {
  906. this._valueCache[uniformName] = null;
  907. this._engine.setIntArray4(this.getUniform(uniformName), array);
  908. return this;
  909. };
  910. /**
  911. * Sets an float array on a uniform variable.
  912. * @param uniformName Name of the variable.
  913. * @param array array to be set.
  914. * @returns this effect.
  915. */
  916. Effect.prototype.setFloatArray = function (uniformName, array) {
  917. this._valueCache[uniformName] = null;
  918. this._engine.setFloatArray(this.getUniform(uniformName), array);
  919. return this;
  920. };
  921. /**
  922. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  923. * @param uniformName Name of the variable.
  924. * @param array array to be set.
  925. * @returns this effect.
  926. */
  927. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  928. this._valueCache[uniformName] = null;
  929. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  930. return this;
  931. };
  932. /**
  933. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  934. * @param uniformName Name of the variable.
  935. * @param array array to be set.
  936. * @returns this effect.
  937. */
  938. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  939. this._valueCache[uniformName] = null;
  940. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  941. return this;
  942. };
  943. /**
  944. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  945. * @param uniformName Name of the variable.
  946. * @param array array to be set.
  947. * @returns this effect.
  948. */
  949. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  950. this._valueCache[uniformName] = null;
  951. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  952. return this;
  953. };
  954. /**
  955. * Sets an array on a uniform variable.
  956. * @param uniformName Name of the variable.
  957. * @param array array to be set.
  958. * @returns this effect.
  959. */
  960. Effect.prototype.setArray = function (uniformName, array) {
  961. this._valueCache[uniformName] = null;
  962. this._engine.setArray(this.getUniform(uniformName), array);
  963. return this;
  964. };
  965. /**
  966. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  967. * @param uniformName Name of the variable.
  968. * @param array array to be set.
  969. * @returns this effect.
  970. */
  971. Effect.prototype.setArray2 = function (uniformName, array) {
  972. this._valueCache[uniformName] = null;
  973. this._engine.setArray2(this.getUniform(uniformName), array);
  974. return this;
  975. };
  976. /**
  977. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  978. * @param uniformName Name of the variable.
  979. * @param array array to be set.
  980. * @returns this effect.
  981. */
  982. Effect.prototype.setArray3 = function (uniformName, array) {
  983. this._valueCache[uniformName] = null;
  984. this._engine.setArray3(this.getUniform(uniformName), array);
  985. return this;
  986. };
  987. /**
  988. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  989. * @param uniformName Name of the variable.
  990. * @param array array to be set.
  991. * @returns this effect.
  992. */
  993. Effect.prototype.setArray4 = function (uniformName, array) {
  994. this._valueCache[uniformName] = null;
  995. this._engine.setArray4(this.getUniform(uniformName), array);
  996. return this;
  997. };
  998. /**
  999. * Sets matrices on a uniform variable.
  1000. * @param uniformName Name of the variable.
  1001. * @param matrices matrices to be set.
  1002. * @returns this effect.
  1003. */
  1004. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1005. if (!matrices) {
  1006. return this;
  1007. }
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrix on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrix matrix to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1019. if (this._cacheMatrix(uniformName, matrix)) {
  1020. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1021. }
  1022. return this;
  1023. };
  1024. /**
  1025. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1026. * @param uniformName Name of the variable.
  1027. * @param matrix matrix to be set.
  1028. * @returns this effect.
  1029. */
  1030. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1031. this._valueCache[uniformName] = null;
  1032. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1033. return this;
  1034. };
  1035. /**
  1036. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1037. * @param uniformName Name of the variable.
  1038. * @param matrix matrix to be set.
  1039. * @returns this effect.
  1040. */
  1041. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1042. this._valueCache[uniformName] = null;
  1043. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1044. return this;
  1045. };
  1046. /**
  1047. * Sets a float on a uniform variable.
  1048. * @param uniformName Name of the variable.
  1049. * @param value value to be set.
  1050. * @returns this effect.
  1051. */
  1052. Effect.prototype.setFloat = function (uniformName, value) {
  1053. var cache = this._valueCache[uniformName];
  1054. if (cache !== undefined && cache === value)
  1055. return this;
  1056. this._valueCache[uniformName] = value;
  1057. this._engine.setFloat(this.getUniform(uniformName), value);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a boolean on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param bool value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setBool = function (uniformName, bool) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === bool)
  1069. return this;
  1070. this._valueCache[uniformName] = bool;
  1071. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a Vector2 on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param vector2 vector2 to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1081. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1082. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1083. }
  1084. return this;
  1085. };
  1086. /**
  1087. * Sets a float2 on a uniform variable.
  1088. * @param uniformName Name of the variable.
  1089. * @param x First float in float2.
  1090. * @param y Second float in float2.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1094. if (this._cacheFloat2(uniformName, x, y)) {
  1095. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1096. }
  1097. return this;
  1098. };
  1099. /**
  1100. * Sets a Vector3 on a uniform variable.
  1101. * @param uniformName Name of the variable.
  1102. * @param vector3 Value to be set.
  1103. * @returns this effect.
  1104. */
  1105. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1106. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1107. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1108. }
  1109. return this;
  1110. };
  1111. /**
  1112. * Sets a float3 on a uniform variable.
  1113. * @param uniformName Name of the variable.
  1114. * @param x First float in float3.
  1115. * @param y Second float in float3.
  1116. * @param z Third float in float3.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1120. if (this._cacheFloat3(uniformName, x, y, z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a Vector4 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param vector4 Value to be set.
  1129. * @returns this effect.
  1130. */
  1131. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1132. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1133. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1134. }
  1135. return this;
  1136. };
  1137. /**
  1138. * Sets a float4 on a uniform variable.
  1139. * @param uniformName Name of the variable.
  1140. * @param x First float in float4.
  1141. * @param y Second float in float4.
  1142. * @param z Third float in float4.
  1143. * @param w Fourth float in float4.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1147. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1148. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a Color3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param color3 Value to be set.
  1156. * @returns this effect.
  1157. */
  1158. Effect.prototype.setColor3 = function (uniformName, color3) {
  1159. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1160. this._engine.setColor3(this.getUniform(uniformName), color3);
  1161. }
  1162. return this;
  1163. };
  1164. /**
  1165. * Sets a Color4 on a uniform variable.
  1166. * @param uniformName Name of the variable.
  1167. * @param color3 Value to be set.
  1168. * @param alpha Alpha value to be set.
  1169. * @returns this effect.
  1170. */
  1171. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1172. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1173. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1174. }
  1175. return this;
  1176. };
  1177. /**
  1178. * Sets a Color4 on a uniform variable
  1179. * @param uniformName defines the name of the variable
  1180. * @param color4 defines the value to be set
  1181. * @returns this effect.
  1182. */
  1183. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1184. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1185. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1186. }
  1187. return this;
  1188. };
  1189. /**
  1190. * Resets the cache of effects.
  1191. */
  1192. Effect.ResetCache = function () {
  1193. Effect._baseCache = {};
  1194. };
  1195. Effect._uniqueIdSeed = 0;
  1196. Effect._baseCache = {};
  1197. /**
  1198. * Store of each shader (The can be looked up using effect.key)
  1199. */
  1200. Effect.ShadersStore = {};
  1201. /**
  1202. * Store of each included file for a shader (The can be looked up using effect.key)
  1203. */
  1204. Effect.IncludesShadersStore = {};
  1205. return Effect;
  1206. }());
  1207. BABYLON.Effect = Effect;
  1208. })(BABYLON || (BABYLON = {}));
  1209. //# sourceMappingURL=babylon.effect.js.map
  1210. "use strict";
  1211. //# sourceMappingURL=babylon.types.js.map
  1212. "use strict";
  1213. var BABYLON;
  1214. (function (BABYLON) {
  1215. var KeyboardEventTypes = /** @class */ (function () {
  1216. function KeyboardEventTypes() {
  1217. }
  1218. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1219. get: function () {
  1220. return KeyboardEventTypes._KEYDOWN;
  1221. },
  1222. enumerable: true,
  1223. configurable: true
  1224. });
  1225. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1226. get: function () {
  1227. return KeyboardEventTypes._KEYUP;
  1228. },
  1229. enumerable: true,
  1230. configurable: true
  1231. });
  1232. KeyboardEventTypes._KEYDOWN = 0x01;
  1233. KeyboardEventTypes._KEYUP = 0x02;
  1234. return KeyboardEventTypes;
  1235. }());
  1236. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1237. var KeyboardInfo = /** @class */ (function () {
  1238. function KeyboardInfo(type, event) {
  1239. this.type = type;
  1240. this.event = event;
  1241. }
  1242. return KeyboardInfo;
  1243. }());
  1244. BABYLON.KeyboardInfo = KeyboardInfo;
  1245. /**
  1246. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1247. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1248. */
  1249. var KeyboardInfoPre = /** @class */ (function (_super) {
  1250. __extends(KeyboardInfoPre, _super);
  1251. function KeyboardInfoPre(type, event) {
  1252. var _this = _super.call(this, type, event) || this;
  1253. _this.skipOnPointerObservable = false;
  1254. return _this;
  1255. }
  1256. return KeyboardInfoPre;
  1257. }(KeyboardInfo));
  1258. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1261. "use strict";
  1262. var BABYLON;
  1263. (function (BABYLON) {
  1264. var PointerEventTypes = /** @class */ (function () {
  1265. function PointerEventTypes() {
  1266. }
  1267. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1268. get: function () {
  1269. return PointerEventTypes._POINTERDOWN;
  1270. },
  1271. enumerable: true,
  1272. configurable: true
  1273. });
  1274. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1275. get: function () {
  1276. return PointerEventTypes._POINTERUP;
  1277. },
  1278. enumerable: true,
  1279. configurable: true
  1280. });
  1281. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1282. get: function () {
  1283. return PointerEventTypes._POINTERMOVE;
  1284. },
  1285. enumerable: true,
  1286. configurable: true
  1287. });
  1288. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1289. get: function () {
  1290. return PointerEventTypes._POINTERWHEEL;
  1291. },
  1292. enumerable: true,
  1293. configurable: true
  1294. });
  1295. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1296. get: function () {
  1297. return PointerEventTypes._POINTERPICK;
  1298. },
  1299. enumerable: true,
  1300. configurable: true
  1301. });
  1302. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1303. get: function () {
  1304. return PointerEventTypes._POINTERTAP;
  1305. },
  1306. enumerable: true,
  1307. configurable: true
  1308. });
  1309. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1310. get: function () {
  1311. return PointerEventTypes._POINTERDOUBLETAP;
  1312. },
  1313. enumerable: true,
  1314. configurable: true
  1315. });
  1316. PointerEventTypes._POINTERDOWN = 0x01;
  1317. PointerEventTypes._POINTERUP = 0x02;
  1318. PointerEventTypes._POINTERMOVE = 0x04;
  1319. PointerEventTypes._POINTERWHEEL = 0x08;
  1320. PointerEventTypes._POINTERPICK = 0x10;
  1321. PointerEventTypes._POINTERTAP = 0x20;
  1322. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1323. return PointerEventTypes;
  1324. }());
  1325. BABYLON.PointerEventTypes = PointerEventTypes;
  1326. var PointerInfoBase = /** @class */ (function () {
  1327. function PointerInfoBase(type, event) {
  1328. this.type = type;
  1329. this.event = event;
  1330. }
  1331. return PointerInfoBase;
  1332. }());
  1333. BABYLON.PointerInfoBase = PointerInfoBase;
  1334. /**
  1335. * This class is used to store pointer related info for the onPrePointerObservable event.
  1336. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1337. */
  1338. var PointerInfoPre = /** @class */ (function (_super) {
  1339. __extends(PointerInfoPre, _super);
  1340. function PointerInfoPre(type, event, localX, localY) {
  1341. var _this = _super.call(this, type, event) || this;
  1342. _this.skipOnPointerObservable = false;
  1343. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1344. return _this;
  1345. }
  1346. return PointerInfoPre;
  1347. }(PointerInfoBase));
  1348. BABYLON.PointerInfoPre = PointerInfoPre;
  1349. /**
  1350. * This type contains all the data related to a pointer event in Babylon.js.
  1351. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1352. */
  1353. var PointerInfo = /** @class */ (function (_super) {
  1354. __extends(PointerInfo, _super);
  1355. function PointerInfo(type, event, pickInfo) {
  1356. var _this = _super.call(this, type, event) || this;
  1357. _this.pickInfo = pickInfo;
  1358. return _this;
  1359. }
  1360. return PointerInfo;
  1361. }(PointerInfoBase));
  1362. BABYLON.PointerInfo = PointerInfo;
  1363. })(BABYLON || (BABYLON = {}));
  1364. //# sourceMappingURL=babylon.pointerEvents.js.map
  1365. "use strict";
  1366. var BABYLON;
  1367. (function (BABYLON) {
  1368. BABYLON.ToGammaSpace = 1 / 2.2;
  1369. BABYLON.ToLinearSpace = 2.2;
  1370. BABYLON.Epsilon = 0.001;
  1371. /**
  1372. * Class used to hold a RBG color
  1373. */
  1374. var Color3 = /** @class */ (function () {
  1375. /**
  1376. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1377. * @param r defines the red component (between 0 and 1, default is 0)
  1378. * @param g defines the green component (between 0 and 1, default is 0)
  1379. * @param b defines the blue component (between 0 and 1, default is 0)
  1380. */
  1381. function Color3(
  1382. /**
  1383. * Defines the red component (between 0 and 1, default is 0)
  1384. */
  1385. r,
  1386. /**
  1387. * Defines the green component (between 0 and 1, default is 0)
  1388. */
  1389. g,
  1390. /**
  1391. * Defines the blue component (between 0 and 1, default is 0)
  1392. */
  1393. b) {
  1394. if (r === void 0) { r = 0; }
  1395. if (g === void 0) { g = 0; }
  1396. if (b === void 0) { b = 0; }
  1397. this.r = r;
  1398. this.g = g;
  1399. this.b = b;
  1400. }
  1401. /**
  1402. * Creates a string with the Color3 current values
  1403. * @returns the string representation of the Color3 object
  1404. */
  1405. Color3.prototype.toString = function () {
  1406. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1407. };
  1408. /**
  1409. * Returns the string "Color3"
  1410. * @returns "Color3"
  1411. */
  1412. Color3.prototype.getClassName = function () {
  1413. return "Color3";
  1414. };
  1415. /**
  1416. * Compute the Color3 hash code
  1417. * @returns an unique number that can be used to hash Color3 objects
  1418. */
  1419. Color3.prototype.getHashCode = function () {
  1420. var hash = this.r || 0;
  1421. hash = (hash * 397) ^ (this.g || 0);
  1422. hash = (hash * 397) ^ (this.b || 0);
  1423. return hash;
  1424. };
  1425. // Operators
  1426. /**
  1427. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1428. * @param array defines the array where to store the r,g,b components
  1429. * @param index defines an optional index in the target array to define where to start storing values
  1430. * @returns the current Color3 object
  1431. */
  1432. Color3.prototype.toArray = function (array, index) {
  1433. if (index === undefined) {
  1434. index = 0;
  1435. }
  1436. array[index] = this.r;
  1437. array[index + 1] = this.g;
  1438. array[index + 2] = this.b;
  1439. return this;
  1440. };
  1441. /**
  1442. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1443. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1444. * @returns a new {BABYLON.Color4} object
  1445. */
  1446. Color3.prototype.toColor4 = function (alpha) {
  1447. if (alpha === void 0) { alpha = 1; }
  1448. return new Color4(this.r, this.g, this.b, alpha);
  1449. };
  1450. /**
  1451. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1452. * @returns the new array
  1453. */
  1454. Color3.prototype.asArray = function () {
  1455. var result = new Array();
  1456. this.toArray(result, 0);
  1457. return result;
  1458. };
  1459. /**
  1460. * Returns the luminance value
  1461. * @returns a float value
  1462. */
  1463. Color3.prototype.toLuminance = function () {
  1464. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1465. };
  1466. /**
  1467. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1468. * @param otherColor defines the second operand
  1469. * @returns the new Color3 object
  1470. */
  1471. Color3.prototype.multiply = function (otherColor) {
  1472. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1473. };
  1474. /**
  1475. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1476. * @param otherColor defines the second operand
  1477. * @param result defines the Color3 object where to store the result
  1478. * @returns the current Color3
  1479. */
  1480. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1481. result.r = this.r * otherColor.r;
  1482. result.g = this.g * otherColor.g;
  1483. result.b = this.b * otherColor.b;
  1484. return this;
  1485. };
  1486. /**
  1487. * Determines equality between Color3 objects
  1488. * @param otherColor defines the second operand
  1489. * @returns true if the rgb values are equal to the passed ones
  1490. */
  1491. Color3.prototype.equals = function (otherColor) {
  1492. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1493. };
  1494. /**
  1495. * Determines equality between the current Color3 object and a set of r,b,g values
  1496. * @param r defines the red component to check
  1497. * @param g defines the green component to check
  1498. * @param b defines the blue component to check
  1499. * @returns true if the rgb values are equal to the passed ones
  1500. */
  1501. Color3.prototype.equalsFloats = function (r, g, b) {
  1502. return this.r === r && this.g === g && this.b === b;
  1503. };
  1504. /**
  1505. * Multiplies in place each rgb value by scale
  1506. * @param scale defines the scaling factor
  1507. * @returns the updated Color3
  1508. */
  1509. Color3.prototype.scale = function (scale) {
  1510. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1511. };
  1512. /**
  1513. * Multiplies the rgb values by scale and stores the result into "result"
  1514. * @param scale defines the scaling factor
  1515. * @param result defines the Color3 object where to store the result
  1516. * @returns the unmodified current Color3
  1517. */
  1518. Color3.prototype.scaleToRef = function (scale, result) {
  1519. result.r = this.r * scale;
  1520. result.g = this.g * scale;
  1521. result.b = this.b * scale;
  1522. return this;
  1523. };
  1524. /**
  1525. * Scale the current Color3 values by a factor and add the result to a given Color3
  1526. * @param scale defines the scale factor
  1527. * @param result defines color to store the result into
  1528. * @returns the unmodified current Color3
  1529. */
  1530. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1531. result.r += this.r * scale;
  1532. result.g += this.g * scale;
  1533. result.b += this.b * scale;
  1534. return this;
  1535. };
  1536. /**
  1537. * Clamps the rgb values by the min and max values and stores the result into "result"
  1538. * @param min defines minimum clamping value (default is 0)
  1539. * @param max defines maximum clamping value (default is 1)
  1540. * @param result defines color to store the result into
  1541. * @returns the original Color3
  1542. */
  1543. Color3.prototype.clampToRef = function (min, max, result) {
  1544. if (min === void 0) { min = 0; }
  1545. if (max === void 0) { max = 1; }
  1546. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1547. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1548. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1549. return this;
  1550. };
  1551. /**
  1552. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1553. * @param otherColor defines the second operand
  1554. * @returns the new Color3
  1555. */
  1556. Color3.prototype.add = function (otherColor) {
  1557. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1558. };
  1559. /**
  1560. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1561. * @param otherColor defines the second operand
  1562. * @param result defines Color3 object to store the result into
  1563. * @returns the unmodified current Color3
  1564. */
  1565. Color3.prototype.addToRef = function (otherColor, result) {
  1566. result.r = this.r + otherColor.r;
  1567. result.g = this.g + otherColor.g;
  1568. result.b = this.b + otherColor.b;
  1569. return this;
  1570. };
  1571. /**
  1572. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1573. * @param otherColor defines the second operand
  1574. * @returns the new Color3
  1575. */
  1576. Color3.prototype.subtract = function (otherColor) {
  1577. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1578. };
  1579. /**
  1580. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1581. * @param otherColor defines the second operand
  1582. * @param result defines Color3 object to store the result into
  1583. * @returns the unmodified current Color3
  1584. */
  1585. Color3.prototype.subtractToRef = function (otherColor, result) {
  1586. result.r = this.r - otherColor.r;
  1587. result.g = this.g - otherColor.g;
  1588. result.b = this.b - otherColor.b;
  1589. return this;
  1590. };
  1591. /**
  1592. * Copy the current object
  1593. * @returns a new Color3 copied the current one
  1594. */
  1595. Color3.prototype.clone = function () {
  1596. return new Color3(this.r, this.g, this.b);
  1597. };
  1598. /**
  1599. * Copies the rgb values from the source in the current Color3
  1600. * @param source defines the source Color3 object
  1601. * @returns the updated Color3 object
  1602. */
  1603. Color3.prototype.copyFrom = function (source) {
  1604. this.r = source.r;
  1605. this.g = source.g;
  1606. this.b = source.b;
  1607. return this;
  1608. };
  1609. /**
  1610. * Updates the Color3 rgb values from the passed floats
  1611. * @param r defines the red component to read from
  1612. * @param g defines the green component to read from
  1613. * @param b defines the blue component to read from
  1614. * @returns the current Color3 object
  1615. */
  1616. Color3.prototype.copyFromFloats = function (r, g, b) {
  1617. this.r = r;
  1618. this.g = g;
  1619. this.b = b;
  1620. return this;
  1621. };
  1622. /**
  1623. * Updates the Color3 rgb values from the passed floats
  1624. * @param r defines the red component to read from
  1625. * @param g defines the green component to read from
  1626. * @param b defines the blue component to read from
  1627. * @returns the current Color3 object
  1628. */
  1629. Color3.prototype.set = function (r, g, b) {
  1630. return this.copyFromFloats(r, g, b);
  1631. };
  1632. /**
  1633. * Compute the Color3 hexadecimal code as a string
  1634. * @returns a string containing the hexadecimal representation of the Color3 object
  1635. */
  1636. Color3.prototype.toHexString = function () {
  1637. var intR = (this.r * 255) | 0;
  1638. var intG = (this.g * 255) | 0;
  1639. var intB = (this.b * 255) | 0;
  1640. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1641. };
  1642. /**
  1643. * Computes a new Color3 converted from the current one to linear space
  1644. * @returns a new Color3 object
  1645. */
  1646. Color3.prototype.toLinearSpace = function () {
  1647. var convertedColor = new Color3();
  1648. this.toLinearSpaceToRef(convertedColor);
  1649. return convertedColor;
  1650. };
  1651. /**
  1652. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1653. * @param convertedColor defines the Color3 object where to store the linear space version
  1654. * @returns the unmodified Color3
  1655. */
  1656. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1657. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1658. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1659. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1660. return this;
  1661. };
  1662. /**
  1663. * Computes a new Color3 converted from the current one to gamma space
  1664. * @returns a new Color3 object
  1665. */
  1666. Color3.prototype.toGammaSpace = function () {
  1667. var convertedColor = new Color3();
  1668. this.toGammaSpaceToRef(convertedColor);
  1669. return convertedColor;
  1670. };
  1671. /**
  1672. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1673. * @param convertedColor defines the Color3 object where to store the gamma space version
  1674. * @returns the unmodified Color3
  1675. */
  1676. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1677. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1678. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1679. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1680. return this;
  1681. };
  1682. // Statics
  1683. /**
  1684. * Creates a new Color3 from the string containing valid hexadecimal values
  1685. * @param hex defines a string containing valid hexadecimal values
  1686. * @returns a new Color3 object
  1687. */
  1688. Color3.FromHexString = function (hex) {
  1689. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1690. return new Color3(0, 0, 0);
  1691. }
  1692. var r = parseInt(hex.substring(1, 3), 16);
  1693. var g = parseInt(hex.substring(3, 5), 16);
  1694. var b = parseInt(hex.substring(5, 7), 16);
  1695. return Color3.FromInts(r, g, b);
  1696. };
  1697. /**
  1698. * Creates a new Vector3 from the starting index of the passed array
  1699. * @param array defines the source array
  1700. * @param offset defines an offset in the source array
  1701. * @returns a new Color3 object
  1702. */
  1703. Color3.FromArray = function (array, offset) {
  1704. if (offset === void 0) { offset = 0; }
  1705. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1706. };
  1707. /**
  1708. * Creates a new Color3 from integer values (< 256)
  1709. * @param r defines the red component to read from (value between 0 and 255)
  1710. * @param g defines the green component to read from (value between 0 and 255)
  1711. * @param b defines the blue component to read from (value between 0 and 255)
  1712. * @returns a new Color3 object
  1713. */
  1714. Color3.FromInts = function (r, g, b) {
  1715. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1716. };
  1717. /**
  1718. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1719. * @param start defines the start Color3 value
  1720. * @param end defines the end Color3 value
  1721. * @param amount defines the gradient value between start and end
  1722. * @returns a new Color3 object
  1723. */
  1724. Color3.Lerp = function (start, end, amount) {
  1725. var r = start.r + ((end.r - start.r) * amount);
  1726. var g = start.g + ((end.g - start.g) * amount);
  1727. var b = start.b + ((end.b - start.b) * amount);
  1728. return new Color3(r, g, b);
  1729. };
  1730. /**
  1731. * Returns a Color3 value containing a red color
  1732. * @returns a new Color3 object
  1733. */
  1734. Color3.Red = function () { return new Color3(1, 0, 0); };
  1735. /**
  1736. * Returns a Color3 value containing a green color
  1737. * @returns a new Color3 object
  1738. */
  1739. Color3.Green = function () { return new Color3(0, 1, 0); };
  1740. /**
  1741. * Returns a Color3 value containing a blue color
  1742. * @returns a new Color3 object
  1743. */
  1744. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1745. /**
  1746. * Returns a Color3 value containing a black color
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.Black = function () { return new Color3(0, 0, 0); };
  1750. /**
  1751. * Returns a Color3 value containing a white color
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.White = function () { return new Color3(1, 1, 1); };
  1755. /**
  1756. * Returns a Color3 value containing a purple color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1760. /**
  1761. * Returns a Color3 value containing a magenta color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1765. /**
  1766. * Returns a Color3 value containing a yellow color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1770. /**
  1771. * Returns a Color3 value containing a gray color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1775. /**
  1776. * Returns a Color3 value containing a teal color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1780. /**
  1781. * Returns a Color3 value containing a random color
  1782. * @returns a new Color3 object
  1783. */
  1784. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1785. return Color3;
  1786. }());
  1787. BABYLON.Color3 = Color3;
  1788. /**
  1789. * Class used to hold a RBGA color
  1790. */
  1791. var Color4 = /** @class */ (function () {
  1792. /**
  1793. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1794. * @param r defines the red component (between 0 and 1, default is 0)
  1795. * @param g defines the green component (between 0 and 1, default is 0)
  1796. * @param b defines the blue component (between 0 and 1, default is 0)
  1797. * @param a defines the alpha component (between 0 and 1, default is 1)
  1798. */
  1799. function Color4(
  1800. /**
  1801. * Defines the red component (between 0 and 1, default is 0)
  1802. */
  1803. r,
  1804. /**
  1805. * Defines the green component (between 0 and 1, default is 0)
  1806. */
  1807. g,
  1808. /**
  1809. * Defines the blue component (between 0 and 1, default is 0)
  1810. */
  1811. b,
  1812. /**
  1813. * Defines the alpha component (between 0 and 1, default is 1)
  1814. */
  1815. a) {
  1816. if (r === void 0) { r = 0; }
  1817. if (g === void 0) { g = 0; }
  1818. if (b === void 0) { b = 0; }
  1819. if (a === void 0) { a = 1; }
  1820. this.r = r;
  1821. this.g = g;
  1822. this.b = b;
  1823. this.a = a;
  1824. }
  1825. // Operators
  1826. /**
  1827. * Adds in place the passed Color4 values to the current Color4 object
  1828. * @param right defines the second operand
  1829. * @returns the current updated Color4 object
  1830. */
  1831. Color4.prototype.addInPlace = function (right) {
  1832. this.r += right.r;
  1833. this.g += right.g;
  1834. this.b += right.b;
  1835. this.a += right.a;
  1836. return this;
  1837. };
  1838. /**
  1839. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1840. * @returns the new array
  1841. */
  1842. Color4.prototype.asArray = function () {
  1843. var result = new Array();
  1844. this.toArray(result, 0);
  1845. return result;
  1846. };
  1847. /**
  1848. * Stores from the starting index in the passed array the Color4 successive values
  1849. * @param array defines the array where to store the r,g,b components
  1850. * @param index defines an optional index in the target array to define where to start storing values
  1851. * @returns the current Color4 object
  1852. */
  1853. Color4.prototype.toArray = function (array, index) {
  1854. if (index === undefined) {
  1855. index = 0;
  1856. }
  1857. array[index] = this.r;
  1858. array[index + 1] = this.g;
  1859. array[index + 2] = this.b;
  1860. array[index + 3] = this.a;
  1861. return this;
  1862. };
  1863. /**
  1864. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1865. * @param right defines the second operand
  1866. * @returns a new Color4 object
  1867. */
  1868. Color4.prototype.add = function (right) {
  1869. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1870. };
  1871. /**
  1872. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1873. * @param right defines the second operand
  1874. * @returns a new Color4 object
  1875. */
  1876. Color4.prototype.subtract = function (right) {
  1877. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1878. };
  1879. /**
  1880. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1881. * @param right defines the second operand
  1882. * @param result defines the Color4 object where to store the result
  1883. * @returns the current Color4 object
  1884. */
  1885. Color4.prototype.subtractToRef = function (right, result) {
  1886. result.r = this.r - right.r;
  1887. result.g = this.g - right.g;
  1888. result.b = this.b - right.b;
  1889. result.a = this.a - right.a;
  1890. return this;
  1891. };
  1892. /**
  1893. * Creates a new Color4 with the current Color4 values multiplied by scale
  1894. * @param scale defines the scaling factor to apply
  1895. * @returns a new Color4 object
  1896. */
  1897. Color4.prototype.scale = function (scale) {
  1898. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1899. };
  1900. /**
  1901. * Multiplies the current Color4 values by scale and stores the result in "result"
  1902. * @param scale defines the scaling factor to apply
  1903. * @param result defines the Color4 object where to store the result
  1904. * @returns the current unmodified Color4
  1905. */
  1906. Color4.prototype.scaleToRef = function (scale, result) {
  1907. result.r = this.r * scale;
  1908. result.g = this.g * scale;
  1909. result.b = this.b * scale;
  1910. result.a = this.a * scale;
  1911. return this;
  1912. };
  1913. /**
  1914. * Scale the current Color4 values by a factor and add the result to a given Color4
  1915. * @param scale defines the scale factor
  1916. * @param result defines the Color4 object where to store the result
  1917. * @returns the unmodified current Color4
  1918. */
  1919. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1920. result.r += this.r * scale;
  1921. result.g += this.g * scale;
  1922. result.b += this.b * scale;
  1923. result.a += this.a * scale;
  1924. return this;
  1925. };
  1926. /**
  1927. * Clamps the rgb values by the min and max values and stores the result into "result"
  1928. * @param min defines minimum clamping value (default is 0)
  1929. * @param max defines maximum clamping value (default is 1)
  1930. * @param result defines color to store the result into.
  1931. * @returns the cuurent Color4
  1932. */
  1933. Color4.prototype.clampToRef = function (min, max, result) {
  1934. if (min === void 0) { min = 0; }
  1935. if (max === void 0) { max = 1; }
  1936. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1937. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1938. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1939. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1940. return this;
  1941. };
  1942. /**
  1943. * Multipy an Color4 value by another and return a new Color4 object
  1944. * @param color defines the Color4 value to multiply by
  1945. * @returns a new Color4 object
  1946. */
  1947. Color4.prototype.multiply = function (color) {
  1948. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1949. };
  1950. /**
  1951. * Multipy a Color4 value by another and push the result in a reference value
  1952. * @param color defines the Color4 value to multiply by
  1953. * @param result defines the Color4 to fill the result in
  1954. * @returns the result Color4
  1955. */
  1956. Color4.prototype.multiplyToRef = function (color, result) {
  1957. result.r = this.r * color.r;
  1958. result.g = this.g * color.g;
  1959. result.b = this.b * color.b;
  1960. result.a = this.a * color.a;
  1961. return result;
  1962. };
  1963. /**
  1964. * Creates a string with the Color4 current values
  1965. * @returns the string representation of the Color4 object
  1966. */
  1967. Color4.prototype.toString = function () {
  1968. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1969. };
  1970. /**
  1971. * Returns the string "Color4"
  1972. * @returns "Color4"
  1973. */
  1974. Color4.prototype.getClassName = function () {
  1975. return "Color4";
  1976. };
  1977. /**
  1978. * Compute the Color4 hash code
  1979. * @returns an unique number that can be used to hash Color4 objects
  1980. */
  1981. Color4.prototype.getHashCode = function () {
  1982. var hash = this.r || 0;
  1983. hash = (hash * 397) ^ (this.g || 0);
  1984. hash = (hash * 397) ^ (this.b || 0);
  1985. hash = (hash * 397) ^ (this.a || 0);
  1986. return hash;
  1987. };
  1988. /**
  1989. * Creates a new Color4 copied from the current one
  1990. * @returns a new Color4 object
  1991. */
  1992. Color4.prototype.clone = function () {
  1993. return new Color4(this.r, this.g, this.b, this.a);
  1994. };
  1995. /**
  1996. * Copies the passed Color4 values into the current one
  1997. * @param source defines the source Color4 object
  1998. * @returns the current updated Color4 object
  1999. */
  2000. Color4.prototype.copyFrom = function (source) {
  2001. this.r = source.r;
  2002. this.g = source.g;
  2003. this.b = source.b;
  2004. this.a = source.a;
  2005. return this;
  2006. };
  2007. /**
  2008. * Copies the passed float values into the current one
  2009. * @param r defines the red component to read from
  2010. * @param g defines the green component to read from
  2011. * @param b defines the blue component to read from
  2012. * @param a defines the alpha component to read from
  2013. * @returns the current updated Color4 object
  2014. */
  2015. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2016. this.r = r;
  2017. this.g = g;
  2018. this.b = b;
  2019. this.a = a;
  2020. return this;
  2021. };
  2022. /**
  2023. * Copies the passed float values into the current one
  2024. * @param r defines the red component to read from
  2025. * @param g defines the green component to read from
  2026. * @param b defines the blue component to read from
  2027. * @param a defines the alpha component to read from
  2028. * @returns the current updated Color4 object
  2029. */
  2030. Color4.prototype.set = function (r, g, b, a) {
  2031. return this.copyFromFloats(r, g, b, a);
  2032. };
  2033. /**
  2034. * Compute the Color4 hexadecimal code as a string
  2035. * @returns a string containing the hexadecimal representation of the Color4 object
  2036. */
  2037. Color4.prototype.toHexString = function () {
  2038. var intR = (this.r * 255) | 0;
  2039. var intG = (this.g * 255) | 0;
  2040. var intB = (this.b * 255) | 0;
  2041. var intA = (this.a * 255) | 0;
  2042. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2043. };
  2044. /**
  2045. * Computes a new Color4 converted from the current one to linear space
  2046. * @returns a new Color4 object
  2047. */
  2048. Color4.prototype.toLinearSpace = function () {
  2049. var convertedColor = new Color4();
  2050. this.toLinearSpaceToRef(convertedColor);
  2051. return convertedColor;
  2052. };
  2053. /**
  2054. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2055. * @param convertedColor defines the Color4 object where to store the linear space version
  2056. * @returns the unmodified Color4
  2057. */
  2058. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2059. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2060. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2061. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2062. convertedColor.a = this.a;
  2063. return this;
  2064. };
  2065. /**
  2066. * Computes a new Color4 converted from the current one to gamma space
  2067. * @returns a new Color4 object
  2068. */
  2069. Color4.prototype.toGammaSpace = function () {
  2070. var convertedColor = new Color4();
  2071. this.toGammaSpaceToRef(convertedColor);
  2072. return convertedColor;
  2073. };
  2074. /**
  2075. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2076. * @param convertedColor defines the Color4 object where to store the gamma space version
  2077. * @returns the unmodified Color4
  2078. */
  2079. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2080. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2081. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2082. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2083. convertedColor.a = this.a;
  2084. return this;
  2085. };
  2086. // Statics
  2087. /**
  2088. * Creates a new Color4 from the string containing valid hexadecimal values
  2089. * @param hex defines a string containing valid hexadecimal values
  2090. * @returns a new Color4 object
  2091. */
  2092. Color4.FromHexString = function (hex) {
  2093. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2094. return new Color4(0.0, 0.0, 0.0, 0.0);
  2095. }
  2096. var r = parseInt(hex.substring(1, 3), 16);
  2097. var g = parseInt(hex.substring(3, 5), 16);
  2098. var b = parseInt(hex.substring(5, 7), 16);
  2099. var a = parseInt(hex.substring(7, 9), 16);
  2100. return Color4.FromInts(r, g, b, a);
  2101. };
  2102. /**
  2103. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2104. * @param left defines the start value
  2105. * @param right defines the end value
  2106. * @param amount defines the gradient factor
  2107. * @returns a new Color4 object
  2108. */
  2109. Color4.Lerp = function (left, right, amount) {
  2110. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2111. Color4.LerpToRef(left, right, amount, result);
  2112. return result;
  2113. };
  2114. /**
  2115. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2116. * @param left defines the start value
  2117. * @param right defines the end value
  2118. * @param amount defines the gradient factor
  2119. * @param result defines the Color4 object where to store data
  2120. */
  2121. Color4.LerpToRef = function (left, right, amount, result) {
  2122. result.r = left.r + (right.r - left.r) * amount;
  2123. result.g = left.g + (right.g - left.g) * amount;
  2124. result.b = left.b + (right.b - left.b) * amount;
  2125. result.a = left.a + (right.a - left.a) * amount;
  2126. };
  2127. /**
  2128. * Creates a new Color4 from the starting index element of the passed array
  2129. * @param array defines the source array to read from
  2130. * @param offset defines the offset in the source array
  2131. * @returns a new Color4 object
  2132. */
  2133. Color4.FromArray = function (array, offset) {
  2134. if (offset === void 0) { offset = 0; }
  2135. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2136. };
  2137. /**
  2138. * Creates a new Color3 from integer values (< 256)
  2139. * @param r defines the red component to read from (value between 0 and 255)
  2140. * @param g defines the green component to read from (value between 0 and 255)
  2141. * @param b defines the blue component to read from (value between 0 and 255)
  2142. * @param a defines the alpha component to read from (value between 0 and 255)
  2143. * @returns a new Color3 object
  2144. */
  2145. Color4.FromInts = function (r, g, b, a) {
  2146. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2147. };
  2148. /**
  2149. * Check the content of a given array and convert it to an array containing RGBA data
  2150. * If the original array was already containing count * 4 values then it is returned directly
  2151. * @param colors defines the array to check
  2152. * @param count defines the number of RGBA data to expect
  2153. * @returns an array containing count * 4 values (RGBA)
  2154. */
  2155. Color4.CheckColors4 = function (colors, count) {
  2156. // Check if color3 was used
  2157. if (colors.length === count * 3) {
  2158. var colors4 = [];
  2159. for (var index = 0; index < colors.length; index += 3) {
  2160. var newIndex = (index / 3) * 4;
  2161. colors4[newIndex] = colors[index];
  2162. colors4[newIndex + 1] = colors[index + 1];
  2163. colors4[newIndex + 2] = colors[index + 2];
  2164. colors4[newIndex + 3] = 1.0;
  2165. }
  2166. return colors4;
  2167. }
  2168. return colors;
  2169. };
  2170. return Color4;
  2171. }());
  2172. BABYLON.Color4 = Color4;
  2173. var Vector2 = /** @class */ (function () {
  2174. /**
  2175. * Creates a new Vector2 from the passed x and y coordinates.
  2176. */
  2177. function Vector2(x, y) {
  2178. this.x = x;
  2179. this.y = y;
  2180. }
  2181. /**
  2182. * Returns a string with the Vector2 coordinates.
  2183. */
  2184. Vector2.prototype.toString = function () {
  2185. return "{X: " + this.x + " Y:" + this.y + "}";
  2186. };
  2187. /**
  2188. * Returns the string "Vector2"
  2189. */
  2190. Vector2.prototype.getClassName = function () {
  2191. return "Vector2";
  2192. };
  2193. /**
  2194. * Returns the Vector2 hash code as a number.
  2195. */
  2196. Vector2.prototype.getHashCode = function () {
  2197. var hash = this.x || 0;
  2198. hash = (hash * 397) ^ (this.y || 0);
  2199. return hash;
  2200. };
  2201. // Operators
  2202. /**
  2203. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2204. * Returns the Vector2.
  2205. */
  2206. Vector2.prototype.toArray = function (array, index) {
  2207. if (index === void 0) { index = 0; }
  2208. array[index] = this.x;
  2209. array[index + 1] = this.y;
  2210. return this;
  2211. };
  2212. /**
  2213. * Returns a new array with 2 elements : the Vector2 coordinates.
  2214. */
  2215. Vector2.prototype.asArray = function () {
  2216. var result = new Array();
  2217. this.toArray(result, 0);
  2218. return result;
  2219. };
  2220. /**
  2221. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2222. * Returns the updated Vector2.
  2223. */
  2224. Vector2.prototype.copyFrom = function (source) {
  2225. this.x = source.x;
  2226. this.y = source.y;
  2227. return this;
  2228. };
  2229. /**
  2230. * Sets the Vector2 coordinates with the passed floats.
  2231. * Returns the updated Vector2.
  2232. */
  2233. Vector2.prototype.copyFromFloats = function (x, y) {
  2234. this.x = x;
  2235. this.y = y;
  2236. return this;
  2237. };
  2238. /**
  2239. * Sets the Vector2 coordinates with the passed floats.
  2240. * Returns the updated Vector2.
  2241. */
  2242. Vector2.prototype.set = function (x, y) {
  2243. return this.copyFromFloats(x, y);
  2244. };
  2245. /**
  2246. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2247. */
  2248. Vector2.prototype.add = function (otherVector) {
  2249. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2250. };
  2251. /**
  2252. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2253. * Returns the Vector2.
  2254. */
  2255. Vector2.prototype.addToRef = function (otherVector, result) {
  2256. result.x = this.x + otherVector.x;
  2257. result.y = this.y + otherVector.y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2262. * Returns the updated Vector2.
  2263. */
  2264. Vector2.prototype.addInPlace = function (otherVector) {
  2265. this.x += otherVector.x;
  2266. this.y += otherVector.y;
  2267. return this;
  2268. };
  2269. /**
  2270. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2271. */
  2272. Vector2.prototype.addVector3 = function (otherVector) {
  2273. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2274. };
  2275. /**
  2276. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2277. */
  2278. Vector2.prototype.subtract = function (otherVector) {
  2279. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2280. };
  2281. /**
  2282. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2283. * Returns the Vector2.
  2284. */
  2285. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2286. result.x = this.x - otherVector.x;
  2287. result.y = this.y - otherVector.y;
  2288. return this;
  2289. };
  2290. /**
  2291. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2292. * Returns the updated Vector2.
  2293. */
  2294. Vector2.prototype.subtractInPlace = function (otherVector) {
  2295. this.x -= otherVector.x;
  2296. this.y -= otherVector.y;
  2297. return this;
  2298. };
  2299. /**
  2300. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2301. * Returns the updated Vector2.
  2302. */
  2303. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2304. this.x *= otherVector.x;
  2305. this.y *= otherVector.y;
  2306. return this;
  2307. };
  2308. /**
  2309. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2310. */
  2311. Vector2.prototype.multiply = function (otherVector) {
  2312. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2313. };
  2314. /**
  2315. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2316. * Returns the Vector2.
  2317. */
  2318. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2319. result.x = this.x * otherVector.x;
  2320. result.y = this.y * otherVector.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2325. */
  2326. Vector2.prototype.multiplyByFloats = function (x, y) {
  2327. return new Vector2(this.x * x, this.y * y);
  2328. };
  2329. /**
  2330. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2331. */
  2332. Vector2.prototype.divide = function (otherVector) {
  2333. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2334. };
  2335. /**
  2336. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2337. * Returns the Vector2.
  2338. */
  2339. Vector2.prototype.divideToRef = function (otherVector, result) {
  2340. result.x = this.x / otherVector.x;
  2341. result.y = this.y / otherVector.y;
  2342. return this;
  2343. };
  2344. /**
  2345. * Divides the current Vector3 coordinates by the passed ones.
  2346. * Returns the updated Vector3.
  2347. */
  2348. Vector2.prototype.divideInPlace = function (otherVector) {
  2349. return this.divideToRef(otherVector, this);
  2350. };
  2351. /**
  2352. * Returns a new Vector2 with current Vector2 negated coordinates.
  2353. */
  2354. Vector2.prototype.negate = function () {
  2355. return new Vector2(-this.x, -this.y);
  2356. };
  2357. /**
  2358. * Multiply the Vector2 coordinates by scale.
  2359. * Returns the updated Vector2.
  2360. */
  2361. Vector2.prototype.scaleInPlace = function (scale) {
  2362. this.x *= scale;
  2363. this.y *= scale;
  2364. return this;
  2365. };
  2366. /**
  2367. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2368. */
  2369. Vector2.prototype.scale = function (scale) {
  2370. var result = new Vector2(0, 0);
  2371. this.scaleToRef(scale, result);
  2372. return result;
  2373. };
  2374. /**
  2375. * Scale the current Vector2 values by a factor to a given Vector2
  2376. * @param scale defines the scale factor
  2377. * @param result defines the Vector2 object where to store the result
  2378. * @returns the unmodified current Vector2
  2379. */
  2380. Vector2.prototype.scaleToRef = function (scale, result) {
  2381. result.x = this.x * scale;
  2382. result.y = this.y * scale;
  2383. return this;
  2384. };
  2385. /**
  2386. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2387. * @param scale defines the scale factor
  2388. * @param result defines the Vector2 object where to store the result
  2389. * @returns the unmodified current Vector2
  2390. */
  2391. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2392. result.x += this.x * scale;
  2393. result.y += this.y * scale;
  2394. return this;
  2395. };
  2396. /**
  2397. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2398. */
  2399. Vector2.prototype.equals = function (otherVector) {
  2400. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2401. };
  2402. /**
  2403. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2404. */
  2405. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2406. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2407. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2408. };
  2409. // Properties
  2410. /**
  2411. * Returns the vector length (float).
  2412. */
  2413. Vector2.prototype.length = function () {
  2414. return Math.sqrt(this.x * this.x + this.y * this.y);
  2415. };
  2416. /**
  2417. * Returns the vector squared length (float);
  2418. */
  2419. Vector2.prototype.lengthSquared = function () {
  2420. return (this.x * this.x + this.y * this.y);
  2421. };
  2422. // Methods
  2423. /**
  2424. * Normalize the vector.
  2425. * Returns the updated Vector2.
  2426. */
  2427. Vector2.prototype.normalize = function () {
  2428. var len = this.length();
  2429. if (len === 0)
  2430. return this;
  2431. var num = 1.0 / len;
  2432. this.x *= num;
  2433. this.y *= num;
  2434. return this;
  2435. };
  2436. /**
  2437. * Returns a new Vector2 copied from the Vector2.
  2438. */
  2439. Vector2.prototype.clone = function () {
  2440. return new Vector2(this.x, this.y);
  2441. };
  2442. // Statics
  2443. /**
  2444. * Returns a new Vector2(0, 0)
  2445. */
  2446. Vector2.Zero = function () {
  2447. return new Vector2(0, 0);
  2448. };
  2449. /**
  2450. * Returns a new Vector2(1, 1)
  2451. */
  2452. Vector2.One = function () {
  2453. return new Vector2(1, 1);
  2454. };
  2455. /**
  2456. * Returns a new Vector2 set from the passed index element of the passed array.
  2457. */
  2458. Vector2.FromArray = function (array, offset) {
  2459. if (offset === void 0) { offset = 0; }
  2460. return new Vector2(array[offset], array[offset + 1]);
  2461. };
  2462. /**
  2463. * Sets "result" from the passed index element of the passed array.
  2464. */
  2465. Vector2.FromArrayToRef = function (array, offset, result) {
  2466. result.x = array[offset];
  2467. result.y = array[offset + 1];
  2468. };
  2469. /**
  2470. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2471. */
  2472. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2473. var squared = amount * amount;
  2474. var cubed = amount * squared;
  2475. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2476. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2477. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2478. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2479. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2480. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2481. return new Vector2(x, y);
  2482. };
  2483. /**
  2484. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2485. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2486. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2487. */
  2488. Vector2.Clamp = function (value, min, max) {
  2489. var x = value.x;
  2490. x = (x > max.x) ? max.x : x;
  2491. x = (x < min.x) ? min.x : x;
  2492. var y = value.y;
  2493. y = (y > max.y) ? max.y : y;
  2494. y = (y < min.y) ? min.y : y;
  2495. return new Vector2(x, y);
  2496. };
  2497. /**
  2498. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2499. */
  2500. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2501. var squared = amount * amount;
  2502. var cubed = amount * squared;
  2503. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2504. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2505. var part3 = (cubed - (2.0 * squared)) + amount;
  2506. var part4 = cubed - squared;
  2507. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2508. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2509. return new Vector2(x, y);
  2510. };
  2511. /**
  2512. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2513. */
  2514. Vector2.Lerp = function (start, end, amount) {
  2515. var x = start.x + ((end.x - start.x) * amount);
  2516. var y = start.y + ((end.y - start.y) * amount);
  2517. return new Vector2(x, y);
  2518. };
  2519. /**
  2520. * Returns the dot product (float) of the vector "left" and the vector "right".
  2521. */
  2522. Vector2.Dot = function (left, right) {
  2523. return left.x * right.x + left.y * right.y;
  2524. };
  2525. /**
  2526. * Returns a new Vector2 equal to the normalized passed vector.
  2527. */
  2528. Vector2.Normalize = function (vector) {
  2529. var newVector = vector.clone();
  2530. newVector.normalize();
  2531. return newVector;
  2532. };
  2533. /**
  2534. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2535. */
  2536. Vector2.Minimize = function (left, right) {
  2537. var x = (left.x < right.x) ? left.x : right.x;
  2538. var y = (left.y < right.y) ? left.y : right.y;
  2539. return new Vector2(x, y);
  2540. };
  2541. /**
  2542. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2543. */
  2544. Vector2.Maximize = function (left, right) {
  2545. var x = (left.x > right.x) ? left.x : right.x;
  2546. var y = (left.y > right.y) ? left.y : right.y;
  2547. return new Vector2(x, y);
  2548. };
  2549. /**
  2550. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2551. */
  2552. Vector2.Transform = function (vector, transformation) {
  2553. var r = Vector2.Zero();
  2554. Vector2.TransformToRef(vector, transformation, r);
  2555. return r;
  2556. };
  2557. /**
  2558. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2559. */
  2560. Vector2.TransformToRef = function (vector, transformation, result) {
  2561. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2562. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2563. result.x = x;
  2564. result.y = y;
  2565. };
  2566. /**
  2567. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2568. */
  2569. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2570. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2571. var sign = a < 0 ? -1 : 1;
  2572. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2573. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2574. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2575. };
  2576. /**
  2577. * Returns the distance (float) between the vectors "value1" and "value2".
  2578. */
  2579. Vector2.Distance = function (value1, value2) {
  2580. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2581. };
  2582. /**
  2583. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2584. */
  2585. Vector2.DistanceSquared = function (value1, value2) {
  2586. var x = value1.x - value2.x;
  2587. var y = value1.y - value2.y;
  2588. return (x * x) + (y * y);
  2589. };
  2590. /**
  2591. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2592. */
  2593. Vector2.Center = function (value1, value2) {
  2594. var center = value1.add(value2);
  2595. center.scaleInPlace(0.5);
  2596. return center;
  2597. };
  2598. /**
  2599. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2600. */
  2601. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2602. var l2 = Vector2.DistanceSquared(segA, segB);
  2603. if (l2 === 0.0) {
  2604. return Vector2.Distance(p, segA);
  2605. }
  2606. var v = segB.subtract(segA);
  2607. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2608. var proj = segA.add(v.multiplyByFloats(t, t));
  2609. return Vector2.Distance(p, proj);
  2610. };
  2611. return Vector2;
  2612. }());
  2613. BABYLON.Vector2 = Vector2;
  2614. /**
  2615. * Classed used to store (x,y,z) vector representation
  2616. * A Vector3 is the main object used in 3D geometry
  2617. * It can represent etiher the coordinates of a point the space, either a direction
  2618. * Reminder: Babylon.js uses a left handed forward facing system
  2619. */
  2620. var Vector3 = /** @class */ (function () {
  2621. /**
  2622. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2623. * @param x defines the first coordinates (on X axis)
  2624. * @param y defines the second coordinates (on Y axis)
  2625. * @param z defines the third coordinates (on Z axis)
  2626. */
  2627. function Vector3(
  2628. /**
  2629. * Defines the first coordinates (on X axis)
  2630. */
  2631. x,
  2632. /**
  2633. * Defines the second coordinates (on Y axis)
  2634. */
  2635. y,
  2636. /**
  2637. * Defines the third coordinates (on Z axis)
  2638. */
  2639. z) {
  2640. this.x = x;
  2641. this.y = y;
  2642. this.z = z;
  2643. }
  2644. /**
  2645. * Creates a string representation of the Vector3
  2646. * @returns a string with the Vector3 coordinates.
  2647. */
  2648. Vector3.prototype.toString = function () {
  2649. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2650. };
  2651. /**
  2652. * Gets the class name
  2653. * @returns the string "Vector3"
  2654. */
  2655. Vector3.prototype.getClassName = function () {
  2656. return "Vector3";
  2657. };
  2658. /**
  2659. * Creates the Vector3 hash code
  2660. * @returns a number which tends to be unique between Vector3 instances
  2661. */
  2662. Vector3.prototype.getHashCode = function () {
  2663. var hash = this.x || 0;
  2664. hash = (hash * 397) ^ (this.y || 0);
  2665. hash = (hash * 397) ^ (this.z || 0);
  2666. return hash;
  2667. };
  2668. // Operators
  2669. /**
  2670. * Creates an array containing three elements : the coordinates of the Vector3
  2671. * @returns a new array of numbers
  2672. */
  2673. Vector3.prototype.asArray = function () {
  2674. var result = [];
  2675. this.toArray(result, 0);
  2676. return result;
  2677. };
  2678. /**
  2679. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2680. * @param array defines the destination array
  2681. * @param index defines the offset in the destination array
  2682. * @returns the current Vector3
  2683. */
  2684. Vector3.prototype.toArray = function (array, index) {
  2685. if (index === void 0) { index = 0; }
  2686. array[index] = this.x;
  2687. array[index + 1] = this.y;
  2688. array[index + 2] = this.z;
  2689. return this;
  2690. };
  2691. /**
  2692. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2693. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2694. */
  2695. Vector3.prototype.toQuaternion = function () {
  2696. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2697. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2698. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2699. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2700. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2701. var cosy = Math.cos(this.y * 0.5);
  2702. var siny = Math.sin(this.y * 0.5);
  2703. result.x = coszMinusx * siny;
  2704. result.y = -sinzMinusx * siny;
  2705. result.z = sinxPlusz * cosy;
  2706. result.w = cosxPlusz * cosy;
  2707. return result;
  2708. };
  2709. /**
  2710. * Adds the passed vector to the current Vector3
  2711. * @param otherVector defines the second operand
  2712. * @returns the current updated Vector3
  2713. */
  2714. Vector3.prototype.addInPlace = function (otherVector) {
  2715. this.x += otherVector.x;
  2716. this.y += otherVector.y;
  2717. this.z += otherVector.z;
  2718. return this;
  2719. };
  2720. /**
  2721. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2722. * @param otherVector defines the second operand
  2723. * @returns the resulting Vector3
  2724. */
  2725. Vector3.prototype.add = function (otherVector) {
  2726. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2727. };
  2728. /**
  2729. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2730. * @param otherVector defines the second operand
  2731. * @param result defines the Vector3 object where to store the result
  2732. * @returns the current Vector3
  2733. */
  2734. Vector3.prototype.addToRef = function (otherVector, result) {
  2735. result.x = this.x + otherVector.x;
  2736. result.y = this.y + otherVector.y;
  2737. result.z = this.z + otherVector.z;
  2738. return this;
  2739. };
  2740. /**
  2741. * Subtract the passed vector from the current Vector3
  2742. * @param otherVector defines the second operand
  2743. * @returns the current updated Vector3
  2744. */
  2745. Vector3.prototype.subtractInPlace = function (otherVector) {
  2746. this.x -= otherVector.x;
  2747. this.y -= otherVector.y;
  2748. this.z -= otherVector.z;
  2749. return this;
  2750. };
  2751. /**
  2752. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2753. * @param otherVector defines the second operand
  2754. * @returns the resulting Vector3
  2755. */
  2756. Vector3.prototype.subtract = function (otherVector) {
  2757. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2758. };
  2759. /**
  2760. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2761. * @param otherVector defines the second operand
  2762. * @param result defines the Vector3 object where to store the result
  2763. * @returns the current Vector3
  2764. */
  2765. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2766. result.x = this.x - otherVector.x;
  2767. result.y = this.y - otherVector.y;
  2768. result.z = this.z - otherVector.z;
  2769. return this;
  2770. };
  2771. /**
  2772. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2773. * @param x defines the x coordinate of the operand
  2774. * @param y defines the y coordinate of the operand
  2775. * @param z defines the z coordinate of the operand
  2776. * @returns the resulting Vector3
  2777. */
  2778. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2779. return new Vector3(this.x - x, this.y - y, this.z - z);
  2780. };
  2781. /**
  2782. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2783. * @param x defines the x coordinate of the operand
  2784. * @param y defines the y coordinate of the operand
  2785. * @param z defines the z coordinate of the operand
  2786. * @param result defines the Vector3 object where to store the result
  2787. * @returns the current Vector3
  2788. */
  2789. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2790. result.x = this.x - x;
  2791. result.y = this.y - y;
  2792. result.z = this.z - z;
  2793. return this;
  2794. };
  2795. /**
  2796. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2797. * @returns a new Vector3
  2798. */
  2799. Vector3.prototype.negate = function () {
  2800. return new Vector3(-this.x, -this.y, -this.z);
  2801. };
  2802. /**
  2803. * Multiplies the Vector3 coordinates by the float "scale"
  2804. * @param scale defines the multiplier factor
  2805. * @returns the current updated Vector3
  2806. */
  2807. Vector3.prototype.scaleInPlace = function (scale) {
  2808. this.x *= scale;
  2809. this.y *= scale;
  2810. this.z *= scale;
  2811. return this;
  2812. };
  2813. /**
  2814. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2815. * @param scale defines the multiplier factor
  2816. * @returns a new Vector3
  2817. */
  2818. Vector3.prototype.scale = function (scale) {
  2819. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2820. };
  2821. /**
  2822. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2823. * @param scale defines the multiplier factor
  2824. * @param result defines the Vector3 object where to store the result
  2825. * @returns the current Vector3
  2826. */
  2827. Vector3.prototype.scaleToRef = function (scale, result) {
  2828. result.x = this.x * scale;
  2829. result.y = this.y * scale;
  2830. result.z = this.z * scale;
  2831. return this;
  2832. };
  2833. /**
  2834. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2835. * @param scale defines the scale factor
  2836. * @param result defines the Vector3 object where to store the result
  2837. * @returns the unmodified current Vector3
  2838. */
  2839. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2840. result.x += this.x * scale;
  2841. result.y += this.y * scale;
  2842. result.z += this.z * scale;
  2843. return this;
  2844. };
  2845. /**
  2846. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2847. * @param otherVector defines the second operand
  2848. * @returns true if both vectors are equals
  2849. */
  2850. Vector3.prototype.equals = function (otherVector) {
  2851. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2852. };
  2853. /**
  2854. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2855. * @param otherVector defines the second operand
  2856. * @param epsilon defines the minimal distance to define values as equals
  2857. * @returns true if both vectors are distant less than epsilon
  2858. */
  2859. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2860. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2861. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  2862. };
  2863. /**
  2864. * Returns true if the current Vector3 coordinates equals the passed floats
  2865. * @param x defines the x coordinate of the operand
  2866. * @param y defines the y coordinate of the operand
  2867. * @param z defines the z coordinate of the operand
  2868. * @returns true if both vectors are equals
  2869. */
  2870. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2871. return this.x === x && this.y === y && this.z === z;
  2872. };
  2873. /**
  2874. * Multiplies the current Vector3 coordinates by the passed ones
  2875. * @param otherVector defines the second operand
  2876. * @returns the current updated Vector3
  2877. */
  2878. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2879. this.x *= otherVector.x;
  2880. this.y *= otherVector.y;
  2881. this.z *= otherVector.z;
  2882. return this;
  2883. };
  2884. /**
  2885. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2886. * @param otherVector defines the second operand
  2887. * @returns the new Vector3
  2888. */
  2889. Vector3.prototype.multiply = function (otherVector) {
  2890. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2891. };
  2892. /**
  2893. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2894. * @param otherVector defines the second operand
  2895. * @param result defines the Vector3 object where to store the result
  2896. * @returns the current Vector3
  2897. */
  2898. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2899. result.x = this.x * otherVector.x;
  2900. result.y = this.y * otherVector.y;
  2901. result.z = this.z * otherVector.z;
  2902. return this;
  2903. };
  2904. /**
  2905. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2906. * @param x defines the x coordinate of the operand
  2907. * @param y defines the y coordinate of the operand
  2908. * @param z defines the z coordinate of the operand
  2909. * @returns the new Vector3
  2910. */
  2911. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2912. return new Vector3(this.x * x, this.y * y, this.z * z);
  2913. };
  2914. /**
  2915. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2916. * @param otherVector defines the second operand
  2917. * @returns the new Vector3
  2918. */
  2919. Vector3.prototype.divide = function (otherVector) {
  2920. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2921. };
  2922. /**
  2923. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2924. * @param otherVector defines the second operand
  2925. * @param result defines the Vector3 object where to store the result
  2926. * @returns the current Vector3
  2927. */
  2928. Vector3.prototype.divideToRef = function (otherVector, result) {
  2929. result.x = this.x / otherVector.x;
  2930. result.y = this.y / otherVector.y;
  2931. result.z = this.z / otherVector.z;
  2932. return this;
  2933. };
  2934. /**
  2935. * Divides the current Vector3 coordinates by the passed ones.
  2936. * @param otherVector defines the second operand
  2937. * @returns the current updated Vector3
  2938. */
  2939. Vector3.prototype.divideInPlace = function (otherVector) {
  2940. return this.divideToRef(otherVector, this);
  2941. };
  2942. /**
  2943. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2944. * @param other defines the second operand
  2945. * @returns the current updated Vector3
  2946. */
  2947. Vector3.prototype.minimizeInPlace = function (other) {
  2948. if (other.x < this.x)
  2949. this.x = other.x;
  2950. if (other.y < this.y)
  2951. this.y = other.y;
  2952. if (other.z < this.z)
  2953. this.z = other.z;
  2954. return this;
  2955. };
  2956. /**
  2957. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2958. * @param other defines the second operand
  2959. * @returns the current updated Vector3
  2960. */
  2961. Vector3.prototype.maximizeInPlace = function (other) {
  2962. if (other.x > this.x)
  2963. this.x = other.x;
  2964. if (other.y > this.y)
  2965. this.y = other.y;
  2966. if (other.z > this.z)
  2967. this.z = other.z;
  2968. return this;
  2969. };
  2970. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2971. /**
  2972. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2973. */
  2974. get: function () {
  2975. var absX = Math.abs(this.x);
  2976. var absY = Math.abs(this.y);
  2977. if (absX !== absY) {
  2978. return true;
  2979. }
  2980. var absZ = Math.abs(this.z);
  2981. if (absX !== absZ) {
  2982. return true;
  2983. }
  2984. if (absY !== absZ) {
  2985. return true;
  2986. }
  2987. return false;
  2988. },
  2989. enumerable: true,
  2990. configurable: true
  2991. });
  2992. // Properties
  2993. /**
  2994. * Gets the length of the Vector3
  2995. * @returns the length of the Vecto3
  2996. */
  2997. Vector3.prototype.length = function () {
  2998. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2999. };
  3000. /**
  3001. * Gets the squared length of the Vector3
  3002. * @returns squared length of the Vector3
  3003. */
  3004. Vector3.prototype.lengthSquared = function () {
  3005. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3006. };
  3007. /**
  3008. * Normalize the current Vector3.
  3009. * Please note that this is an in place operation.
  3010. * @returns the current updated Vector3
  3011. */
  3012. Vector3.prototype.normalize = function () {
  3013. var len = this.length();
  3014. if (len === 0 || len === 1.0)
  3015. return this;
  3016. var num = 1.0 / len;
  3017. this.x *= num;
  3018. this.y *= num;
  3019. this.z *= num;
  3020. return this;
  3021. };
  3022. /**
  3023. * Normalize the current Vector3 to a new vector
  3024. * @returns the new Vector3
  3025. */
  3026. Vector3.prototype.normalizeToNew = function () {
  3027. var normalized = new Vector3(0, 0, 0);
  3028. this.normalizeToRef(normalized);
  3029. return normalized;
  3030. };
  3031. /**
  3032. * Normalize the current Vector3 to the reference
  3033. * @param reference define the Vector3 to update
  3034. * @returns the updated Vector3
  3035. */
  3036. Vector3.prototype.normalizeToRef = function (reference) {
  3037. var len = this.length();
  3038. if (len === 0 || len === 1.0) {
  3039. reference.set(this.x, this.y, this.z);
  3040. return reference;
  3041. }
  3042. var scale = 1.0 / len;
  3043. this.scaleToRef(scale, reference);
  3044. return reference;
  3045. };
  3046. /**
  3047. * Creates a new Vector3 copied from the current Vector3
  3048. * @returns the new Vector3
  3049. */
  3050. Vector3.prototype.clone = function () {
  3051. return new Vector3(this.x, this.y, this.z);
  3052. };
  3053. /**
  3054. * Copies the passed vector coordinates to the current Vector3 ones
  3055. * @param source defines the source Vector3
  3056. * @returns the current updated Vector3
  3057. */
  3058. Vector3.prototype.copyFrom = function (source) {
  3059. this.x = source.x;
  3060. this.y = source.y;
  3061. this.z = source.z;
  3062. return this;
  3063. };
  3064. /**
  3065. * Copies the passed floats to the current Vector3 coordinates
  3066. * @param x defines the x coordinate of the operand
  3067. * @param y defines the y coordinate of the operand
  3068. * @param z defines the z coordinate of the operand
  3069. * @returns the current updated Vector3
  3070. */
  3071. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3072. this.x = x;
  3073. this.y = y;
  3074. this.z = z;
  3075. return this;
  3076. };
  3077. /**
  3078. * Copies the passed floats to the current Vector3 coordinates
  3079. * @param x defines the x coordinate of the operand
  3080. * @param y defines the y coordinate of the operand
  3081. * @param z defines the z coordinate of the operand
  3082. * @returns the current updated Vector3
  3083. */
  3084. Vector3.prototype.set = function (x, y, z) {
  3085. return this.copyFromFloats(x, y, z);
  3086. };
  3087. // Statics
  3088. /**
  3089. * Get the clip factor between two vectors
  3090. * @param vector0 defines the first operand
  3091. * @param vector1 defines the second operand
  3092. * @param axis defines the axis to use
  3093. * @param size defines the size along the axis
  3094. * @returns the clip factor
  3095. */
  3096. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3097. var d0 = Vector3.Dot(vector0, axis) - size;
  3098. var d1 = Vector3.Dot(vector1, axis) - size;
  3099. var s = d0 / (d0 - d1);
  3100. return s;
  3101. };
  3102. /**
  3103. * Get angle between two vectors
  3104. * @param vector0 angle between vector0 and vector1
  3105. * @param vector1 angle between vector0 and vector1
  3106. * @param normal direction of the normal
  3107. * @return the angle between vector0 and vector1
  3108. */
  3109. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3110. var v0 = vector0.clone().normalize();
  3111. var v1 = vector1.clone().normalize();
  3112. var dot = Vector3.Dot(v0, v1);
  3113. var n = Vector3.Cross(v0, v1);
  3114. if (Vector3.Dot(n, normal) > 0) {
  3115. return Math.acos(dot);
  3116. }
  3117. return -Math.acos(dot);
  3118. };
  3119. /**
  3120. * Returns a new Vector3 set from the index "offset" of the passed array
  3121. * @param array defines the source array
  3122. * @param offset defines the offset in the source array
  3123. * @returns the new Vector3
  3124. */
  3125. Vector3.FromArray = function (array, offset) {
  3126. if (!offset) {
  3127. offset = 0;
  3128. }
  3129. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3130. };
  3131. /**
  3132. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3133. * This function is deprecated. Use FromArray instead
  3134. * @param array defines the source array
  3135. * @param offset defines the offset in the source array
  3136. * @returns the new Vector3
  3137. */
  3138. Vector3.FromFloatArray = function (array, offset) {
  3139. return Vector3.FromArray(array, offset);
  3140. };
  3141. /**
  3142. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3143. * @param array defines the source array
  3144. * @param offset defines the offset in the source array
  3145. * @param result defines the Vector3 where to store the result
  3146. */
  3147. Vector3.FromArrayToRef = function (array, offset, result) {
  3148. result.x = array[offset];
  3149. result.y = array[offset + 1];
  3150. result.z = array[offset + 2];
  3151. };
  3152. /**
  3153. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3154. * This function is deprecated. Use FromArrayToRef instead.
  3155. * @param array defines the source array
  3156. * @param offset defines the offset in the source array
  3157. * @param result defines the Vector3 where to store the result
  3158. */
  3159. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3160. return Vector3.FromArrayToRef(array, offset, result);
  3161. };
  3162. /**
  3163. * Sets the passed vector "result" with the passed floats.
  3164. * @param x defines the x coordinate of the source
  3165. * @param y defines the y coordinate of the source
  3166. * @param z defines the z coordinate of the source
  3167. * @param result defines the Vector3 where to store the result
  3168. */
  3169. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3170. result.x = x;
  3171. result.y = y;
  3172. result.z = z;
  3173. };
  3174. /**
  3175. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3176. * @returns a new empty Vector3
  3177. */
  3178. Vector3.Zero = function () {
  3179. return new Vector3(0.0, 0.0, 0.0);
  3180. };
  3181. /**
  3182. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3183. * @returns a new unit Vector3
  3184. */
  3185. Vector3.One = function () {
  3186. return new Vector3(1.0, 1.0, 1.0);
  3187. };
  3188. /**
  3189. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3190. * @returns a new up Vector3
  3191. */
  3192. Vector3.Up = function () {
  3193. return new Vector3(0.0, 1.0, 0.0);
  3194. };
  3195. /**
  3196. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3197. * @returns a new forward Vector3
  3198. */
  3199. Vector3.Forward = function () {
  3200. return new Vector3(0.0, 0.0, 1.0);
  3201. };
  3202. /**
  3203. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3204. * @returns a new right Vector3
  3205. */
  3206. Vector3.Right = function () {
  3207. return new Vector3(1.0, 0.0, 0.0);
  3208. };
  3209. /**
  3210. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3211. * @returns a new left Vector3
  3212. */
  3213. Vector3.Left = function () {
  3214. return new Vector3(-1.0, 0.0, 0.0);
  3215. };
  3216. /**
  3217. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3218. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3219. * @param vector defines the Vector3 to transform
  3220. * @param transformation defines the transformation matrix
  3221. * @returns the transformed Vector3
  3222. */
  3223. Vector3.TransformCoordinates = function (vector, transformation) {
  3224. var result = Vector3.Zero();
  3225. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3226. return result;
  3227. };
  3228. /**
  3229. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3230. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3231. * @param vector defines the Vector3 to transform
  3232. * @param transformation defines the transformation matrix
  3233. * @param result defines the Vector3 where to store the result
  3234. */
  3235. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3236. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3237. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3238. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3239. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3240. result.x = x / w;
  3241. result.y = y / w;
  3242. result.z = z / w;
  3243. };
  3244. /**
  3245. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3246. * This method computes tranformed coordinates only, not transformed direction vectors
  3247. * @param x define the x coordinate of the source vector
  3248. * @param y define the y coordinate of the source vector
  3249. * @param z define the z coordinate of the source vector
  3250. * @param transformation defines the transformation matrix
  3251. * @param result defines the Vector3 where to store the result
  3252. */
  3253. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3254. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3255. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3256. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3257. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3258. result.x = rx / rw;
  3259. result.y = ry / rw;
  3260. result.z = rz / rw;
  3261. };
  3262. /**
  3263. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3264. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3265. * @param vector defines the Vector3 to transform
  3266. * @param transformation defines the transformation matrix
  3267. * @returns the new Vector3
  3268. */
  3269. Vector3.TransformNormal = function (vector, transformation) {
  3270. var result = Vector3.Zero();
  3271. Vector3.TransformNormalToRef(vector, transformation, result);
  3272. return result;
  3273. };
  3274. /**
  3275. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3276. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3277. * @param vector defines the Vector3 to transform
  3278. * @param transformation defines the transformation matrix
  3279. * @param result defines the Vector3 where to store the result
  3280. */
  3281. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3282. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3283. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3284. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3285. result.x = x;
  3286. result.y = y;
  3287. result.z = z;
  3288. };
  3289. /**
  3290. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3291. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3292. * @param x define the x coordinate of the source vector
  3293. * @param y define the y coordinate of the source vector
  3294. * @param z define the z coordinate of the source vector
  3295. * @param transformation defines the transformation matrix
  3296. * @param result defines the Vector3 where to store the result
  3297. */
  3298. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3299. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3300. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3301. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3302. };
  3303. /**
  3304. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3305. * @param value1 defines the first control point
  3306. * @param value2 defines the second control point
  3307. * @param value3 defines the third control point
  3308. * @param value4 defines the fourth control point
  3309. * @param amount defines the amount on the spline to use
  3310. * @returns the new Vector3
  3311. */
  3312. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3313. var squared = amount * amount;
  3314. var cubed = amount * squared;
  3315. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3316. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3317. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3318. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3319. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3320. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3321. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3322. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3323. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3324. return new Vector3(x, y, z);
  3325. };
  3326. /**
  3327. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3328. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3329. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3330. * @param value defines the current value
  3331. * @param min defines the lower range value
  3332. * @param max defines the upper range value
  3333. * @returns the new Vector3
  3334. */
  3335. Vector3.Clamp = function (value, min, max) {
  3336. var x = value.x;
  3337. x = (x > max.x) ? max.x : x;
  3338. x = (x < min.x) ? min.x : x;
  3339. var y = value.y;
  3340. y = (y > max.y) ? max.y : y;
  3341. y = (y < min.y) ? min.y : y;
  3342. var z = value.z;
  3343. z = (z > max.z) ? max.z : z;
  3344. z = (z < min.z) ? min.z : z;
  3345. return new Vector3(x, y, z);
  3346. };
  3347. /**
  3348. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3349. * @param value1 defines the first control point
  3350. * @param tangent1 defines the first tangent vector
  3351. * @param value2 defines the second control point
  3352. * @param tangent2 defines the second tangent vector
  3353. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3354. * @returns the new Vector3
  3355. */
  3356. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3357. var squared = amount * amount;
  3358. var cubed = amount * squared;
  3359. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3360. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3361. var part3 = (cubed - (2.0 * squared)) + amount;
  3362. var part4 = cubed - squared;
  3363. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3364. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3365. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3366. return new Vector3(x, y, z);
  3367. };
  3368. /**
  3369. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3370. * @param start defines the start value
  3371. * @param end defines the end value
  3372. * @param amount max defines amount between both (between 0 and 1)
  3373. * @returns the new Vector3
  3374. */
  3375. Vector3.Lerp = function (start, end, amount) {
  3376. var result = new Vector3(0, 0, 0);
  3377. Vector3.LerpToRef(start, end, amount, result);
  3378. return result;
  3379. };
  3380. /**
  3381. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3382. * @param start defines the start value
  3383. * @param end defines the end value
  3384. * @param amount max defines amount between both (between 0 and 1)
  3385. * @param result defines the Vector3 where to store the result
  3386. */
  3387. Vector3.LerpToRef = function (start, end, amount, result) {
  3388. result.x = start.x + ((end.x - start.x) * amount);
  3389. result.y = start.y + ((end.y - start.y) * amount);
  3390. result.z = start.z + ((end.z - start.z) * amount);
  3391. };
  3392. /**
  3393. * Returns the dot product (float) between the vectors "left" and "right"
  3394. * @param left defines the left operand
  3395. * @param right defines the right operand
  3396. * @returns the dot product
  3397. */
  3398. Vector3.Dot = function (left, right) {
  3399. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3400. };
  3401. /**
  3402. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3403. * The cross product is then orthogonal to both "left" and "right"
  3404. * @param left defines the left operand
  3405. * @param right defines the right operand
  3406. * @returns the cross product
  3407. */
  3408. Vector3.Cross = function (left, right) {
  3409. var result = Vector3.Zero();
  3410. Vector3.CrossToRef(left, right, result);
  3411. return result;
  3412. };
  3413. /**
  3414. * Sets the passed vector "result" with the cross product of "left" and "right"
  3415. * The cross product is then orthogonal to both "left" and "right"
  3416. * @param left defines the left operand
  3417. * @param right defines the right operand
  3418. * @param result defines the Vector3 where to store the result
  3419. */
  3420. Vector3.CrossToRef = function (left, right, result) {
  3421. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3422. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3423. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3424. result.copyFrom(MathTmp.Vector3[0]);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 as the normalization of the passed vector
  3428. * @param vector defines the Vector3 to normalize
  3429. * @returns the new Vector3
  3430. */
  3431. Vector3.Normalize = function (vector) {
  3432. var result = Vector3.Zero();
  3433. Vector3.NormalizeToRef(vector, result);
  3434. return result;
  3435. };
  3436. /**
  3437. * Sets the passed vector "result" with the normalization of the passed first vector
  3438. * @param vector defines the Vector3 to normalize
  3439. * @param result defines the Vector3 where to store the result
  3440. */
  3441. Vector3.NormalizeToRef = function (vector, result) {
  3442. result.copyFrom(vector);
  3443. result.normalize();
  3444. };
  3445. /**
  3446. * Project a Vector3 onto screen space
  3447. * @param vector defines the Vector3 to project
  3448. * @param world defines the world matrix to use
  3449. * @param transform defines the transform (view x projection) matrix to use
  3450. * @param viewport defines the screen viewport to use
  3451. * @returns the new Vector3
  3452. */
  3453. Vector3.Project = function (vector, world, transform, viewport) {
  3454. var cw = viewport.width;
  3455. var ch = viewport.height;
  3456. var cx = viewport.x;
  3457. var cy = viewport.y;
  3458. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3459. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3460. var matrix = MathTmp.Matrix[0];
  3461. world.multiplyToRef(transform, matrix);
  3462. matrix.multiplyToRef(viewportMatrix, matrix);
  3463. return Vector3.TransformCoordinates(vector, matrix);
  3464. };
  3465. /**
  3466. * Unproject from screen space to object space
  3467. * @param source defines the screen space Vector3 to use
  3468. * @param viewportWidth defines the current width of the viewport
  3469. * @param viewportHeight defines the current height of the viewport
  3470. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3471. * @param transform defines the transform (view x projection) matrix to use
  3472. * @returns the new Vector3
  3473. */
  3474. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3475. var matrix = MathTmp.Matrix[0];
  3476. world.multiplyToRef(transform, matrix);
  3477. matrix.invert();
  3478. source.x = source.x / viewportWidth * 2 - 1;
  3479. source.y = -(source.y / viewportHeight * 2 - 1);
  3480. var vector = Vector3.TransformCoordinates(source, matrix);
  3481. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3482. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3483. vector = vector.scale(1.0 / num);
  3484. }
  3485. return vector;
  3486. };
  3487. /**
  3488. * Unproject from screen space to object space
  3489. * @param source defines the screen space Vector3 to use
  3490. * @param viewportWidth defines the current width of the viewport
  3491. * @param viewportHeight defines the current height of the viewport
  3492. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3493. * @param view defines the view matrix to use
  3494. * @param projection defines the projection matrix to use
  3495. * @returns the new Vector3
  3496. */
  3497. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3498. var result = Vector3.Zero();
  3499. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3500. return result;
  3501. };
  3502. /**
  3503. * Unproject from screen space to object space
  3504. * @param source defines the screen space Vector3 to use
  3505. * @param viewportWidth defines the current width of the viewport
  3506. * @param viewportHeight defines the current height of the viewport
  3507. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3508. * @param view defines the view matrix to use
  3509. * @param projection defines the projection matrix to use
  3510. * @param result defines the Vector3 where to store the result
  3511. */
  3512. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3513. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3514. };
  3515. /**
  3516. * Unproject from screen space to object space
  3517. * @param sourceX defines the screen space x coordinate to use
  3518. * @param sourceY defines the screen space y coordinate to use
  3519. * @param sourceZ defines the screen space z coordinate to use
  3520. * @param viewportWidth defines the current width of the viewport
  3521. * @param viewportHeight defines the current height of the viewport
  3522. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3523. * @param view defines the view matrix to use
  3524. * @param projection defines the projection matrix to use
  3525. * @param result defines the Vector3 where to store the result
  3526. */
  3527. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3528. var matrix = MathTmp.Matrix[0];
  3529. world.multiplyToRef(view, matrix);
  3530. matrix.multiplyToRef(projection, matrix);
  3531. matrix.invert();
  3532. var screenSource = MathTmp.Vector3[0];
  3533. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3534. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3535. screenSource.z = 2 * sourceZ - 1.0;
  3536. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3537. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3538. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3539. result.scaleInPlace(1.0 / num);
  3540. }
  3541. };
  3542. /**
  3543. * Gets the minimal coordinate values between two Vector3
  3544. * @param left defines the first operand
  3545. * @param right defines the second operand
  3546. * @returns the new Vector3
  3547. */
  3548. Vector3.Minimize = function (left, right) {
  3549. var min = left.clone();
  3550. min.minimizeInPlace(right);
  3551. return min;
  3552. };
  3553. /**
  3554. * Gets the maximal coordinate values between two Vector3
  3555. * @param left defines the first operand
  3556. * @param right defines the second operand
  3557. * @returns the new Vector3
  3558. */
  3559. Vector3.Maximize = function (left, right) {
  3560. var max = left.clone();
  3561. max.maximizeInPlace(right);
  3562. return max;
  3563. };
  3564. /**
  3565. * Returns the distance between the vectors "value1" and "value2"
  3566. * @param value1 defines the first operand
  3567. * @param value2 defines the second operand
  3568. * @returns the distance
  3569. */
  3570. Vector3.Distance = function (value1, value2) {
  3571. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3572. };
  3573. /**
  3574. * Returns the squared distance between the vectors "value1" and "value2"
  3575. * @param value1 defines the first operand
  3576. * @param value2 defines the second operand
  3577. * @returns the squared distance
  3578. */
  3579. Vector3.DistanceSquared = function (value1, value2) {
  3580. var x = value1.x - value2.x;
  3581. var y = value1.y - value2.y;
  3582. var z = value1.z - value2.z;
  3583. return (x * x) + (y * y) + (z * z);
  3584. };
  3585. /**
  3586. * Returns a new Vector3 located at the center between "value1" and "value2"
  3587. * @param value1 defines the first operand
  3588. * @param value2 defines the second operand
  3589. * @returns the new Vector3
  3590. */
  3591. Vector3.Center = function (value1, value2) {
  3592. var center = value1.add(value2);
  3593. center.scaleInPlace(0.5);
  3594. return center;
  3595. };
  3596. /**
  3597. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3598. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3599. * to something in order to rotate it from its local system to the given target system
  3600. * Note: axis1, axis2 and axis3 are normalized during this operation
  3601. * @param axis1 defines the first axis
  3602. * @param axis2 defines the second axis
  3603. * @param axis3 defines the third axis
  3604. * @returns a new Vector3
  3605. */
  3606. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3607. var rotation = Vector3.Zero();
  3608. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3609. return rotation;
  3610. };
  3611. /**
  3612. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3613. * @param axis1 defines the first axis
  3614. * @param axis2 defines the second axis
  3615. * @param axis3 defines the third axis
  3616. * @param ref defines the Vector3 where to store the result
  3617. */
  3618. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3619. var quat = MathTmp.Quaternion[0];
  3620. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3621. quat.toEulerAnglesToRef(ref);
  3622. };
  3623. return Vector3;
  3624. }());
  3625. BABYLON.Vector3 = Vector3;
  3626. //Vector4 class created for EulerAngle class conversion to Quaternion
  3627. var Vector4 = /** @class */ (function () {
  3628. /**
  3629. * Creates a Vector4 object from the passed floats.
  3630. */
  3631. function Vector4(x, y, z, w) {
  3632. this.x = x;
  3633. this.y = y;
  3634. this.z = z;
  3635. this.w = w;
  3636. }
  3637. /**
  3638. * Returns the string with the Vector4 coordinates.
  3639. */
  3640. Vector4.prototype.toString = function () {
  3641. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3642. };
  3643. /**
  3644. * Returns the string "Vector4".
  3645. */
  3646. Vector4.prototype.getClassName = function () {
  3647. return "Vector4";
  3648. };
  3649. /**
  3650. * Returns the Vector4 hash code.
  3651. */
  3652. Vector4.prototype.getHashCode = function () {
  3653. var hash = this.x || 0;
  3654. hash = (hash * 397) ^ (this.y || 0);
  3655. hash = (hash * 397) ^ (this.z || 0);
  3656. hash = (hash * 397) ^ (this.w || 0);
  3657. return hash;
  3658. };
  3659. // Operators
  3660. /**
  3661. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3662. */
  3663. Vector4.prototype.asArray = function () {
  3664. var result = new Array();
  3665. this.toArray(result, 0);
  3666. return result;
  3667. };
  3668. /**
  3669. * Populates the passed array from the passed index with the Vector4 coordinates.
  3670. * Returns the Vector4.
  3671. */
  3672. Vector4.prototype.toArray = function (array, index) {
  3673. if (index === undefined) {
  3674. index = 0;
  3675. }
  3676. array[index] = this.x;
  3677. array[index + 1] = this.y;
  3678. array[index + 2] = this.z;
  3679. array[index + 3] = this.w;
  3680. return this;
  3681. };
  3682. /**
  3683. * Adds the passed vector to the current Vector4.
  3684. * Returns the updated Vector4.
  3685. */
  3686. Vector4.prototype.addInPlace = function (otherVector) {
  3687. this.x += otherVector.x;
  3688. this.y += otherVector.y;
  3689. this.z += otherVector.z;
  3690. this.w += otherVector.w;
  3691. return this;
  3692. };
  3693. /**
  3694. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3695. */
  3696. Vector4.prototype.add = function (otherVector) {
  3697. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3698. };
  3699. /**
  3700. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3701. * Returns the current Vector4.
  3702. */
  3703. Vector4.prototype.addToRef = function (otherVector, result) {
  3704. result.x = this.x + otherVector.x;
  3705. result.y = this.y + otherVector.y;
  3706. result.z = this.z + otherVector.z;
  3707. result.w = this.w + otherVector.w;
  3708. return this;
  3709. };
  3710. /**
  3711. * Subtract in place the passed vector from the current Vector4.
  3712. * Returns the updated Vector4.
  3713. */
  3714. Vector4.prototype.subtractInPlace = function (otherVector) {
  3715. this.x -= otherVector.x;
  3716. this.y -= otherVector.y;
  3717. this.z -= otherVector.z;
  3718. this.w -= otherVector.w;
  3719. return this;
  3720. };
  3721. /**
  3722. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3723. */
  3724. Vector4.prototype.subtract = function (otherVector) {
  3725. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3726. };
  3727. /**
  3728. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3729. * Returns the current Vector4.
  3730. */
  3731. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3732. result.x = this.x - otherVector.x;
  3733. result.y = this.y - otherVector.y;
  3734. result.z = this.z - otherVector.z;
  3735. result.w = this.w - otherVector.w;
  3736. return this;
  3737. };
  3738. /**
  3739. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3740. */
  3741. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3742. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3743. };
  3744. /**
  3745. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3746. * Returns the current Vector4.
  3747. */
  3748. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3749. result.x = this.x - x;
  3750. result.y = this.y - y;
  3751. result.z = this.z - z;
  3752. result.w = this.w - w;
  3753. return this;
  3754. };
  3755. /**
  3756. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3757. */
  3758. Vector4.prototype.negate = function () {
  3759. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3760. };
  3761. /**
  3762. * Multiplies the current Vector4 coordinates by scale (float).
  3763. * Returns the updated Vector4.
  3764. */
  3765. Vector4.prototype.scaleInPlace = function (scale) {
  3766. this.x *= scale;
  3767. this.y *= scale;
  3768. this.z *= scale;
  3769. this.w *= scale;
  3770. return this;
  3771. };
  3772. /**
  3773. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3774. */
  3775. Vector4.prototype.scale = function (scale) {
  3776. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3777. };
  3778. /**
  3779. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3780. * Returns the current Vector4.
  3781. */
  3782. Vector4.prototype.scaleToRef = function (scale, result) {
  3783. result.x = this.x * scale;
  3784. result.y = this.y * scale;
  3785. result.z = this.z * scale;
  3786. result.w = this.w * scale;
  3787. return this;
  3788. };
  3789. /**
  3790. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3791. * @param scale defines the scale factor
  3792. * @param result defines the Vector4 object where to store the result
  3793. * @returns the unmodified current Vector4
  3794. */
  3795. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3796. result.x += this.x * scale;
  3797. result.y += this.y * scale;
  3798. result.z += this.z * scale;
  3799. result.w += this.w * scale;
  3800. return this;
  3801. };
  3802. /**
  3803. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3804. */
  3805. Vector4.prototype.equals = function (otherVector) {
  3806. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3807. };
  3808. /**
  3809. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3810. */
  3811. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3812. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3813. return otherVector
  3814. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3815. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3816. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3817. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3818. };
  3819. /**
  3820. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3821. */
  3822. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3823. return this.x === x && this.y === y && this.z === z && this.w === w;
  3824. };
  3825. /**
  3826. * Multiplies in place the current Vector4 by the passed one.
  3827. * Returns the updated Vector4.
  3828. */
  3829. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3830. this.x *= otherVector.x;
  3831. this.y *= otherVector.y;
  3832. this.z *= otherVector.z;
  3833. this.w *= otherVector.w;
  3834. return this;
  3835. };
  3836. /**
  3837. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3838. */
  3839. Vector4.prototype.multiply = function (otherVector) {
  3840. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3841. };
  3842. /**
  3843. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3844. * Returns the current Vector4.
  3845. */
  3846. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3847. result.x = this.x * otherVector.x;
  3848. result.y = this.y * otherVector.y;
  3849. result.z = this.z * otherVector.z;
  3850. result.w = this.w * otherVector.w;
  3851. return this;
  3852. };
  3853. /**
  3854. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3855. */
  3856. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3857. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3858. };
  3859. /**
  3860. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3861. */
  3862. Vector4.prototype.divide = function (otherVector) {
  3863. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3864. };
  3865. /**
  3866. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3867. * Returns the current Vector4.
  3868. */
  3869. Vector4.prototype.divideToRef = function (otherVector, result) {
  3870. result.x = this.x / otherVector.x;
  3871. result.y = this.y / otherVector.y;
  3872. result.z = this.z / otherVector.z;
  3873. result.w = this.w / otherVector.w;
  3874. return this;
  3875. };
  3876. /**
  3877. * Divides the current Vector3 coordinates by the passed ones.
  3878. * @returns the updated Vector3.
  3879. */
  3880. Vector4.prototype.divideInPlace = function (otherVector) {
  3881. return this.divideToRef(otherVector, this);
  3882. };
  3883. /**
  3884. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3885. * @param other defines the second operand
  3886. * @returns the current updated Vector4
  3887. */
  3888. Vector4.prototype.minimizeInPlace = function (other) {
  3889. if (other.x < this.x)
  3890. this.x = other.x;
  3891. if (other.y < this.y)
  3892. this.y = other.y;
  3893. if (other.z < this.z)
  3894. this.z = other.z;
  3895. if (other.w < this.w)
  3896. this.w = other.w;
  3897. return this;
  3898. };
  3899. /**
  3900. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3901. * @param other defines the second operand
  3902. * @returns the current updated Vector4
  3903. */
  3904. Vector4.prototype.maximizeInPlace = function (other) {
  3905. if (other.x > this.x)
  3906. this.x = other.x;
  3907. if (other.y > this.y)
  3908. this.y = other.y;
  3909. if (other.z > this.z)
  3910. this.z = other.z;
  3911. if (other.w > this.w)
  3912. this.w = other.w;
  3913. return this;
  3914. };
  3915. // Properties
  3916. /**
  3917. * Returns the Vector4 length (float).
  3918. */
  3919. Vector4.prototype.length = function () {
  3920. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3921. };
  3922. /**
  3923. * Returns the Vector4 squared length (float).
  3924. */
  3925. Vector4.prototype.lengthSquared = function () {
  3926. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3927. };
  3928. // Methods
  3929. /**
  3930. * Normalizes in place the Vector4.
  3931. * Returns the updated Vector4.
  3932. */
  3933. Vector4.prototype.normalize = function () {
  3934. var len = this.length();
  3935. if (len === 0)
  3936. return this;
  3937. var num = 1.0 / len;
  3938. this.x *= num;
  3939. this.y *= num;
  3940. this.z *= num;
  3941. this.w *= num;
  3942. return this;
  3943. };
  3944. /**
  3945. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3946. */
  3947. Vector4.prototype.toVector3 = function () {
  3948. return new Vector3(this.x, this.y, this.z);
  3949. };
  3950. /**
  3951. * Returns a new Vector4 copied from the current one.
  3952. */
  3953. Vector4.prototype.clone = function () {
  3954. return new Vector4(this.x, this.y, this.z, this.w);
  3955. };
  3956. /**
  3957. * Updates the current Vector4 with the passed one coordinates.
  3958. * Returns the updated Vector4.
  3959. */
  3960. Vector4.prototype.copyFrom = function (source) {
  3961. this.x = source.x;
  3962. this.y = source.y;
  3963. this.z = source.z;
  3964. this.w = source.w;
  3965. return this;
  3966. };
  3967. /**
  3968. * Updates the current Vector4 coordinates with the passed floats.
  3969. * Returns the updated Vector4.
  3970. */
  3971. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3972. this.x = x;
  3973. this.y = y;
  3974. this.z = z;
  3975. this.w = w;
  3976. return this;
  3977. };
  3978. /**
  3979. * Updates the current Vector4 coordinates with the passed floats.
  3980. * Returns the updated Vector4.
  3981. */
  3982. Vector4.prototype.set = function (x, y, z, w) {
  3983. return this.copyFromFloats(x, y, z, w);
  3984. };
  3985. // Statics
  3986. /**
  3987. * Returns a new Vector4 set from the starting index of the passed array.
  3988. */
  3989. Vector4.FromArray = function (array, offset) {
  3990. if (!offset) {
  3991. offset = 0;
  3992. }
  3993. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3994. };
  3995. /**
  3996. * Updates the passed vector "result" from the starting index of the passed array.
  3997. */
  3998. Vector4.FromArrayToRef = function (array, offset, result) {
  3999. result.x = array[offset];
  4000. result.y = array[offset + 1];
  4001. result.z = array[offset + 2];
  4002. result.w = array[offset + 3];
  4003. };
  4004. /**
  4005. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4006. */
  4007. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4008. Vector4.FromArrayToRef(array, offset, result);
  4009. };
  4010. /**
  4011. * Updates the passed vector "result" coordinates from the passed floats.
  4012. */
  4013. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4014. result.x = x;
  4015. result.y = y;
  4016. result.z = z;
  4017. result.w = w;
  4018. };
  4019. /**
  4020. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4021. */
  4022. Vector4.Zero = function () {
  4023. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4024. };
  4025. /**
  4026. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4027. */
  4028. Vector4.One = function () {
  4029. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4030. };
  4031. /**
  4032. * Returns a new normalized Vector4 from the passed one.
  4033. */
  4034. Vector4.Normalize = function (vector) {
  4035. var result = Vector4.Zero();
  4036. Vector4.NormalizeToRef(vector, result);
  4037. return result;
  4038. };
  4039. /**
  4040. * Updates the passed vector "result" from the normalization of the passed one.
  4041. */
  4042. Vector4.NormalizeToRef = function (vector, result) {
  4043. result.copyFrom(vector);
  4044. result.normalize();
  4045. };
  4046. Vector4.Minimize = function (left, right) {
  4047. var min = left.clone();
  4048. min.minimizeInPlace(right);
  4049. return min;
  4050. };
  4051. Vector4.Maximize = function (left, right) {
  4052. var max = left.clone();
  4053. max.maximizeInPlace(right);
  4054. return max;
  4055. };
  4056. /**
  4057. * Returns the distance (float) between the vectors "value1" and "value2".
  4058. */
  4059. Vector4.Distance = function (value1, value2) {
  4060. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4061. };
  4062. /**
  4063. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4064. */
  4065. Vector4.DistanceSquared = function (value1, value2) {
  4066. var x = value1.x - value2.x;
  4067. var y = value1.y - value2.y;
  4068. var z = value1.z - value2.z;
  4069. var w = value1.w - value2.w;
  4070. return (x * x) + (y * y) + (z * z) + (w * w);
  4071. };
  4072. /**
  4073. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4074. */
  4075. Vector4.Center = function (value1, value2) {
  4076. var center = value1.add(value2);
  4077. center.scaleInPlace(0.5);
  4078. return center;
  4079. };
  4080. /**
  4081. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4082. * This methods computes transformed normalized direction vectors only.
  4083. */
  4084. Vector4.TransformNormal = function (vector, transformation) {
  4085. var result = Vector4.Zero();
  4086. Vector4.TransformNormalToRef(vector, transformation, result);
  4087. return result;
  4088. };
  4089. /**
  4090. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4091. * This methods computes transformed normalized direction vectors only.
  4092. */
  4093. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4094. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4095. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4096. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4097. result.x = x;
  4098. result.y = y;
  4099. result.z = z;
  4100. result.w = vector.w;
  4101. };
  4102. /**
  4103. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4104. * This methods computes transformed normalized direction vectors only.
  4105. */
  4106. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4107. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4108. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4109. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4110. result.w = w;
  4111. };
  4112. return Vector4;
  4113. }());
  4114. BABYLON.Vector4 = Vector4;
  4115. var Size = /** @class */ (function () {
  4116. /**
  4117. * Creates a Size object from the passed width and height (floats).
  4118. */
  4119. function Size(width, height) {
  4120. this.width = width;
  4121. this.height = height;
  4122. }
  4123. // Returns a string with the Size width and height.
  4124. Size.prototype.toString = function () {
  4125. return "{W: " + this.width + ", H: " + this.height + "}";
  4126. };
  4127. /**
  4128. * Returns the string "Size"
  4129. */
  4130. Size.prototype.getClassName = function () {
  4131. return "Size";
  4132. };
  4133. /**
  4134. * Returns the Size hash code.
  4135. */
  4136. Size.prototype.getHashCode = function () {
  4137. var hash = this.width || 0;
  4138. hash = (hash * 397) ^ (this.height || 0);
  4139. return hash;
  4140. };
  4141. /**
  4142. * Updates the current size from the passed one.
  4143. * Returns the updated Size.
  4144. */
  4145. Size.prototype.copyFrom = function (src) {
  4146. this.width = src.width;
  4147. this.height = src.height;
  4148. };
  4149. /**
  4150. * Updates in place the current Size from the passed floats.
  4151. * Returns the updated Size.
  4152. */
  4153. Size.prototype.copyFromFloats = function (width, height) {
  4154. this.width = width;
  4155. this.height = height;
  4156. return this;
  4157. };
  4158. /**
  4159. * Updates in place the current Size from the passed floats.
  4160. * Returns the updated Size.
  4161. */
  4162. Size.prototype.set = function (width, height) {
  4163. return this.copyFromFloats(width, height);
  4164. };
  4165. /**
  4166. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4167. */
  4168. Size.prototype.multiplyByFloats = function (w, h) {
  4169. return new Size(this.width * w, this.height * h);
  4170. };
  4171. /**
  4172. * Returns a new Size copied from the passed one.
  4173. */
  4174. Size.prototype.clone = function () {
  4175. return new Size(this.width, this.height);
  4176. };
  4177. /**
  4178. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4179. */
  4180. Size.prototype.equals = function (other) {
  4181. if (!other) {
  4182. return false;
  4183. }
  4184. return (this.width === other.width) && (this.height === other.height);
  4185. };
  4186. Object.defineProperty(Size.prototype, "surface", {
  4187. /**
  4188. * Returns the surface of the Size : width * height (float).
  4189. */
  4190. get: function () {
  4191. return this.width * this.height;
  4192. },
  4193. enumerable: true,
  4194. configurable: true
  4195. });
  4196. /**
  4197. * Returns a new Size set to (0.0, 0.0)
  4198. */
  4199. Size.Zero = function () {
  4200. return new Size(0.0, 0.0);
  4201. };
  4202. /**
  4203. * Returns a new Size set as the addition result of the current Size and the passed one.
  4204. */
  4205. Size.prototype.add = function (otherSize) {
  4206. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4207. return r;
  4208. };
  4209. /**
  4210. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4211. */
  4212. Size.prototype.subtract = function (otherSize) {
  4213. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4214. return r;
  4215. };
  4216. /**
  4217. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4218. */
  4219. Size.Lerp = function (start, end, amount) {
  4220. var w = start.width + ((end.width - start.width) * amount);
  4221. var h = start.height + ((end.height - start.height) * amount);
  4222. return new Size(w, h);
  4223. };
  4224. return Size;
  4225. }());
  4226. BABYLON.Size = Size;
  4227. var Quaternion = /** @class */ (function () {
  4228. /**
  4229. * Creates a new Quaternion from the passed floats.
  4230. */
  4231. function Quaternion(x, y, z, w) {
  4232. if (x === void 0) { x = 0.0; }
  4233. if (y === void 0) { y = 0.0; }
  4234. if (z === void 0) { z = 0.0; }
  4235. if (w === void 0) { w = 1.0; }
  4236. this.x = x;
  4237. this.y = y;
  4238. this.z = z;
  4239. this.w = w;
  4240. }
  4241. /**
  4242. * Returns a string with the Quaternion coordinates.
  4243. */
  4244. Quaternion.prototype.toString = function () {
  4245. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4246. };
  4247. /**
  4248. * Returns the string "Quaternion".
  4249. */
  4250. Quaternion.prototype.getClassName = function () {
  4251. return "Quaternion";
  4252. };
  4253. /**
  4254. * Returns the Quaternion hash code.
  4255. */
  4256. Quaternion.prototype.getHashCode = function () {
  4257. var hash = this.x || 0;
  4258. hash = (hash * 397) ^ (this.y || 0);
  4259. hash = (hash * 397) ^ (this.z || 0);
  4260. hash = (hash * 397) ^ (this.w || 0);
  4261. return hash;
  4262. };
  4263. /**
  4264. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4265. */
  4266. Quaternion.prototype.asArray = function () {
  4267. return [this.x, this.y, this.z, this.w];
  4268. };
  4269. /**
  4270. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4271. */
  4272. Quaternion.prototype.equals = function (otherQuaternion) {
  4273. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4274. };
  4275. /**
  4276. * Returns a new Quaternion copied from the current one.
  4277. */
  4278. Quaternion.prototype.clone = function () {
  4279. return new Quaternion(this.x, this.y, this.z, this.w);
  4280. };
  4281. /**
  4282. * Updates the current Quaternion from the passed one coordinates.
  4283. * Returns the updated Quaterion.
  4284. */
  4285. Quaternion.prototype.copyFrom = function (other) {
  4286. this.x = other.x;
  4287. this.y = other.y;
  4288. this.z = other.z;
  4289. this.w = other.w;
  4290. return this;
  4291. };
  4292. /**
  4293. * Updates the current Quaternion from the passed float coordinates.
  4294. * Returns the updated Quaterion.
  4295. */
  4296. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4297. this.x = x;
  4298. this.y = y;
  4299. this.z = z;
  4300. this.w = w;
  4301. return this;
  4302. };
  4303. /**
  4304. * Updates the current Quaternion from the passed float coordinates.
  4305. * Returns the updated Quaterion.
  4306. */
  4307. Quaternion.prototype.set = function (x, y, z, w) {
  4308. return this.copyFromFloats(x, y, z, w);
  4309. };
  4310. /**
  4311. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4312. */
  4313. Quaternion.prototype.add = function (other) {
  4314. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4315. };
  4316. /**
  4317. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4318. */
  4319. Quaternion.prototype.subtract = function (other) {
  4320. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4321. };
  4322. /**
  4323. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4324. */
  4325. Quaternion.prototype.scale = function (value) {
  4326. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4327. };
  4328. /**
  4329. * Scale the current Quaternion values by a factor to a given Quaternion
  4330. * @param scale defines the scale factor
  4331. * @param result defines the Quaternion object where to store the result
  4332. * @returns the unmodified current Quaternion
  4333. */
  4334. Quaternion.prototype.scaleToRef = function (scale, result) {
  4335. result.x = this.x * scale;
  4336. result.y = this.y * scale;
  4337. result.z = this.z * scale;
  4338. result.w = this.w * scale;
  4339. return this;
  4340. };
  4341. /**
  4342. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4343. * @param scale defines the scale factor
  4344. * @param result defines the Quaternion object where to store the result
  4345. * @returns the unmodified current Quaternion
  4346. */
  4347. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4348. result.x += this.x * scale;
  4349. result.y += this.y * scale;
  4350. result.z += this.z * scale;
  4351. result.w += this.w * scale;
  4352. return this;
  4353. };
  4354. /**
  4355. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4356. */
  4357. Quaternion.prototype.multiply = function (q1) {
  4358. var result = new Quaternion(0, 0, 0, 1.0);
  4359. this.multiplyToRef(q1, result);
  4360. return result;
  4361. };
  4362. /**
  4363. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4364. * Returns the current Quaternion.
  4365. */
  4366. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4367. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4368. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4369. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4370. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4371. result.copyFromFloats(x, y, z, w);
  4372. return this;
  4373. };
  4374. /**
  4375. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4376. * Returns the updated Quaternion.
  4377. */
  4378. Quaternion.prototype.multiplyInPlace = function (q1) {
  4379. this.multiplyToRef(q1, this);
  4380. return this;
  4381. };
  4382. /**
  4383. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4384. * Returns the current Quaternion.
  4385. */
  4386. Quaternion.prototype.conjugateToRef = function (ref) {
  4387. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4388. return this;
  4389. };
  4390. /**
  4391. * Conjugates in place the current Quaternion.
  4392. * Returns the updated Quaternion.
  4393. */
  4394. Quaternion.prototype.conjugateInPlace = function () {
  4395. this.x *= -1;
  4396. this.y *= -1;
  4397. this.z *= -1;
  4398. return this;
  4399. };
  4400. /**
  4401. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4402. */
  4403. Quaternion.prototype.conjugate = function () {
  4404. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4405. return result;
  4406. };
  4407. /**
  4408. * Returns the Quaternion length (float).
  4409. */
  4410. Quaternion.prototype.length = function () {
  4411. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4412. };
  4413. /**
  4414. * Normalize in place the current Quaternion.
  4415. * Returns the updated Quaternion.
  4416. */
  4417. Quaternion.prototype.normalize = function () {
  4418. var length = 1.0 / this.length();
  4419. this.x *= length;
  4420. this.y *= length;
  4421. this.z *= length;
  4422. this.w *= length;
  4423. return this;
  4424. };
  4425. /**
  4426. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4427. * @param order is a reserved parameter and is ignore for now
  4428. * @returns the new Vector3
  4429. */
  4430. Quaternion.prototype.toEulerAngles = function (order) {
  4431. if (order === void 0) { order = "YZX"; }
  4432. var result = Vector3.Zero();
  4433. this.toEulerAnglesToRef(result, order);
  4434. return result;
  4435. };
  4436. /**
  4437. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4438. * @param result defines the vector which will be filled with the Euler angles
  4439. * @param order is a reserved parameter and is ignore for now
  4440. * @returns the current Quaternion
  4441. */
  4442. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4443. if (order === void 0) { order = "YZX"; }
  4444. var qz = this.z;
  4445. var qx = this.x;
  4446. var qy = this.y;
  4447. var qw = this.w;
  4448. var sqw = qw * qw;
  4449. var sqz = qz * qz;
  4450. var sqx = qx * qx;
  4451. var sqy = qy * qy;
  4452. var zAxisY = qy * qz - qx * qw;
  4453. var limit = .4999999;
  4454. if (zAxisY < -limit) {
  4455. result.y = 2 * Math.atan2(qy, qw);
  4456. result.x = Math.PI / 2;
  4457. result.z = 0;
  4458. }
  4459. else if (zAxisY > limit) {
  4460. result.y = 2 * Math.atan2(qy, qw);
  4461. result.x = -Math.PI / 2;
  4462. result.z = 0;
  4463. }
  4464. else {
  4465. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4466. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4467. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4468. }
  4469. return this;
  4470. };
  4471. /**
  4472. * Updates the passed rotation matrix with the current Quaternion values.
  4473. * Returns the current Quaternion.
  4474. */
  4475. Quaternion.prototype.toRotationMatrix = function (result) {
  4476. var xx = this.x * this.x;
  4477. var yy = this.y * this.y;
  4478. var zz = this.z * this.z;
  4479. var xy = this.x * this.y;
  4480. var zw = this.z * this.w;
  4481. var zx = this.z * this.x;
  4482. var yw = this.y * this.w;
  4483. var yz = this.y * this.z;
  4484. var xw = this.x * this.w;
  4485. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4486. result.m[1] = 2.0 * (xy + zw);
  4487. result.m[2] = 2.0 * (zx - yw);
  4488. result.m[3] = 0;
  4489. result.m[4] = 2.0 * (xy - zw);
  4490. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4491. result.m[6] = 2.0 * (yz + xw);
  4492. result.m[7] = 0;
  4493. result.m[8] = 2.0 * (zx + yw);
  4494. result.m[9] = 2.0 * (yz - xw);
  4495. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4496. result.m[11] = 0;
  4497. result.m[12] = 0;
  4498. result.m[13] = 0;
  4499. result.m[14] = 0;
  4500. result.m[15] = 1.0;
  4501. result._markAsUpdated();
  4502. return this;
  4503. };
  4504. /**
  4505. * Updates the current Quaternion from the passed rotation matrix values.
  4506. * Returns the updated Quaternion.
  4507. */
  4508. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4509. Quaternion.FromRotationMatrixToRef(matrix, this);
  4510. return this;
  4511. };
  4512. // Statics
  4513. /**
  4514. * Returns a new Quaternion set from the passed rotation matrix values.
  4515. */
  4516. Quaternion.FromRotationMatrix = function (matrix) {
  4517. var result = new Quaternion();
  4518. Quaternion.FromRotationMatrixToRef(matrix, result);
  4519. return result;
  4520. };
  4521. /**
  4522. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4523. */
  4524. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4525. var data = matrix.m;
  4526. var m11 = data[0], m12 = data[4], m13 = data[8];
  4527. var m21 = data[1], m22 = data[5], m23 = data[9];
  4528. var m31 = data[2], m32 = data[6], m33 = data[10];
  4529. var trace = m11 + m22 + m33;
  4530. var s;
  4531. if (trace > 0) {
  4532. s = 0.5 / Math.sqrt(trace + 1.0);
  4533. result.w = 0.25 / s;
  4534. result.x = (m32 - m23) * s;
  4535. result.y = (m13 - m31) * s;
  4536. result.z = (m21 - m12) * s;
  4537. }
  4538. else if (m11 > m22 && m11 > m33) {
  4539. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4540. result.w = (m32 - m23) / s;
  4541. result.x = 0.25 * s;
  4542. result.y = (m12 + m21) / s;
  4543. result.z = (m13 + m31) / s;
  4544. }
  4545. else if (m22 > m33) {
  4546. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4547. result.w = (m13 - m31) / s;
  4548. result.x = (m12 + m21) / s;
  4549. result.y = 0.25 * s;
  4550. result.z = (m23 + m32) / s;
  4551. }
  4552. else {
  4553. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4554. result.w = (m21 - m12) / s;
  4555. result.x = (m13 + m31) / s;
  4556. result.y = (m23 + m32) / s;
  4557. result.z = 0.25 * s;
  4558. }
  4559. };
  4560. /**
  4561. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4562. */
  4563. Quaternion.Zero = function () {
  4564. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4565. };
  4566. /**
  4567. * Returns a new Quaternion as the inverted current Quaternion.
  4568. */
  4569. Quaternion.Inverse = function (q) {
  4570. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4571. };
  4572. /**
  4573. * Returns the identity Quaternion.
  4574. */
  4575. Quaternion.Identity = function () {
  4576. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4577. };
  4578. Quaternion.IsIdentity = function (quaternion) {
  4579. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4580. };
  4581. /**
  4582. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4583. */
  4584. Quaternion.RotationAxis = function (axis, angle) {
  4585. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4586. };
  4587. /**
  4588. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4589. */
  4590. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4591. var sin = Math.sin(angle / 2);
  4592. axis.normalize();
  4593. result.w = Math.cos(angle / 2);
  4594. result.x = axis.x * sin;
  4595. result.y = axis.y * sin;
  4596. result.z = axis.z * sin;
  4597. return result;
  4598. };
  4599. /**
  4600. * Retuns a new Quaternion set from the starting index of the passed array.
  4601. */
  4602. Quaternion.FromArray = function (array, offset) {
  4603. if (!offset) {
  4604. offset = 0;
  4605. }
  4606. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4607. };
  4608. /**
  4609. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4610. */
  4611. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4612. var q = new Quaternion();
  4613. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4614. return q;
  4615. };
  4616. /**
  4617. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4618. */
  4619. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4620. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4621. var halfRoll = roll * 0.5;
  4622. var halfPitch = pitch * 0.5;
  4623. var halfYaw = yaw * 0.5;
  4624. var sinRoll = Math.sin(halfRoll);
  4625. var cosRoll = Math.cos(halfRoll);
  4626. var sinPitch = Math.sin(halfPitch);
  4627. var cosPitch = Math.cos(halfPitch);
  4628. var sinYaw = Math.sin(halfYaw);
  4629. var cosYaw = Math.cos(halfYaw);
  4630. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4631. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4632. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4633. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4634. };
  4635. /**
  4636. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4637. */
  4638. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4639. var result = new Quaternion();
  4640. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4641. return result;
  4642. };
  4643. /**
  4644. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4645. */
  4646. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4647. // Produces a quaternion from Euler angles in the z-x-z orientation
  4648. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4649. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4650. var halfBeta = beta * 0.5;
  4651. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4652. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4653. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4654. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4655. };
  4656. /**
  4657. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4658. * cf to Vector3.RotationFromAxis() documentation.
  4659. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4660. */
  4661. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4662. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4663. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4664. return quat;
  4665. };
  4666. /**
  4667. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4668. * cf to Vector3.RotationFromAxis() documentation.
  4669. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4670. */
  4671. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4672. var rotMat = MathTmp.Matrix[0];
  4673. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4674. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4675. };
  4676. Quaternion.Slerp = function (left, right, amount) {
  4677. var result = Quaternion.Identity();
  4678. Quaternion.SlerpToRef(left, right, amount, result);
  4679. return result;
  4680. };
  4681. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4682. var num2;
  4683. var num3;
  4684. var num = amount;
  4685. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4686. var flag = false;
  4687. if (num4 < 0) {
  4688. flag = true;
  4689. num4 = -num4;
  4690. }
  4691. if (num4 > 0.999999) {
  4692. num3 = 1 - num;
  4693. num2 = flag ? -num : num;
  4694. }
  4695. else {
  4696. var num5 = Math.acos(num4);
  4697. var num6 = (1.0 / Math.sin(num5));
  4698. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4699. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4700. }
  4701. result.x = (num3 * left.x) + (num2 * right.x);
  4702. result.y = (num3 * left.y) + (num2 * right.y);
  4703. result.z = (num3 * left.z) + (num2 * right.z);
  4704. result.w = (num3 * left.w) + (num2 * right.w);
  4705. };
  4706. /**
  4707. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4708. */
  4709. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4710. var squared = amount * amount;
  4711. var cubed = amount * squared;
  4712. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4713. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4714. var part3 = (cubed - (2.0 * squared)) + amount;
  4715. var part4 = cubed - squared;
  4716. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4717. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4718. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4719. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4720. return new Quaternion(x, y, z, w);
  4721. };
  4722. return Quaternion;
  4723. }());
  4724. BABYLON.Quaternion = Quaternion;
  4725. var Matrix = /** @class */ (function () {
  4726. function Matrix() {
  4727. this._isIdentity = false;
  4728. this._isIdentityDirty = true;
  4729. this.m = new Float32Array(16);
  4730. this._markAsUpdated();
  4731. }
  4732. Matrix.prototype._markAsUpdated = function () {
  4733. this.updateFlag = Matrix._updateFlagSeed++;
  4734. this._isIdentityDirty = true;
  4735. };
  4736. // Properties
  4737. /**
  4738. * Boolean : True is the matrix is the identity matrix
  4739. */
  4740. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4741. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4742. if (this._isIdentityDirty) {
  4743. this._isIdentityDirty = false;
  4744. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4745. this._isIdentity = false;
  4746. }
  4747. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4748. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4749. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4750. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4751. this._isIdentity = false;
  4752. }
  4753. else {
  4754. this._isIdentity = true;
  4755. }
  4756. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4757. this._isIdentity = false;
  4758. }
  4759. }
  4760. return this._isIdentity;
  4761. };
  4762. /**
  4763. * Returns the matrix determinant (float).
  4764. */
  4765. Matrix.prototype.determinant = function () {
  4766. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4767. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4768. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4769. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4770. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4771. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4772. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4773. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4774. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4775. };
  4776. // Methods
  4777. /**
  4778. * Returns the matrix underlying array.
  4779. */
  4780. Matrix.prototype.toArray = function () {
  4781. return this.m;
  4782. };
  4783. /**
  4784. * Returns the matrix underlying array.
  4785. */
  4786. Matrix.prototype.asArray = function () {
  4787. return this.toArray();
  4788. };
  4789. /**
  4790. * Inverts in place the Matrix.
  4791. * Returns the Matrix inverted.
  4792. */
  4793. Matrix.prototype.invert = function () {
  4794. this.invertToRef(this);
  4795. return this;
  4796. };
  4797. /**
  4798. * Sets all the matrix elements to zero.
  4799. * Returns the Matrix.
  4800. */
  4801. Matrix.prototype.reset = function () {
  4802. for (var index = 0; index < 16; index++) {
  4803. this.m[index] = 0.0;
  4804. }
  4805. this._markAsUpdated();
  4806. return this;
  4807. };
  4808. /**
  4809. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4810. */
  4811. Matrix.prototype.add = function (other) {
  4812. var result = new Matrix();
  4813. this.addToRef(other, result);
  4814. return result;
  4815. };
  4816. /**
  4817. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4818. * Returns the Matrix.
  4819. */
  4820. Matrix.prototype.addToRef = function (other, result) {
  4821. for (var index = 0; index < 16; index++) {
  4822. result.m[index] = this.m[index] + other.m[index];
  4823. }
  4824. result._markAsUpdated();
  4825. return this;
  4826. };
  4827. /**
  4828. * Adds in place the passed matrix to the current Matrix.
  4829. * Returns the updated Matrix.
  4830. */
  4831. Matrix.prototype.addToSelf = function (other) {
  4832. for (var index = 0; index < 16; index++) {
  4833. this.m[index] += other.m[index];
  4834. }
  4835. this._markAsUpdated();
  4836. return this;
  4837. };
  4838. /**
  4839. * Sets the passed matrix with the current inverted Matrix.
  4840. * Returns the unmodified current Matrix.
  4841. */
  4842. Matrix.prototype.invertToRef = function (other) {
  4843. var l1 = this.m[0];
  4844. var l2 = this.m[1];
  4845. var l3 = this.m[2];
  4846. var l4 = this.m[3];
  4847. var l5 = this.m[4];
  4848. var l6 = this.m[5];
  4849. var l7 = this.m[6];
  4850. var l8 = this.m[7];
  4851. var l9 = this.m[8];
  4852. var l10 = this.m[9];
  4853. var l11 = this.m[10];
  4854. var l12 = this.m[11];
  4855. var l13 = this.m[12];
  4856. var l14 = this.m[13];
  4857. var l15 = this.m[14];
  4858. var l16 = this.m[15];
  4859. var l17 = (l11 * l16) - (l12 * l15);
  4860. var l18 = (l10 * l16) - (l12 * l14);
  4861. var l19 = (l10 * l15) - (l11 * l14);
  4862. var l20 = (l9 * l16) - (l12 * l13);
  4863. var l21 = (l9 * l15) - (l11 * l13);
  4864. var l22 = (l9 * l14) - (l10 * l13);
  4865. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4866. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4867. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4868. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4869. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4870. var l28 = (l7 * l16) - (l8 * l15);
  4871. var l29 = (l6 * l16) - (l8 * l14);
  4872. var l30 = (l6 * l15) - (l7 * l14);
  4873. var l31 = (l5 * l16) - (l8 * l13);
  4874. var l32 = (l5 * l15) - (l7 * l13);
  4875. var l33 = (l5 * l14) - (l6 * l13);
  4876. var l34 = (l7 * l12) - (l8 * l11);
  4877. var l35 = (l6 * l12) - (l8 * l10);
  4878. var l36 = (l6 * l11) - (l7 * l10);
  4879. var l37 = (l5 * l12) - (l8 * l9);
  4880. var l38 = (l5 * l11) - (l7 * l9);
  4881. var l39 = (l5 * l10) - (l6 * l9);
  4882. other.m[0] = l23 * l27;
  4883. other.m[4] = l24 * l27;
  4884. other.m[8] = l25 * l27;
  4885. other.m[12] = l26 * l27;
  4886. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4887. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4888. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4889. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4890. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4891. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4892. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4893. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4894. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4895. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4896. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4897. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4898. other._markAsUpdated();
  4899. return this;
  4900. };
  4901. /**
  4902. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4903. * Returns the updated Matrix.
  4904. */
  4905. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4906. this.m[12] = x;
  4907. this.m[13] = y;
  4908. this.m[14] = z;
  4909. this._markAsUpdated();
  4910. return this;
  4911. };
  4912. /**
  4913. * Inserts the translation vector in the current Matrix.
  4914. * Returns the updated Matrix.
  4915. */
  4916. Matrix.prototype.setTranslation = function (vector3) {
  4917. this.m[12] = vector3.x;
  4918. this.m[13] = vector3.y;
  4919. this.m[14] = vector3.z;
  4920. this._markAsUpdated();
  4921. return this;
  4922. };
  4923. /**
  4924. * Returns a new Vector3 as the extracted translation from the Matrix.
  4925. */
  4926. Matrix.prototype.getTranslation = function () {
  4927. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4928. };
  4929. /**
  4930. * Fill a Vector3 with the extracted translation from the Matrix.
  4931. */
  4932. Matrix.prototype.getTranslationToRef = function (result) {
  4933. result.x = this.m[12];
  4934. result.y = this.m[13];
  4935. result.z = this.m[14];
  4936. return this;
  4937. };
  4938. /**
  4939. * Remove rotation and scaling part from the Matrix.
  4940. * Returns the updated Matrix.
  4941. */
  4942. Matrix.prototype.removeRotationAndScaling = function () {
  4943. this.setRowFromFloats(0, 1, 0, 0, 0);
  4944. this.setRowFromFloats(1, 0, 1, 0, 0);
  4945. this.setRowFromFloats(2, 0, 0, 1, 0);
  4946. return this;
  4947. };
  4948. /**
  4949. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4950. */
  4951. Matrix.prototype.multiply = function (other) {
  4952. var result = new Matrix();
  4953. this.multiplyToRef(other, result);
  4954. return result;
  4955. };
  4956. /**
  4957. * Updates the current Matrix from the passed one values.
  4958. * Returns the updated Matrix.
  4959. */
  4960. Matrix.prototype.copyFrom = function (other) {
  4961. for (var index = 0; index < 16; index++) {
  4962. this.m[index] = other.m[index];
  4963. }
  4964. this._markAsUpdated();
  4965. return this;
  4966. };
  4967. /**
  4968. * Populates the passed array from the starting index with the Matrix values.
  4969. * Returns the Matrix.
  4970. */
  4971. Matrix.prototype.copyToArray = function (array, offset) {
  4972. if (offset === void 0) { offset = 0; }
  4973. for (var index = 0; index < 16; index++) {
  4974. array[offset + index] = this.m[index];
  4975. }
  4976. return this;
  4977. };
  4978. /**
  4979. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4980. */
  4981. Matrix.prototype.multiplyToRef = function (other, result) {
  4982. this.multiplyToArray(other, result.m, 0);
  4983. result._markAsUpdated();
  4984. return this;
  4985. };
  4986. /**
  4987. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4988. */
  4989. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4990. var tm0 = this.m[0];
  4991. var tm1 = this.m[1];
  4992. var tm2 = this.m[2];
  4993. var tm3 = this.m[3];
  4994. var tm4 = this.m[4];
  4995. var tm5 = this.m[5];
  4996. var tm6 = this.m[6];
  4997. var tm7 = this.m[7];
  4998. var tm8 = this.m[8];
  4999. var tm9 = this.m[9];
  5000. var tm10 = this.m[10];
  5001. var tm11 = this.m[11];
  5002. var tm12 = this.m[12];
  5003. var tm13 = this.m[13];
  5004. var tm14 = this.m[14];
  5005. var tm15 = this.m[15];
  5006. var om0 = other.m[0];
  5007. var om1 = other.m[1];
  5008. var om2 = other.m[2];
  5009. var om3 = other.m[3];
  5010. var om4 = other.m[4];
  5011. var om5 = other.m[5];
  5012. var om6 = other.m[6];
  5013. var om7 = other.m[7];
  5014. var om8 = other.m[8];
  5015. var om9 = other.m[9];
  5016. var om10 = other.m[10];
  5017. var om11 = other.m[11];
  5018. var om12 = other.m[12];
  5019. var om13 = other.m[13];
  5020. var om14 = other.m[14];
  5021. var om15 = other.m[15];
  5022. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5023. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5024. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5025. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5026. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5027. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5028. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5029. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5030. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5031. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5032. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5033. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5034. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5035. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5036. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5037. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5038. return this;
  5039. };
  5040. /**
  5041. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5042. */
  5043. Matrix.prototype.equals = function (value) {
  5044. return value &&
  5045. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5046. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5047. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5048. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5049. };
  5050. /**
  5051. * Returns a new Matrix from the current Matrix.
  5052. */
  5053. Matrix.prototype.clone = function () {
  5054. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5055. };
  5056. /**
  5057. * Returns the string "Matrix"
  5058. */
  5059. Matrix.prototype.getClassName = function () {
  5060. return "Matrix";
  5061. };
  5062. /**
  5063. * Returns the Matrix hash code.
  5064. */
  5065. Matrix.prototype.getHashCode = function () {
  5066. var hash = this.m[0] || 0;
  5067. for (var i = 1; i < 16; i++) {
  5068. hash = (hash * 397) ^ (this.m[i] || 0);
  5069. }
  5070. return hash;
  5071. };
  5072. /**
  5073. * Decomposes the current Matrix into :
  5074. * - a scale vector3 passed as a reference to update,
  5075. * - a rotation quaternion passed as a reference to update,
  5076. * - a translation vector3 passed as a reference to update.
  5077. * Returns the true if operation was successful.
  5078. */
  5079. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5080. translation.x = this.m[12];
  5081. translation.y = this.m[13];
  5082. translation.z = this.m[14];
  5083. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5084. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5085. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5086. if (this.determinant() <= 0) {
  5087. scale.y *= -1;
  5088. }
  5089. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5090. rotation.x = 0;
  5091. rotation.y = 0;
  5092. rotation.z = 0;
  5093. rotation.w = 1;
  5094. return false;
  5095. }
  5096. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5097. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5098. return true;
  5099. };
  5100. /**
  5101. * Returns the index-th row of the current matrix as a new Vector4.
  5102. */
  5103. Matrix.prototype.getRow = function (index) {
  5104. if (index < 0 || index > 3) {
  5105. return null;
  5106. }
  5107. var i = index * 4;
  5108. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5109. };
  5110. /**
  5111. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5112. * Returns the updated Matrix.
  5113. */
  5114. Matrix.prototype.setRow = function (index, row) {
  5115. if (index < 0 || index > 3) {
  5116. return this;
  5117. }
  5118. var i = index * 4;
  5119. this.m[i + 0] = row.x;
  5120. this.m[i + 1] = row.y;
  5121. this.m[i + 2] = row.z;
  5122. this.m[i + 3] = row.w;
  5123. this._markAsUpdated();
  5124. return this;
  5125. };
  5126. /**
  5127. * Compute the transpose of the matrix.
  5128. * Returns a new Matrix.
  5129. */
  5130. Matrix.prototype.transpose = function () {
  5131. return Matrix.Transpose(this);
  5132. };
  5133. /**
  5134. * Compute the transpose of the matrix.
  5135. * Returns the current matrix.
  5136. */
  5137. Matrix.prototype.transposeToRef = function (result) {
  5138. Matrix.TransposeToRef(this, result);
  5139. return this;
  5140. };
  5141. /**
  5142. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5143. * Returns the updated Matrix.
  5144. */
  5145. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5146. if (index < 0 || index > 3) {
  5147. return this;
  5148. }
  5149. var i = index * 4;
  5150. this.m[i + 0] = x;
  5151. this.m[i + 1] = y;
  5152. this.m[i + 2] = z;
  5153. this.m[i + 3] = w;
  5154. this._markAsUpdated();
  5155. return this;
  5156. };
  5157. /**
  5158. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5159. * @param scale defines the scale factor
  5160. * @returns a new Matrix
  5161. */
  5162. Matrix.prototype.scale = function (scale) {
  5163. var result = new Matrix();
  5164. this.scaleToRef(scale, result);
  5165. return result;
  5166. };
  5167. /**
  5168. * Scale the current Matrix values by a factor to a given result Matrix
  5169. * @param scale defines the scale factor
  5170. * @param result defines the Matrix to store the result
  5171. * @returns the current Matrix
  5172. */
  5173. Matrix.prototype.scaleToRef = function (scale, result) {
  5174. for (var index = 0; index < 16; index++) {
  5175. result.m[index] = this.m[index] * scale;
  5176. }
  5177. result._markAsUpdated();
  5178. return this;
  5179. };
  5180. /**
  5181. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5182. * @param scale defines the scale factor
  5183. * @param result defines the Matrix to store the result
  5184. * @returns the current Matrix
  5185. */
  5186. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5187. for (var index = 0; index < 16; index++) {
  5188. result.m[index] += this.m[index] * scale;
  5189. }
  5190. result._markAsUpdated();
  5191. return this;
  5192. };
  5193. /**
  5194. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5195. * @param ref matrix to store the result
  5196. */
  5197. Matrix.prototype.toNormalMatrix = function (ref) {
  5198. this.invertToRef(ref);
  5199. ref.transpose();
  5200. var m = ref.m;
  5201. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5202. };
  5203. /**
  5204. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5205. */
  5206. Matrix.prototype.getRotationMatrix = function () {
  5207. var result = Matrix.Identity();
  5208. this.getRotationMatrixToRef(result);
  5209. return result;
  5210. };
  5211. /**
  5212. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5213. * Returns the current Matrix.
  5214. */
  5215. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5216. var m = this.m;
  5217. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5218. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5219. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5220. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5221. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5222. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5223. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5224. return this;
  5225. };
  5226. // Statics
  5227. /**
  5228. * Returns a new Matrix set from the starting index of the passed array.
  5229. */
  5230. Matrix.FromArray = function (array, offset) {
  5231. var result = new Matrix();
  5232. if (!offset) {
  5233. offset = 0;
  5234. }
  5235. Matrix.FromArrayToRef(array, offset, result);
  5236. return result;
  5237. };
  5238. /**
  5239. * Sets the passed "result" matrix from the starting index of the passed array.
  5240. */
  5241. Matrix.FromArrayToRef = function (array, offset, result) {
  5242. for (var index = 0; index < 16; index++) {
  5243. result.m[index] = array[index + offset];
  5244. }
  5245. result._markAsUpdated();
  5246. };
  5247. /**
  5248. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5249. */
  5250. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5251. for (var index = 0; index < 16; index++) {
  5252. result.m[index] = array[index + offset] * scale;
  5253. }
  5254. result._markAsUpdated();
  5255. };
  5256. /**
  5257. * Sets the passed matrix "result" with the 16 passed floats.
  5258. */
  5259. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5260. result.m[0] = initialM11;
  5261. result.m[1] = initialM12;
  5262. result.m[2] = initialM13;
  5263. result.m[3] = initialM14;
  5264. result.m[4] = initialM21;
  5265. result.m[5] = initialM22;
  5266. result.m[6] = initialM23;
  5267. result.m[7] = initialM24;
  5268. result.m[8] = initialM31;
  5269. result.m[9] = initialM32;
  5270. result.m[10] = initialM33;
  5271. result.m[11] = initialM34;
  5272. result.m[12] = initialM41;
  5273. result.m[13] = initialM42;
  5274. result.m[14] = initialM43;
  5275. result.m[15] = initialM44;
  5276. result._markAsUpdated();
  5277. };
  5278. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5279. /**
  5280. * Static identity matrix to be used as readonly matrix
  5281. * Must not be updated.
  5282. */
  5283. get: function () {
  5284. return Matrix._identityReadOnly;
  5285. },
  5286. enumerable: true,
  5287. configurable: true
  5288. });
  5289. /**
  5290. * Returns a new Matrix set from the 16 passed floats.
  5291. */
  5292. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5293. var result = new Matrix();
  5294. result.m[0] = initialM11;
  5295. result.m[1] = initialM12;
  5296. result.m[2] = initialM13;
  5297. result.m[3] = initialM14;
  5298. result.m[4] = initialM21;
  5299. result.m[5] = initialM22;
  5300. result.m[6] = initialM23;
  5301. result.m[7] = initialM24;
  5302. result.m[8] = initialM31;
  5303. result.m[9] = initialM32;
  5304. result.m[10] = initialM33;
  5305. result.m[11] = initialM34;
  5306. result.m[12] = initialM41;
  5307. result.m[13] = initialM42;
  5308. result.m[14] = initialM43;
  5309. result.m[15] = initialM44;
  5310. return result;
  5311. };
  5312. /**
  5313. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5314. */
  5315. Matrix.Compose = function (scale, rotation, translation) {
  5316. var result = Matrix.Identity();
  5317. Matrix.ComposeToRef(scale, rotation, translation, result);
  5318. return result;
  5319. };
  5320. /**
  5321. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5322. */
  5323. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5324. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5325. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5326. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5327. result.setTranslation(translation);
  5328. };
  5329. /**
  5330. * Returns a new indentity Matrix.
  5331. */
  5332. Matrix.Identity = function () {
  5333. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5334. };
  5335. /**
  5336. * Sets the passed "result" as an identity matrix.
  5337. */
  5338. Matrix.IdentityToRef = function (result) {
  5339. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5340. };
  5341. /**
  5342. * Returns a new zero Matrix.
  5343. */
  5344. Matrix.Zero = function () {
  5345. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5346. };
  5347. /**
  5348. * Returns a new rotation matrix for "angle" radians around the X axis.
  5349. */
  5350. Matrix.RotationX = function (angle) {
  5351. var result = new Matrix();
  5352. Matrix.RotationXToRef(angle, result);
  5353. return result;
  5354. };
  5355. /**
  5356. * Returns a new Matrix as the passed inverted one.
  5357. */
  5358. Matrix.Invert = function (source) {
  5359. var result = new Matrix();
  5360. source.invertToRef(result);
  5361. return result;
  5362. };
  5363. /**
  5364. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5365. */
  5366. Matrix.RotationXToRef = function (angle, result) {
  5367. var s = Math.sin(angle);
  5368. var c = Math.cos(angle);
  5369. result.m[0] = 1.0;
  5370. result.m[15] = 1.0;
  5371. result.m[5] = c;
  5372. result.m[10] = c;
  5373. result.m[9] = -s;
  5374. result.m[6] = s;
  5375. result.m[1] = 0.0;
  5376. result.m[2] = 0.0;
  5377. result.m[3] = 0.0;
  5378. result.m[4] = 0.0;
  5379. result.m[7] = 0.0;
  5380. result.m[8] = 0.0;
  5381. result.m[11] = 0.0;
  5382. result.m[12] = 0.0;
  5383. result.m[13] = 0.0;
  5384. result.m[14] = 0.0;
  5385. result._markAsUpdated();
  5386. };
  5387. /**
  5388. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5389. */
  5390. Matrix.RotationY = function (angle) {
  5391. var result = new Matrix();
  5392. Matrix.RotationYToRef(angle, result);
  5393. return result;
  5394. };
  5395. /**
  5396. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5397. */
  5398. Matrix.RotationYToRef = function (angle, result) {
  5399. var s = Math.sin(angle);
  5400. var c = Math.cos(angle);
  5401. result.m[5] = 1.0;
  5402. result.m[15] = 1.0;
  5403. result.m[0] = c;
  5404. result.m[2] = -s;
  5405. result.m[8] = s;
  5406. result.m[10] = c;
  5407. result.m[1] = 0.0;
  5408. result.m[3] = 0.0;
  5409. result.m[4] = 0.0;
  5410. result.m[6] = 0.0;
  5411. result.m[7] = 0.0;
  5412. result.m[9] = 0.0;
  5413. result.m[11] = 0.0;
  5414. result.m[12] = 0.0;
  5415. result.m[13] = 0.0;
  5416. result.m[14] = 0.0;
  5417. result._markAsUpdated();
  5418. };
  5419. /**
  5420. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5421. */
  5422. Matrix.RotationZ = function (angle) {
  5423. var result = new Matrix();
  5424. Matrix.RotationZToRef(angle, result);
  5425. return result;
  5426. };
  5427. /**
  5428. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5429. */
  5430. Matrix.RotationZToRef = function (angle, result) {
  5431. var s = Math.sin(angle);
  5432. var c = Math.cos(angle);
  5433. result.m[10] = 1.0;
  5434. result.m[15] = 1.0;
  5435. result.m[0] = c;
  5436. result.m[1] = s;
  5437. result.m[4] = -s;
  5438. result.m[5] = c;
  5439. result.m[2] = 0.0;
  5440. result.m[3] = 0.0;
  5441. result.m[6] = 0.0;
  5442. result.m[7] = 0.0;
  5443. result.m[8] = 0.0;
  5444. result.m[9] = 0.0;
  5445. result.m[11] = 0.0;
  5446. result.m[12] = 0.0;
  5447. result.m[13] = 0.0;
  5448. result.m[14] = 0.0;
  5449. result._markAsUpdated();
  5450. };
  5451. /**
  5452. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5453. */
  5454. Matrix.RotationAxis = function (axis, angle) {
  5455. var result = Matrix.Zero();
  5456. Matrix.RotationAxisToRef(axis, angle, result);
  5457. return result;
  5458. };
  5459. /**
  5460. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5461. */
  5462. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5463. var s = Math.sin(-angle);
  5464. var c = Math.cos(-angle);
  5465. var c1 = 1 - c;
  5466. axis.normalize();
  5467. result.m[0] = (axis.x * axis.x) * c1 + c;
  5468. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5469. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5470. result.m[3] = 0.0;
  5471. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5472. result.m[5] = (axis.y * axis.y) * c1 + c;
  5473. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5474. result.m[7] = 0.0;
  5475. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5476. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5477. result.m[10] = (axis.z * axis.z) * c1 + c;
  5478. result.m[11] = 0.0;
  5479. result.m[15] = 1.0;
  5480. result._markAsUpdated();
  5481. };
  5482. /**
  5483. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5484. */
  5485. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5486. var result = new Matrix();
  5487. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5488. return result;
  5489. };
  5490. /**
  5491. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5492. */
  5493. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5494. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5495. this._tempQuaternion.toRotationMatrix(result);
  5496. };
  5497. /**
  5498. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5499. */
  5500. Matrix.Scaling = function (x, y, z) {
  5501. var result = Matrix.Zero();
  5502. Matrix.ScalingToRef(x, y, z, result);
  5503. return result;
  5504. };
  5505. /**
  5506. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5507. */
  5508. Matrix.ScalingToRef = function (x, y, z, result) {
  5509. result.m[0] = x;
  5510. result.m[1] = 0.0;
  5511. result.m[2] = 0.0;
  5512. result.m[3] = 0.0;
  5513. result.m[4] = 0.0;
  5514. result.m[5] = y;
  5515. result.m[6] = 0.0;
  5516. result.m[7] = 0.0;
  5517. result.m[8] = 0.0;
  5518. result.m[9] = 0.0;
  5519. result.m[10] = z;
  5520. result.m[11] = 0.0;
  5521. result.m[12] = 0.0;
  5522. result.m[13] = 0.0;
  5523. result.m[14] = 0.0;
  5524. result.m[15] = 1.0;
  5525. result._markAsUpdated();
  5526. };
  5527. /**
  5528. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5529. */
  5530. Matrix.Translation = function (x, y, z) {
  5531. var result = Matrix.Identity();
  5532. Matrix.TranslationToRef(x, y, z, result);
  5533. return result;
  5534. };
  5535. /**
  5536. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5537. */
  5538. Matrix.TranslationToRef = function (x, y, z, result) {
  5539. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  5540. };
  5541. /**
  5542. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5543. * @param startValue defines the start value
  5544. * @param endValue defines the end value
  5545. * @param gradient defines the gradient factor
  5546. * @returns the new matrix
  5547. */
  5548. Matrix.Lerp = function (startValue, endValue, gradient) {
  5549. var result = Matrix.Zero();
  5550. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5551. return result;
  5552. };
  5553. /**
  5554. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5555. * @param startValue defines the start value
  5556. * @param endValue defines the end value
  5557. * @param gradient defines the gradient factor
  5558. * @param result defines the Matrix object where to store data
  5559. */
  5560. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5561. for (var index = 0; index < 16; index++) {
  5562. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5563. }
  5564. result._markAsUpdated();
  5565. };
  5566. /**
  5567. * Returns a new Matrix whose values are computed by :
  5568. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5569. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5570. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5571. */
  5572. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5573. var startScale = new Vector3(0, 0, 0);
  5574. var startRotation = new Quaternion();
  5575. var startTranslation = new Vector3(0, 0, 0);
  5576. startValue.decompose(startScale, startRotation, startTranslation);
  5577. var endScale = new Vector3(0, 0, 0);
  5578. var endRotation = new Quaternion();
  5579. var endTranslation = new Vector3(0, 0, 0);
  5580. endValue.decompose(endScale, endRotation, endTranslation);
  5581. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5582. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5583. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5584. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5585. };
  5586. /**
  5587. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5588. * This methods works for a Left-Handed system.
  5589. */
  5590. Matrix.LookAtLH = function (eye, target, up) {
  5591. var result = Matrix.Zero();
  5592. Matrix.LookAtLHToRef(eye, target, up, result);
  5593. return result;
  5594. };
  5595. /**
  5596. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5597. * This methods works for a Left-Handed system.
  5598. */
  5599. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5600. // Z axis
  5601. target.subtractToRef(eye, this._zAxis);
  5602. this._zAxis.normalize();
  5603. // X axis
  5604. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5605. if (this._xAxis.lengthSquared() === 0) {
  5606. this._xAxis.x = 1.0;
  5607. }
  5608. else {
  5609. this._xAxis.normalize();
  5610. }
  5611. // Y axis
  5612. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5613. this._yAxis.normalize();
  5614. // Eye angles
  5615. var ex = -Vector3.Dot(this._xAxis, eye);
  5616. var ey = -Vector3.Dot(this._yAxis, eye);
  5617. var ez = -Vector3.Dot(this._zAxis, eye);
  5618. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  5619. };
  5620. /**
  5621. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5622. * This methods works for a Right-Handed system.
  5623. */
  5624. Matrix.LookAtRH = function (eye, target, up) {
  5625. var result = Matrix.Zero();
  5626. Matrix.LookAtRHToRef(eye, target, up, result);
  5627. return result;
  5628. };
  5629. /**
  5630. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5631. * This methods works for a Left-Handed system.
  5632. */
  5633. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5634. // Z axis
  5635. eye.subtractToRef(target, this._zAxis);
  5636. this._zAxis.normalize();
  5637. // X axis
  5638. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5639. if (this._xAxis.lengthSquared() === 0) {
  5640. this._xAxis.x = 1.0;
  5641. }
  5642. else {
  5643. this._xAxis.normalize();
  5644. }
  5645. // Y axis
  5646. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5647. this._yAxis.normalize();
  5648. // Eye angles
  5649. var ex = -Vector3.Dot(this._xAxis, eye);
  5650. var ey = -Vector3.Dot(this._yAxis, eye);
  5651. var ez = -Vector3.Dot(this._zAxis, eye);
  5652. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  5653. };
  5654. /**
  5655. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5656. */
  5657. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5658. var matrix = Matrix.Zero();
  5659. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5660. return matrix;
  5661. };
  5662. /**
  5663. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5664. */
  5665. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5666. var n = znear;
  5667. var f = zfar;
  5668. var a = 2.0 / width;
  5669. var b = 2.0 / height;
  5670. var c = 2.0 / (f - n);
  5671. var d = -(f + n) / (f - n);
  5672. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  5673. };
  5674. /**
  5675. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5676. */
  5677. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5678. var matrix = Matrix.Zero();
  5679. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5680. return matrix;
  5681. };
  5682. /**
  5683. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5684. */
  5685. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5686. var n = znear;
  5687. var f = zfar;
  5688. var a = 2.0 / (right - left);
  5689. var b = 2.0 / (top - bottom);
  5690. var c = 2.0 / (f - n);
  5691. var d = -(f + n) / (f - n);
  5692. var i0 = (left + right) / (left - right);
  5693. var i1 = (top + bottom) / (bottom - top);
  5694. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  5695. };
  5696. /**
  5697. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5698. */
  5699. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5700. var matrix = Matrix.Zero();
  5701. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5702. return matrix;
  5703. };
  5704. /**
  5705. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5706. */
  5707. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5708. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5709. result.m[10] *= -1.0;
  5710. };
  5711. /**
  5712. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5713. */
  5714. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5715. var matrix = Matrix.Zero();
  5716. var n = znear;
  5717. var f = zfar;
  5718. var a = 2.0 * n / width;
  5719. var b = 2.0 * n / height;
  5720. var c = (f + n) / (f - n);
  5721. var d = -2.0 * f * n / (f - n);
  5722. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  5723. return matrix;
  5724. };
  5725. /**
  5726. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5727. */
  5728. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5729. var matrix = Matrix.Zero();
  5730. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5731. return matrix;
  5732. };
  5733. /**
  5734. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5735. */
  5736. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5737. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5738. var n = znear;
  5739. var f = zfar;
  5740. var t = 1.0 / (Math.tan(fov * 0.5));
  5741. var a = isVerticalFovFixed ? (t / aspect) : t;
  5742. var b = isVerticalFovFixed ? t : (t * aspect);
  5743. var c = (f + n) / (f - n);
  5744. var d = -2.0 * f * n / (f - n);
  5745. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  5746. };
  5747. /**
  5748. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5749. */
  5750. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5751. var matrix = Matrix.Zero();
  5752. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5753. return matrix;
  5754. };
  5755. /**
  5756. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5757. */
  5758. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5759. //alternatively this could be expressed as:
  5760. // m = PerspectiveFovLHToRef
  5761. // m[10] *= -1.0;
  5762. // m[11] *= -1.0;
  5763. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5764. var n = znear;
  5765. var f = zfar;
  5766. var t = 1.0 / (Math.tan(fov * 0.5));
  5767. var a = isVerticalFovFixed ? (t / aspect) : t;
  5768. var b = isVerticalFovFixed ? t : (t * aspect);
  5769. var c = -(f + n) / (f - n);
  5770. var d = -2 * f * n / (f - n);
  5771. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  5772. };
  5773. /**
  5774. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5775. */
  5776. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5777. if (rightHanded === void 0) { rightHanded = false; }
  5778. var rightHandedFactor = rightHanded ? -1 : 1;
  5779. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5780. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5781. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5782. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5783. var xScale = 2.0 / (leftTan + rightTan);
  5784. var yScale = 2.0 / (upTan + downTan);
  5785. result.m[0] = xScale;
  5786. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5787. result.m[5] = yScale;
  5788. result.m[6] = result.m[7] = 0.0;
  5789. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5790. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5791. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5792. result.m[10] = -zfar / (znear - zfar);
  5793. result.m[11] = 1.0 * rightHandedFactor;
  5794. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5795. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5796. // result.m[14] = (znear * zfar) / (znear - zfar);
  5797. result._markAsUpdated();
  5798. };
  5799. /**
  5800. * Returns the final transformation matrix : world * view * projection * viewport
  5801. */
  5802. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5803. var cw = viewport.width;
  5804. var ch = viewport.height;
  5805. var cx = viewport.x;
  5806. var cy = viewport.y;
  5807. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  5808. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5809. };
  5810. /**
  5811. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5812. */
  5813. Matrix.GetAsMatrix2x2 = function (matrix) {
  5814. return new Float32Array([
  5815. matrix.m[0], matrix.m[1],
  5816. matrix.m[4], matrix.m[5]
  5817. ]);
  5818. };
  5819. /**
  5820. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5821. */
  5822. Matrix.GetAsMatrix3x3 = function (matrix) {
  5823. return new Float32Array([
  5824. matrix.m[0], matrix.m[1], matrix.m[2],
  5825. matrix.m[4], matrix.m[5], matrix.m[6],
  5826. matrix.m[8], matrix.m[9], matrix.m[10]
  5827. ]);
  5828. };
  5829. /**
  5830. * Compute the transpose of the passed Matrix.
  5831. * Returns a new Matrix.
  5832. */
  5833. Matrix.Transpose = function (matrix) {
  5834. var result = new Matrix();
  5835. Matrix.TransposeToRef(matrix, result);
  5836. return result;
  5837. };
  5838. /**
  5839. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5840. */
  5841. Matrix.TransposeToRef = function (matrix, result) {
  5842. result.m[0] = matrix.m[0];
  5843. result.m[1] = matrix.m[4];
  5844. result.m[2] = matrix.m[8];
  5845. result.m[3] = matrix.m[12];
  5846. result.m[4] = matrix.m[1];
  5847. result.m[5] = matrix.m[5];
  5848. result.m[6] = matrix.m[9];
  5849. result.m[7] = matrix.m[13];
  5850. result.m[8] = matrix.m[2];
  5851. result.m[9] = matrix.m[6];
  5852. result.m[10] = matrix.m[10];
  5853. result.m[11] = matrix.m[14];
  5854. result.m[12] = matrix.m[3];
  5855. result.m[13] = matrix.m[7];
  5856. result.m[14] = matrix.m[11];
  5857. result.m[15] = matrix.m[15];
  5858. };
  5859. /**
  5860. * Returns a new Matrix as the reflection matrix across the passed plane.
  5861. */
  5862. Matrix.Reflection = function (plane) {
  5863. var matrix = new Matrix();
  5864. Matrix.ReflectionToRef(plane, matrix);
  5865. return matrix;
  5866. };
  5867. /**
  5868. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5869. */
  5870. Matrix.ReflectionToRef = function (plane, result) {
  5871. plane.normalize();
  5872. var x = plane.normal.x;
  5873. var y = plane.normal.y;
  5874. var z = plane.normal.z;
  5875. var temp = -2 * x;
  5876. var temp2 = -2 * y;
  5877. var temp3 = -2 * z;
  5878. result.m[0] = (temp * x) + 1;
  5879. result.m[1] = temp2 * x;
  5880. result.m[2] = temp3 * x;
  5881. result.m[3] = 0.0;
  5882. result.m[4] = temp * y;
  5883. result.m[5] = (temp2 * y) + 1;
  5884. result.m[6] = temp3 * y;
  5885. result.m[7] = 0.0;
  5886. result.m[8] = temp * z;
  5887. result.m[9] = temp2 * z;
  5888. result.m[10] = (temp3 * z) + 1;
  5889. result.m[11] = 0.0;
  5890. result.m[12] = temp * plane.d;
  5891. result.m[13] = temp2 * plane.d;
  5892. result.m[14] = temp3 * plane.d;
  5893. result.m[15] = 1.0;
  5894. result._markAsUpdated();
  5895. };
  5896. /**
  5897. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5898. */
  5899. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5900. result.m[0] = xaxis.x;
  5901. result.m[1] = xaxis.y;
  5902. result.m[2] = xaxis.z;
  5903. result.m[3] = 0.0;
  5904. result.m[4] = yaxis.x;
  5905. result.m[5] = yaxis.y;
  5906. result.m[6] = yaxis.z;
  5907. result.m[7] = 0.0;
  5908. result.m[8] = zaxis.x;
  5909. result.m[9] = zaxis.y;
  5910. result.m[10] = zaxis.z;
  5911. result.m[11] = 0.0;
  5912. result.m[12] = 0.0;
  5913. result.m[13] = 0.0;
  5914. result.m[14] = 0.0;
  5915. result.m[15] = 1.0;
  5916. result._markAsUpdated();
  5917. };
  5918. /**
  5919. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5920. */
  5921. Matrix.FromQuaternionToRef = function (quat, result) {
  5922. var xx = quat.x * quat.x;
  5923. var yy = quat.y * quat.y;
  5924. var zz = quat.z * quat.z;
  5925. var xy = quat.x * quat.y;
  5926. var zw = quat.z * quat.w;
  5927. var zx = quat.z * quat.x;
  5928. var yw = quat.y * quat.w;
  5929. var yz = quat.y * quat.z;
  5930. var xw = quat.x * quat.w;
  5931. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5932. result.m[1] = 2.0 * (xy + zw);
  5933. result.m[2] = 2.0 * (zx - yw);
  5934. result.m[3] = 0.0;
  5935. result.m[4] = 2.0 * (xy - zw);
  5936. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5937. result.m[6] = 2.0 * (yz + xw);
  5938. result.m[7] = 0.0;
  5939. result.m[8] = 2.0 * (zx + yw);
  5940. result.m[9] = 2.0 * (yz - xw);
  5941. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5942. result.m[11] = 0.0;
  5943. result.m[12] = 0.0;
  5944. result.m[13] = 0.0;
  5945. result.m[14] = 0.0;
  5946. result.m[15] = 1.0;
  5947. result._markAsUpdated();
  5948. };
  5949. Matrix._tempQuaternion = new Quaternion();
  5950. Matrix._xAxis = Vector3.Zero();
  5951. Matrix._yAxis = Vector3.Zero();
  5952. Matrix._zAxis = Vector3.Zero();
  5953. Matrix._updateFlagSeed = 0;
  5954. Matrix._identityReadOnly = Matrix.Identity();
  5955. return Matrix;
  5956. }());
  5957. BABYLON.Matrix = Matrix;
  5958. var Plane = /** @class */ (function () {
  5959. /**
  5960. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5961. */
  5962. function Plane(a, b, c, d) {
  5963. this.normal = new Vector3(a, b, c);
  5964. this.d = d;
  5965. }
  5966. /**
  5967. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5968. */
  5969. Plane.prototype.asArray = function () {
  5970. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5971. };
  5972. // Methods
  5973. /**
  5974. * Returns a new plane copied from the current Plane.
  5975. */
  5976. Plane.prototype.clone = function () {
  5977. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5978. };
  5979. /**
  5980. * Returns the string "Plane".
  5981. */
  5982. Plane.prototype.getClassName = function () {
  5983. return "Plane";
  5984. };
  5985. /**
  5986. * Returns the Plane hash code.
  5987. */
  5988. Plane.prototype.getHashCode = function () {
  5989. var hash = this.normal.getHashCode();
  5990. hash = (hash * 397) ^ (this.d || 0);
  5991. return hash;
  5992. };
  5993. /**
  5994. * Normalize the current Plane in place.
  5995. * Returns the updated Plane.
  5996. */
  5997. Plane.prototype.normalize = function () {
  5998. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5999. var magnitude = 0.0;
  6000. if (norm !== 0) {
  6001. magnitude = 1.0 / norm;
  6002. }
  6003. this.normal.x *= magnitude;
  6004. this.normal.y *= magnitude;
  6005. this.normal.z *= magnitude;
  6006. this.d *= magnitude;
  6007. return this;
  6008. };
  6009. /**
  6010. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6011. */
  6012. Plane.prototype.transform = function (transformation) {
  6013. var transposedMatrix = Matrix.Transpose(transformation);
  6014. var x = this.normal.x;
  6015. var y = this.normal.y;
  6016. var z = this.normal.z;
  6017. var d = this.d;
  6018. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6019. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6020. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6021. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6022. return new Plane(normalX, normalY, normalZ, finalD);
  6023. };
  6024. /**
  6025. * Returns the dot product (float) of the point coordinates and the plane normal.
  6026. */
  6027. Plane.prototype.dotCoordinate = function (point) {
  6028. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6029. };
  6030. /**
  6031. * Updates the current Plane from the plane defined by the three passed points.
  6032. * Returns the updated Plane.
  6033. */
  6034. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6035. var x1 = point2.x - point1.x;
  6036. var y1 = point2.y - point1.y;
  6037. var z1 = point2.z - point1.z;
  6038. var x2 = point3.x - point1.x;
  6039. var y2 = point3.y - point1.y;
  6040. var z2 = point3.z - point1.z;
  6041. var yz = (y1 * z2) - (z1 * y2);
  6042. var xz = (z1 * x2) - (x1 * z2);
  6043. var xy = (x1 * y2) - (y1 * x2);
  6044. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6045. var invPyth;
  6046. if (pyth !== 0) {
  6047. invPyth = 1.0 / pyth;
  6048. }
  6049. else {
  6050. invPyth = 0.0;
  6051. }
  6052. this.normal.x = yz * invPyth;
  6053. this.normal.y = xz * invPyth;
  6054. this.normal.z = xy * invPyth;
  6055. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6056. return this;
  6057. };
  6058. /**
  6059. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6060. */
  6061. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6062. var dot = Vector3.Dot(this.normal, direction);
  6063. return (dot <= epsilon);
  6064. };
  6065. /**
  6066. * Returns the signed distance (float) from the passed point to the Plane.
  6067. */
  6068. Plane.prototype.signedDistanceTo = function (point) {
  6069. return Vector3.Dot(point, this.normal) + this.d;
  6070. };
  6071. // Statics
  6072. /**
  6073. * Returns a new Plane from the passed array.
  6074. */
  6075. Plane.FromArray = function (array) {
  6076. return new Plane(array[0], array[1], array[2], array[3]);
  6077. };
  6078. /**
  6079. * Returns a new Plane defined by the three passed points.
  6080. */
  6081. Plane.FromPoints = function (point1, point2, point3) {
  6082. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6083. result.copyFromPoints(point1, point2, point3);
  6084. return result;
  6085. };
  6086. /**
  6087. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6088. * Note : the vector "normal" is updated because normalized.
  6089. */
  6090. Plane.FromPositionAndNormal = function (origin, normal) {
  6091. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6092. normal.normalize();
  6093. result.normal = normal;
  6094. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6095. return result;
  6096. };
  6097. /**
  6098. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6099. */
  6100. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6101. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6102. return Vector3.Dot(point, normal) + d;
  6103. };
  6104. return Plane;
  6105. }());
  6106. BABYLON.Plane = Plane;
  6107. var Viewport = /** @class */ (function () {
  6108. /**
  6109. * Creates a Viewport object located at (x, y) and sized (width, height).
  6110. */
  6111. function Viewport(x, y, width, height) {
  6112. this.x = x;
  6113. this.y = y;
  6114. this.width = width;
  6115. this.height = height;
  6116. }
  6117. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6118. if (renderWidthOrEngine.getRenderWidth) {
  6119. var engine = renderWidthOrEngine;
  6120. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6121. }
  6122. var renderWidth = renderWidthOrEngine;
  6123. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6124. };
  6125. /**
  6126. * Returns a new Viewport copied from the current one.
  6127. */
  6128. Viewport.prototype.clone = function () {
  6129. return new Viewport(this.x, this.y, this.width, this.height);
  6130. };
  6131. return Viewport;
  6132. }());
  6133. BABYLON.Viewport = Viewport;
  6134. var Frustum = /** @class */ (function () {
  6135. function Frustum() {
  6136. }
  6137. /**
  6138. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6139. */
  6140. Frustum.GetPlanes = function (transform) {
  6141. var frustumPlanes = [];
  6142. for (var index = 0; index < 6; index++) {
  6143. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6144. }
  6145. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6146. return frustumPlanes;
  6147. };
  6148. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6149. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6150. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6151. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6152. frustumPlane.d = transform.m[15] + transform.m[14];
  6153. frustumPlane.normalize();
  6154. };
  6155. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6156. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6157. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6158. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6159. frustumPlane.d = transform.m[15] - transform.m[14];
  6160. frustumPlane.normalize();
  6161. };
  6162. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6163. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6164. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6165. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6166. frustumPlane.d = transform.m[15] + transform.m[12];
  6167. frustumPlane.normalize();
  6168. };
  6169. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6170. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6171. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6172. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6173. frustumPlane.d = transform.m[15] - transform.m[12];
  6174. frustumPlane.normalize();
  6175. };
  6176. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6177. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6178. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6179. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6180. frustumPlane.d = transform.m[15] - transform.m[13];
  6181. frustumPlane.normalize();
  6182. };
  6183. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6184. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6185. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6186. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6187. frustumPlane.d = transform.m[15] + transform.m[13];
  6188. frustumPlane.normalize();
  6189. };
  6190. /**
  6191. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6192. */
  6193. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6194. // Near
  6195. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6196. // Far
  6197. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6198. // Left
  6199. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6200. // Right
  6201. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6202. // Top
  6203. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6204. // Bottom
  6205. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6206. };
  6207. return Frustum;
  6208. }());
  6209. BABYLON.Frustum = Frustum;
  6210. var Space;
  6211. (function (Space) {
  6212. Space[Space["LOCAL"] = 0] = "LOCAL";
  6213. Space[Space["WORLD"] = 1] = "WORLD";
  6214. Space[Space["BONE"] = 2] = "BONE";
  6215. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6216. var Axis = /** @class */ (function () {
  6217. function Axis() {
  6218. }
  6219. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6220. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6221. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6222. return Axis;
  6223. }());
  6224. BABYLON.Axis = Axis;
  6225. ;
  6226. var BezierCurve = /** @class */ (function () {
  6227. function BezierCurve() {
  6228. }
  6229. /**
  6230. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6231. */
  6232. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6233. // Extract X (which is equal to time here)
  6234. var f0 = 1 - 3 * x2 + 3 * x1;
  6235. var f1 = 3 * x2 - 6 * x1;
  6236. var f2 = 3 * x1;
  6237. var refinedT = t;
  6238. for (var i = 0; i < 5; i++) {
  6239. var refinedT2 = refinedT * refinedT;
  6240. var refinedT3 = refinedT2 * refinedT;
  6241. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6242. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6243. refinedT -= (x - t) * slope;
  6244. refinedT = Math.min(1, Math.max(0, refinedT));
  6245. }
  6246. // Resolve cubic bezier for the given x
  6247. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6248. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6249. Math.pow(refinedT, 3);
  6250. };
  6251. return BezierCurve;
  6252. }());
  6253. BABYLON.BezierCurve = BezierCurve;
  6254. var Orientation;
  6255. (function (Orientation) {
  6256. Orientation[Orientation["CW"] = 0] = "CW";
  6257. Orientation[Orientation["CCW"] = 1] = "CCW";
  6258. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6259. var Angle = /** @class */ (function () {
  6260. /**
  6261. * Creates an Angle object of "radians" radians (float).
  6262. */
  6263. function Angle(radians) {
  6264. var _this = this;
  6265. /**
  6266. * Returns the Angle value in degrees (float).
  6267. */
  6268. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6269. /**
  6270. * Returns the Angle value in radians (float).
  6271. */
  6272. this.radians = function () { return _this._radians; };
  6273. this._radians = radians;
  6274. if (this._radians < 0.0)
  6275. this._radians += (2.0 * Math.PI);
  6276. }
  6277. /**
  6278. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6279. */
  6280. Angle.BetweenTwoPoints = function (a, b) {
  6281. var delta = b.subtract(a);
  6282. var theta = Math.atan2(delta.y, delta.x);
  6283. return new Angle(theta);
  6284. };
  6285. /**
  6286. * Returns a new Angle object from the passed float in radians.
  6287. */
  6288. Angle.FromRadians = function (radians) {
  6289. return new Angle(radians);
  6290. };
  6291. /**
  6292. * Returns a new Angle object from the passed float in degrees.
  6293. */
  6294. Angle.FromDegrees = function (degrees) {
  6295. return new Angle(degrees * Math.PI / 180.0);
  6296. };
  6297. return Angle;
  6298. }());
  6299. BABYLON.Angle = Angle;
  6300. var Arc2 = /** @class */ (function () {
  6301. /**
  6302. * Creates an Arc object from the three passed points : start, middle and end.
  6303. */
  6304. function Arc2(startPoint, midPoint, endPoint) {
  6305. this.startPoint = startPoint;
  6306. this.midPoint = midPoint;
  6307. this.endPoint = endPoint;
  6308. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6309. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6310. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6311. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6312. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  6313. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6314. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6315. var a1 = this.startAngle.degrees();
  6316. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6317. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6318. // angles correction
  6319. if (a2 - a1 > +180.0)
  6320. a2 -= 360.0;
  6321. if (a2 - a1 < -180.0)
  6322. a2 += 360.0;
  6323. if (a3 - a2 > +180.0)
  6324. a3 -= 360.0;
  6325. if (a3 - a2 < -180.0)
  6326. a3 += 360.0;
  6327. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6328. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6329. }
  6330. return Arc2;
  6331. }());
  6332. BABYLON.Arc2 = Arc2;
  6333. var Path2 = /** @class */ (function () {
  6334. /**
  6335. * Creates a Path2 object from the starting 2D coordinates x and y.
  6336. */
  6337. function Path2(x, y) {
  6338. this._points = new Array();
  6339. this._length = 0.0;
  6340. this.closed = false;
  6341. this._points.push(new Vector2(x, y));
  6342. }
  6343. /**
  6344. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6345. * Returns the updated Path2.
  6346. */
  6347. Path2.prototype.addLineTo = function (x, y) {
  6348. if (this.closed) {
  6349. return this;
  6350. }
  6351. var newPoint = new Vector2(x, y);
  6352. var previousPoint = this._points[this._points.length - 1];
  6353. this._points.push(newPoint);
  6354. this._length += newPoint.subtract(previousPoint).length();
  6355. return this;
  6356. };
  6357. /**
  6358. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  6359. * Returns the updated Path2.
  6360. */
  6361. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6362. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6363. if (this.closed) {
  6364. return this;
  6365. }
  6366. var startPoint = this._points[this._points.length - 1];
  6367. var midPoint = new Vector2(midX, midY);
  6368. var endPoint = new Vector2(endX, endY);
  6369. var arc = new Arc2(startPoint, midPoint, endPoint);
  6370. var increment = arc.angle.radians() / numberOfSegments;
  6371. if (arc.orientation === Orientation.CW)
  6372. increment *= -1;
  6373. var currentAngle = arc.startAngle.radians() + increment;
  6374. for (var i = 0; i < numberOfSegments; i++) {
  6375. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6376. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6377. this.addLineTo(x, y);
  6378. currentAngle += increment;
  6379. }
  6380. return this;
  6381. };
  6382. /**
  6383. * Closes the Path2.
  6384. * Returns the Path2.
  6385. */
  6386. Path2.prototype.close = function () {
  6387. this.closed = true;
  6388. return this;
  6389. };
  6390. /**
  6391. * Returns the Path2 total length (float).
  6392. */
  6393. Path2.prototype.length = function () {
  6394. var result = this._length;
  6395. if (!this.closed) {
  6396. var lastPoint = this._points[this._points.length - 1];
  6397. var firstPoint = this._points[0];
  6398. result += (firstPoint.subtract(lastPoint).length());
  6399. }
  6400. return result;
  6401. };
  6402. /**
  6403. * Returns the Path2 internal array of points.
  6404. */
  6405. Path2.prototype.getPoints = function () {
  6406. return this._points;
  6407. };
  6408. /**
  6409. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6410. */
  6411. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6412. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6413. return Vector2.Zero();
  6414. }
  6415. var lengthPosition = normalizedLengthPosition * this.length();
  6416. var previousOffset = 0;
  6417. for (var i = 0; i < this._points.length; i++) {
  6418. var j = (i + 1) % this._points.length;
  6419. var a = this._points[i];
  6420. var b = this._points[j];
  6421. var bToA = b.subtract(a);
  6422. var nextOffset = (bToA.length() + previousOffset);
  6423. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6424. var dir = bToA.normalize();
  6425. var localOffset = lengthPosition - previousOffset;
  6426. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6427. }
  6428. previousOffset = nextOffset;
  6429. }
  6430. return Vector2.Zero();
  6431. };
  6432. /**
  6433. * Returns a new Path2 starting at the coordinates (x, y).
  6434. */
  6435. Path2.StartingAt = function (x, y) {
  6436. return new Path2(x, y);
  6437. };
  6438. return Path2;
  6439. }());
  6440. BABYLON.Path2 = Path2;
  6441. var Path3D = /** @class */ (function () {
  6442. /**
  6443. * new Path3D(path, normal, raw)
  6444. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6445. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6446. * path : an array of Vector3, the curve axis of the Path3D
  6447. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6448. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6449. */
  6450. function Path3D(path, firstNormal, raw) {
  6451. if (firstNormal === void 0) { firstNormal = null; }
  6452. this.path = path;
  6453. this._curve = new Array();
  6454. this._distances = new Array();
  6455. this._tangents = new Array();
  6456. this._normals = new Array();
  6457. this._binormals = new Array();
  6458. for (var p = 0; p < path.length; p++) {
  6459. this._curve[p] = path[p].clone(); // hard copy
  6460. }
  6461. this._raw = raw || false;
  6462. this._compute(firstNormal);
  6463. }
  6464. /**
  6465. * Returns the Path3D array of successive Vector3 designing its curve.
  6466. */
  6467. Path3D.prototype.getCurve = function () {
  6468. return this._curve;
  6469. };
  6470. /**
  6471. * Returns an array populated with tangent vectors on each Path3D curve point.
  6472. */
  6473. Path3D.prototype.getTangents = function () {
  6474. return this._tangents;
  6475. };
  6476. /**
  6477. * Returns an array populated with normal vectors on each Path3D curve point.
  6478. */
  6479. Path3D.prototype.getNormals = function () {
  6480. return this._normals;
  6481. };
  6482. /**
  6483. * Returns an array populated with binormal vectors on each Path3D curve point.
  6484. */
  6485. Path3D.prototype.getBinormals = function () {
  6486. return this._binormals;
  6487. };
  6488. /**
  6489. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6490. */
  6491. Path3D.prototype.getDistances = function () {
  6492. return this._distances;
  6493. };
  6494. /**
  6495. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6496. * Returns the same object updated.
  6497. */
  6498. Path3D.prototype.update = function (path, firstNormal) {
  6499. if (firstNormal === void 0) { firstNormal = null; }
  6500. for (var p = 0; p < path.length; p++) {
  6501. this._curve[p].x = path[p].x;
  6502. this._curve[p].y = path[p].y;
  6503. this._curve[p].z = path[p].z;
  6504. }
  6505. this._compute(firstNormal);
  6506. return this;
  6507. };
  6508. // private function compute() : computes tangents, normals and binormals
  6509. Path3D.prototype._compute = function (firstNormal) {
  6510. var l = this._curve.length;
  6511. // first and last tangents
  6512. this._tangents[0] = this._getFirstNonNullVector(0);
  6513. if (!this._raw) {
  6514. this._tangents[0].normalize();
  6515. }
  6516. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6517. if (!this._raw) {
  6518. this._tangents[l - 1].normalize();
  6519. }
  6520. // normals and binormals at first point : arbitrary vector with _normalVector()
  6521. var tg0 = this._tangents[0];
  6522. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6523. this._normals[0] = pp0;
  6524. if (!this._raw) {
  6525. this._normals[0].normalize();
  6526. }
  6527. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6528. if (!this._raw) {
  6529. this._binormals[0].normalize();
  6530. }
  6531. this._distances[0] = 0.0;
  6532. // normals and binormals : next points
  6533. var prev; // previous vector (segment)
  6534. var cur; // current vector (segment)
  6535. var curTang; // current tangent
  6536. // previous normal
  6537. var prevBinor; // previous binormal
  6538. for (var i = 1; i < l; i++) {
  6539. // tangents
  6540. prev = this._getLastNonNullVector(i);
  6541. if (i < l - 1) {
  6542. cur = this._getFirstNonNullVector(i);
  6543. this._tangents[i] = prev.add(cur);
  6544. this._tangents[i].normalize();
  6545. }
  6546. this._distances[i] = this._distances[i - 1] + prev.length();
  6547. // normals and binormals
  6548. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6549. curTang = this._tangents[i];
  6550. prevBinor = this._binormals[i - 1];
  6551. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6552. if (!this._raw) {
  6553. this._normals[i].normalize();
  6554. }
  6555. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6556. if (!this._raw) {
  6557. this._binormals[i].normalize();
  6558. }
  6559. }
  6560. };
  6561. // private function getFirstNonNullVector(index)
  6562. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6563. Path3D.prototype._getFirstNonNullVector = function (index) {
  6564. var i = 1;
  6565. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6566. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6567. i++;
  6568. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6569. }
  6570. return nNVector;
  6571. };
  6572. // private function getLastNonNullVector(index)
  6573. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6574. Path3D.prototype._getLastNonNullVector = function (index) {
  6575. var i = 1;
  6576. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6577. while (nLVector.length() === 0 && index > i + 1) {
  6578. i++;
  6579. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6580. }
  6581. return nLVector;
  6582. };
  6583. // private function normalVector(v0, vt, va) :
  6584. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6585. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6586. Path3D.prototype._normalVector = function (v0, vt, va) {
  6587. var normal0;
  6588. var tgl = vt.length();
  6589. if (tgl === 0.0) {
  6590. tgl = 1.0;
  6591. }
  6592. if (va === undefined || va === null) {
  6593. var point;
  6594. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6595. point = new Vector3(0.0, -1.0, 0.0);
  6596. }
  6597. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6598. point = new Vector3(1.0, 0.0, 0.0);
  6599. }
  6600. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6601. point = new Vector3(0.0, 0.0, 1.0);
  6602. }
  6603. else {
  6604. point = Vector3.Zero();
  6605. }
  6606. normal0 = Vector3.Cross(vt, point);
  6607. }
  6608. else {
  6609. normal0 = Vector3.Cross(vt, va);
  6610. Vector3.CrossToRef(normal0, vt, normal0);
  6611. }
  6612. normal0.normalize();
  6613. return normal0;
  6614. };
  6615. return Path3D;
  6616. }());
  6617. BABYLON.Path3D = Path3D;
  6618. var Curve3 = /** @class */ (function () {
  6619. /**
  6620. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6621. * A Curve3 is designed from a series of successive Vector3.
  6622. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6623. */
  6624. function Curve3(points) {
  6625. this._length = 0.0;
  6626. this._points = points;
  6627. this._length = this._computeLength(points);
  6628. }
  6629. /**
  6630. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6631. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6632. * @param v1 (Vector3) the control point
  6633. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6634. * @param nbPoints (integer) the wanted number of points in the curve
  6635. */
  6636. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6637. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6638. var bez = new Array();
  6639. var equation = function (t, val0, val1, val2) {
  6640. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6641. return res;
  6642. };
  6643. for (var i = 0; i <= nbPoints; i++) {
  6644. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  6645. }
  6646. return new Curve3(bez);
  6647. };
  6648. /**
  6649. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6650. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6651. * @param v1 (Vector3) the first control point
  6652. * @param v2 (Vector3) the second control point
  6653. * @param v3 (Vector3) the end point of the Cubic Bezier
  6654. * @param nbPoints (integer) the wanted number of points in the curve
  6655. */
  6656. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6657. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6658. var bez = new Array();
  6659. var equation = function (t, val0, val1, val2, val3) {
  6660. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  6661. return res;
  6662. };
  6663. for (var i = 0; i <= nbPoints; i++) {
  6664. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  6665. }
  6666. return new Curve3(bez);
  6667. };
  6668. /**
  6669. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6670. * @param p1 (Vector3) the origin point of the Hermite Spline
  6671. * @param t1 (Vector3) the tangent vector at the origin point
  6672. * @param p2 (Vector3) the end point of the Hermite Spline
  6673. * @param t2 (Vector3) the tangent vector at the end point
  6674. * @param nbPoints (integer) the wanted number of points in the curve
  6675. */
  6676. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6677. var hermite = new Array();
  6678. var step = 1.0 / nbPoints;
  6679. for (var i = 0; i <= nbPoints; i++) {
  6680. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6681. }
  6682. return new Curve3(hermite);
  6683. };
  6684. /**
  6685. * Returns a Curve3 object along a CatmullRom Spline curve :
  6686. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6687. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6688. */
  6689. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6690. var totalPoints = new Array();
  6691. totalPoints.push(points[0].clone());
  6692. Array.prototype.push.apply(totalPoints, points);
  6693. totalPoints.push(points[points.length - 1].clone());
  6694. var catmullRom = new Array();
  6695. var step = 1.0 / nbPoints;
  6696. var amount = 0.0;
  6697. for (var i = 0; i < totalPoints.length - 3; i++) {
  6698. amount = 0;
  6699. for (var c = 0; c < nbPoints; c++) {
  6700. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6701. amount += step;
  6702. }
  6703. }
  6704. i--;
  6705. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6706. return new Curve3(catmullRom);
  6707. };
  6708. /**
  6709. * Returns the Curve3 stored array of successive Vector3
  6710. */
  6711. Curve3.prototype.getPoints = function () {
  6712. return this._points;
  6713. };
  6714. /**
  6715. * Returns the computed length (float) of the curve.
  6716. */
  6717. Curve3.prototype.length = function () {
  6718. return this._length;
  6719. };
  6720. /**
  6721. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6722. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6723. * curveA and curveB keep unchanged.
  6724. */
  6725. Curve3.prototype.continue = function (curve) {
  6726. var lastPoint = this._points[this._points.length - 1];
  6727. var continuedPoints = this._points.slice();
  6728. var curvePoints = curve.getPoints();
  6729. for (var i = 1; i < curvePoints.length; i++) {
  6730. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6731. }
  6732. var continuedCurve = new Curve3(continuedPoints);
  6733. return continuedCurve;
  6734. };
  6735. Curve3.prototype._computeLength = function (path) {
  6736. var l = 0;
  6737. for (var i = 1; i < path.length; i++) {
  6738. l += (path[i].subtract(path[i - 1])).length();
  6739. }
  6740. return l;
  6741. };
  6742. return Curve3;
  6743. }());
  6744. BABYLON.Curve3 = Curve3;
  6745. // Vertex formats
  6746. var PositionNormalVertex = /** @class */ (function () {
  6747. function PositionNormalVertex(position, normal) {
  6748. if (position === void 0) { position = Vector3.Zero(); }
  6749. if (normal === void 0) { normal = Vector3.Up(); }
  6750. this.position = position;
  6751. this.normal = normal;
  6752. }
  6753. PositionNormalVertex.prototype.clone = function () {
  6754. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6755. };
  6756. return PositionNormalVertex;
  6757. }());
  6758. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6759. var PositionNormalTextureVertex = /** @class */ (function () {
  6760. function PositionNormalTextureVertex(position, normal, uv) {
  6761. if (position === void 0) { position = Vector3.Zero(); }
  6762. if (normal === void 0) { normal = Vector3.Up(); }
  6763. if (uv === void 0) { uv = Vector2.Zero(); }
  6764. this.position = position;
  6765. this.normal = normal;
  6766. this.uv = uv;
  6767. }
  6768. PositionNormalTextureVertex.prototype.clone = function () {
  6769. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6770. };
  6771. return PositionNormalTextureVertex;
  6772. }());
  6773. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6774. // Temporary pre-allocated objects for engine internal use
  6775. // usage in any internal function :
  6776. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6777. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6778. var Tmp = /** @class */ (function () {
  6779. function Tmp() {
  6780. }
  6781. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6782. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6783. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6784. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6785. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6786. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6787. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6788. Matrix.Zero(), Matrix.Zero(),
  6789. Matrix.Zero(), Matrix.Zero(),
  6790. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6791. return Tmp;
  6792. }());
  6793. BABYLON.Tmp = Tmp;
  6794. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6795. var MathTmp = /** @class */ (function () {
  6796. function MathTmp() {
  6797. }
  6798. MathTmp.Vector3 = [Vector3.Zero()];
  6799. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6800. MathTmp.Quaternion = [Quaternion.Zero()];
  6801. return MathTmp;
  6802. }());
  6803. })(BABYLON || (BABYLON = {}));
  6804. //# sourceMappingURL=babylon.math.js.map
  6805. "use strict";
  6806. var BABYLON;
  6807. (function (BABYLON) {
  6808. var Scalar = /** @class */ (function () {
  6809. function Scalar() {
  6810. }
  6811. /**
  6812. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6813. */
  6814. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6815. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6816. var num = a - b;
  6817. return -epsilon <= num && num <= epsilon;
  6818. };
  6819. /**
  6820. * Returns a string : the upper case translation of the number i to hexadecimal.
  6821. */
  6822. Scalar.ToHex = function (i) {
  6823. var str = i.toString(16);
  6824. if (i <= 15) {
  6825. return ("0" + str).toUpperCase();
  6826. }
  6827. return str.toUpperCase();
  6828. };
  6829. /**
  6830. * Returns -1 if value is negative and +1 is value is positive.
  6831. * Returns the value itself if it's equal to zero.
  6832. */
  6833. Scalar.Sign = function (value) {
  6834. value = +value; // convert to a number
  6835. if (value === 0 || isNaN(value))
  6836. return value;
  6837. return value > 0 ? 1 : -1;
  6838. };
  6839. /**
  6840. * Returns the value itself if it's between min and max.
  6841. * Returns min if the value is lower than min.
  6842. * Returns max if the value is greater than max.
  6843. */
  6844. Scalar.Clamp = function (value, min, max) {
  6845. if (min === void 0) { min = 0; }
  6846. if (max === void 0) { max = 1; }
  6847. return Math.min(max, Math.max(min, value));
  6848. };
  6849. /**
  6850. * Returns the log2 of value.
  6851. */
  6852. Scalar.Log2 = function (value) {
  6853. return Math.log(value) * Math.LOG2E;
  6854. };
  6855. /**
  6856. * Loops the value, so that it is never larger than length and never smaller than 0.
  6857. *
  6858. * This is similar to the modulo operator but it works with floating point numbers.
  6859. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6860. * With t = 5 and length = 2.5, the result would be 0.0.
  6861. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6862. */
  6863. Scalar.Repeat = function (value, length) {
  6864. return value - Math.floor(value / length) * length;
  6865. };
  6866. /**
  6867. * Normalize the value between 0.0 and 1.0 using min and max values
  6868. */
  6869. Scalar.Normalize = function (value, min, max) {
  6870. return (value - min) / (max - min);
  6871. };
  6872. /**
  6873. * Denormalize the value from 0.0 and 1.0 using min and max values
  6874. */
  6875. Scalar.Denormalize = function (normalized, min, max) {
  6876. return (normalized * (max - min) + min);
  6877. };
  6878. /**
  6879. * Calculates the shortest difference between two given angles given in degrees.
  6880. */
  6881. Scalar.DeltaAngle = function (current, target) {
  6882. var num = Scalar.Repeat(target - current, 360.0);
  6883. if (num > 180.0) {
  6884. num -= 360.0;
  6885. }
  6886. return num;
  6887. };
  6888. /**
  6889. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6890. *
  6891. * The returned value will move back and forth between 0 and length
  6892. */
  6893. Scalar.PingPong = function (tx, length) {
  6894. var t = Scalar.Repeat(tx, length * 2.0);
  6895. return length - Math.abs(t - length);
  6896. };
  6897. /**
  6898. * Interpolates between min and max with smoothing at the limits.
  6899. *
  6900. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6901. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6902. */
  6903. Scalar.SmoothStep = function (from, to, tx) {
  6904. var t = Scalar.Clamp(tx);
  6905. t = -2.0 * t * t * t + 3.0 * t * t;
  6906. return to * t + from * (1.0 - t);
  6907. };
  6908. /**
  6909. * Moves a value current towards target.
  6910. *
  6911. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6912. * Negative values of maxDelta pushes the value away from target.
  6913. */
  6914. Scalar.MoveTowards = function (current, target, maxDelta) {
  6915. var result = 0;
  6916. if (Math.abs(target - current) <= maxDelta) {
  6917. result = target;
  6918. }
  6919. else {
  6920. result = current + Scalar.Sign(target - current) * maxDelta;
  6921. }
  6922. return result;
  6923. };
  6924. /**
  6925. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6926. *
  6927. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6928. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6929. */
  6930. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6931. var num = Scalar.DeltaAngle(current, target);
  6932. var result = 0;
  6933. if (-maxDelta < num && num < maxDelta) {
  6934. result = target;
  6935. }
  6936. else {
  6937. target = current + num;
  6938. result = Scalar.MoveTowards(current, target, maxDelta);
  6939. }
  6940. return result;
  6941. };
  6942. /**
  6943. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6944. */
  6945. Scalar.Lerp = function (start, end, amount) {
  6946. return start + ((end - start) * amount);
  6947. };
  6948. /**
  6949. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6950. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6951. */
  6952. Scalar.LerpAngle = function (start, end, amount) {
  6953. var num = Scalar.Repeat(end - start, 360.0);
  6954. if (num > 180.0) {
  6955. num -= 360.0;
  6956. }
  6957. return start + num * Scalar.Clamp(amount);
  6958. };
  6959. /**
  6960. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6961. */
  6962. Scalar.InverseLerp = function (a, b, value) {
  6963. var result = 0;
  6964. if (a != b) {
  6965. result = Scalar.Clamp((value - a) / (b - a));
  6966. }
  6967. else {
  6968. result = 0.0;
  6969. }
  6970. return result;
  6971. };
  6972. /**
  6973. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6974. */
  6975. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6976. var squared = amount * amount;
  6977. var cubed = amount * squared;
  6978. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6979. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6980. var part3 = (cubed - (2.0 * squared)) + amount;
  6981. var part4 = cubed - squared;
  6982. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6983. };
  6984. /**
  6985. * Returns a random float number between and min and max values
  6986. */
  6987. Scalar.RandomRange = function (min, max) {
  6988. if (min === max)
  6989. return min;
  6990. return ((Math.random() * (max - min)) + min);
  6991. };
  6992. /**
  6993. * This function returns percentage of a number in a given range.
  6994. *
  6995. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6996. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6997. */
  6998. Scalar.RangeToPercent = function (number, min, max) {
  6999. return ((number - min) / (max - min));
  7000. };
  7001. /**
  7002. * This function returns number that corresponds to the percentage in a given range.
  7003. *
  7004. * PercentToRange(0.34,0,100) will return 34.
  7005. */
  7006. Scalar.PercentToRange = function (percent, min, max) {
  7007. return ((max - min) * percent + min);
  7008. };
  7009. /**
  7010. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7011. * @param angle The angle to normalize in radian.
  7012. * @return The converted angle.
  7013. */
  7014. Scalar.NormalizeRadians = function (angle) {
  7015. // More precise but slower version kept for reference.
  7016. // angle = angle % Tools.TwoPi;
  7017. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7018. //if (angle > Math.PI) {
  7019. // angle -= Tools.TwoPi;
  7020. //}
  7021. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7022. return angle;
  7023. };
  7024. /**
  7025. * Two pi constants convenient for computation.
  7026. */
  7027. Scalar.TwoPi = Math.PI * 2;
  7028. return Scalar;
  7029. }());
  7030. BABYLON.Scalar = Scalar;
  7031. })(BABYLON || (BABYLON = {}));
  7032. //# sourceMappingURL=babylon.math.scalar.js.map
  7033. "use strict";
  7034. //# sourceMappingURL=babylon.mixins.js.map
  7035. "use strict";
  7036. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7037. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7038. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7039. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7040. //# sourceMappingURL=babylon.webgl2.js.map
  7041. "use strict";
  7042. var BABYLON;
  7043. (function (BABYLON) {
  7044. var __decoratorInitialStore = {};
  7045. var __mergedStore = {};
  7046. var _copySource = function (creationFunction, source, instanciate) {
  7047. var destination = creationFunction();
  7048. // Tags
  7049. if (BABYLON.Tags) {
  7050. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7051. }
  7052. var classStore = getMergedStore(destination);
  7053. // Properties
  7054. for (var property in classStore) {
  7055. var propertyDescriptor = classStore[property];
  7056. var sourceProperty = source[property];
  7057. var propertyType = propertyDescriptor.type;
  7058. if (sourceProperty !== undefined && sourceProperty !== null) {
  7059. switch (propertyType) {
  7060. case 0: // Value
  7061. case 6:// Mesh reference
  7062. destination[property] = sourceProperty;
  7063. break;
  7064. case 1:// Texture
  7065. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7066. break;
  7067. case 2: // Color3
  7068. case 3: // FresnelParameters
  7069. case 4: // Vector2
  7070. case 5: // Vector3
  7071. case 7: // Color Curves
  7072. case 10:// Quaternion
  7073. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7074. break;
  7075. }
  7076. }
  7077. }
  7078. return destination;
  7079. };
  7080. function getDirectStore(target) {
  7081. var classKey = target.getClassName();
  7082. if (!__decoratorInitialStore[classKey]) {
  7083. __decoratorInitialStore[classKey] = {};
  7084. }
  7085. return __decoratorInitialStore[classKey];
  7086. }
  7087. /**
  7088. * Return the list of properties flagged as serializable
  7089. * @param target: host object
  7090. */
  7091. function getMergedStore(target) {
  7092. var classKey = target.getClassName();
  7093. if (__mergedStore[classKey]) {
  7094. return __mergedStore[classKey];
  7095. }
  7096. __mergedStore[classKey] = {};
  7097. var store = __mergedStore[classKey];
  7098. var currentTarget = target;
  7099. var currentKey = classKey;
  7100. while (currentKey) {
  7101. var initialStore = __decoratorInitialStore[currentKey];
  7102. for (var property in initialStore) {
  7103. store[property] = initialStore[property];
  7104. }
  7105. var parent_1 = void 0;
  7106. var done = false;
  7107. do {
  7108. parent_1 = Object.getPrototypeOf(currentTarget);
  7109. if (!parent_1.getClassName) {
  7110. done = true;
  7111. break;
  7112. }
  7113. if (parent_1.getClassName() !== currentKey) {
  7114. break;
  7115. }
  7116. currentTarget = parent_1;
  7117. } while (parent_1);
  7118. if (done) {
  7119. break;
  7120. }
  7121. currentKey = parent_1.getClassName();
  7122. currentTarget = parent_1;
  7123. }
  7124. return store;
  7125. }
  7126. function generateSerializableMember(type, sourceName) {
  7127. return function (target, propertyKey) {
  7128. var classStore = getDirectStore(target);
  7129. if (!classStore[propertyKey]) {
  7130. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7131. }
  7132. };
  7133. }
  7134. function generateExpandMember(setCallback, targetKey) {
  7135. if (targetKey === void 0) { targetKey = null; }
  7136. return function (target, propertyKey) {
  7137. var key = targetKey || ("_" + propertyKey);
  7138. Object.defineProperty(target, propertyKey, {
  7139. get: function () {
  7140. return this[key];
  7141. },
  7142. set: function (value) {
  7143. if (this[key] === value) {
  7144. return;
  7145. }
  7146. this[key] = value;
  7147. target[setCallback].apply(this);
  7148. },
  7149. enumerable: true,
  7150. configurable: true
  7151. });
  7152. };
  7153. }
  7154. function expandToProperty(callback, targetKey) {
  7155. if (targetKey === void 0) { targetKey = null; }
  7156. return generateExpandMember(callback, targetKey);
  7157. }
  7158. BABYLON.expandToProperty = expandToProperty;
  7159. function serialize(sourceName) {
  7160. return generateSerializableMember(0, sourceName); // value member
  7161. }
  7162. BABYLON.serialize = serialize;
  7163. function serializeAsTexture(sourceName) {
  7164. return generateSerializableMember(1, sourceName); // texture member
  7165. }
  7166. BABYLON.serializeAsTexture = serializeAsTexture;
  7167. function serializeAsColor3(sourceName) {
  7168. return generateSerializableMember(2, sourceName); // color3 member
  7169. }
  7170. BABYLON.serializeAsColor3 = serializeAsColor3;
  7171. function serializeAsFresnelParameters(sourceName) {
  7172. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7173. }
  7174. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7175. function serializeAsVector2(sourceName) {
  7176. return generateSerializableMember(4, sourceName); // vector2 member
  7177. }
  7178. BABYLON.serializeAsVector2 = serializeAsVector2;
  7179. function serializeAsVector3(sourceName) {
  7180. return generateSerializableMember(5, sourceName); // vector3 member
  7181. }
  7182. BABYLON.serializeAsVector3 = serializeAsVector3;
  7183. function serializeAsMeshReference(sourceName) {
  7184. return generateSerializableMember(6, sourceName); // mesh reference member
  7185. }
  7186. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7187. function serializeAsColorCurves(sourceName) {
  7188. return generateSerializableMember(7, sourceName); // color curves
  7189. }
  7190. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7191. function serializeAsColor4(sourceName) {
  7192. return generateSerializableMember(8, sourceName); // color 4
  7193. }
  7194. BABYLON.serializeAsColor4 = serializeAsColor4;
  7195. function serializeAsImageProcessingConfiguration(sourceName) {
  7196. return generateSerializableMember(9, sourceName); // image processing
  7197. }
  7198. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7199. function serializeAsQuaternion(sourceName) {
  7200. return generateSerializableMember(10, sourceName); // quaternion member
  7201. }
  7202. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7203. var SerializationHelper = /** @class */ (function () {
  7204. function SerializationHelper() {
  7205. }
  7206. SerializationHelper.Serialize = function (entity, serializationObject) {
  7207. if (!serializationObject) {
  7208. serializationObject = {};
  7209. }
  7210. // Tags
  7211. if (BABYLON.Tags) {
  7212. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7213. }
  7214. var serializedProperties = getMergedStore(entity);
  7215. // Properties
  7216. for (var property in serializedProperties) {
  7217. var propertyDescriptor = serializedProperties[property];
  7218. var targetPropertyName = propertyDescriptor.sourceName || property;
  7219. var propertyType = propertyDescriptor.type;
  7220. var sourceProperty = entity[property];
  7221. if (sourceProperty !== undefined && sourceProperty !== null) {
  7222. switch (propertyType) {
  7223. case 0:// Value
  7224. serializationObject[targetPropertyName] = sourceProperty;
  7225. break;
  7226. case 1:// Texture
  7227. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7228. break;
  7229. case 2:// Color3
  7230. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7231. break;
  7232. case 3:// FresnelParameters
  7233. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7234. break;
  7235. case 4:// Vector2
  7236. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7237. break;
  7238. case 5:// Vector3
  7239. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7240. break;
  7241. case 6:// Mesh reference
  7242. serializationObject[targetPropertyName] = sourceProperty.id;
  7243. break;
  7244. case 7:// Color Curves
  7245. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7246. break;
  7247. case 8:// Color 4
  7248. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7249. break;
  7250. case 9:// Image Processing
  7251. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7252. break;
  7253. }
  7254. }
  7255. }
  7256. return serializationObject;
  7257. };
  7258. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7259. if (rootUrl === void 0) { rootUrl = null; }
  7260. var destination = creationFunction();
  7261. if (!rootUrl) {
  7262. rootUrl = "";
  7263. }
  7264. // Tags
  7265. if (BABYLON.Tags) {
  7266. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7267. }
  7268. var classStore = getMergedStore(destination);
  7269. // Properties
  7270. for (var property in classStore) {
  7271. var propertyDescriptor = classStore[property];
  7272. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7273. var propertyType = propertyDescriptor.type;
  7274. if (sourceProperty !== undefined && sourceProperty !== null) {
  7275. var dest = destination;
  7276. switch (propertyType) {
  7277. case 0:// Value
  7278. dest[property] = sourceProperty;
  7279. break;
  7280. case 1:// Texture
  7281. if (scene) {
  7282. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7283. }
  7284. break;
  7285. case 2:// Color3
  7286. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7287. break;
  7288. case 3:// FresnelParameters
  7289. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7290. break;
  7291. case 4:// Vector2
  7292. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7293. break;
  7294. case 5:// Vector3
  7295. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7296. break;
  7297. case 6:// Mesh reference
  7298. if (scene) {
  7299. dest[property] = scene.getLastMeshByID(sourceProperty);
  7300. }
  7301. break;
  7302. case 7:// Color Curves
  7303. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7304. break;
  7305. case 8:// Color 4
  7306. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7307. break;
  7308. case 9:// Image Processing
  7309. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7310. break;
  7311. }
  7312. }
  7313. }
  7314. return destination;
  7315. };
  7316. SerializationHelper.Clone = function (creationFunction, source) {
  7317. return _copySource(creationFunction, source, false);
  7318. };
  7319. SerializationHelper.Instanciate = function (creationFunction, source) {
  7320. return _copySource(creationFunction, source, true);
  7321. };
  7322. return SerializationHelper;
  7323. }());
  7324. BABYLON.SerializationHelper = SerializationHelper;
  7325. })(BABYLON || (BABYLON = {}));
  7326. //# sourceMappingURL=babylon.decorators.js.map
  7327. "use strict";
  7328. var BABYLON;
  7329. (function (BABYLON) {
  7330. /**
  7331. * Wrapper class for promise with external resolve and reject.
  7332. */
  7333. var Deferred = /** @class */ (function () {
  7334. /**
  7335. * Constructor for this deferred object.
  7336. */
  7337. function Deferred() {
  7338. var _this = this;
  7339. this.promise = new Promise(function (resolve, reject) {
  7340. _this._resolve = resolve;
  7341. _this._reject = reject;
  7342. });
  7343. }
  7344. Object.defineProperty(Deferred.prototype, "resolve", {
  7345. /**
  7346. * The resolve method of the promise associated with this deferred object.
  7347. */
  7348. get: function () {
  7349. return this._resolve;
  7350. },
  7351. enumerable: true,
  7352. configurable: true
  7353. });
  7354. Object.defineProperty(Deferred.prototype, "reject", {
  7355. /**
  7356. * The reject method of the promise associated with this deferred object.
  7357. */
  7358. get: function () {
  7359. return this._reject;
  7360. },
  7361. enumerable: true,
  7362. configurable: true
  7363. });
  7364. return Deferred;
  7365. }());
  7366. BABYLON.Deferred = Deferred;
  7367. })(BABYLON || (BABYLON = {}));
  7368. //# sourceMappingURL=babylon.deferred.js.map
  7369. "use strict";
  7370. var BABYLON;
  7371. (function (BABYLON) {
  7372. /**
  7373. * A class serves as a medium between the observable and its observers
  7374. */
  7375. var EventState = /** @class */ (function () {
  7376. /**
  7377. * Create a new EventState
  7378. * @param mask defines the mask associated with this state
  7379. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7380. * @param target defines the original target of the state
  7381. * @param currentTarget defines the current target of the state
  7382. */
  7383. function EventState(mask, skipNextObservers, target, currentTarget) {
  7384. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7385. this.initalize(mask, skipNextObservers, target, currentTarget);
  7386. }
  7387. /**
  7388. * Initialize the current event state
  7389. * @param mask defines the mask associated with this state
  7390. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7391. * @param target defines the original target of the state
  7392. * @param currentTarget defines the current target of the state
  7393. * @returns the current event state
  7394. */
  7395. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7396. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7397. this.mask = mask;
  7398. this.skipNextObservers = skipNextObservers;
  7399. this.target = target;
  7400. this.currentTarget = currentTarget;
  7401. return this;
  7402. };
  7403. return EventState;
  7404. }());
  7405. BABYLON.EventState = EventState;
  7406. /**
  7407. * Represent an Observer registered to a given Observable object.
  7408. */
  7409. var Observer = /** @class */ (function () {
  7410. /**
  7411. * Creates a new observer
  7412. * @param callback defines the callback to call when the observer is notified
  7413. * @param mask defines the mask of the observer (used to filter notifications)
  7414. * @param scope defines the current scope used to restore the JS context
  7415. */
  7416. function Observer(
  7417. /**
  7418. * Defines the callback to call when the observer is notified
  7419. */
  7420. callback,
  7421. /**
  7422. * Defines the mask of the observer (used to filter notifications)
  7423. */
  7424. mask,
  7425. /**
  7426. * Defines the current scope used to restore the JS context
  7427. */
  7428. scope) {
  7429. if (scope === void 0) { scope = null; }
  7430. this.callback = callback;
  7431. this.mask = mask;
  7432. this.scope = scope;
  7433. /** @ignore */
  7434. this._willBeUnregistered = false;
  7435. /**
  7436. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7437. */
  7438. this.unregisterOnNextCall = false;
  7439. }
  7440. return Observer;
  7441. }());
  7442. BABYLON.Observer = Observer;
  7443. /**
  7444. * Represent a list of observers registered to multiple Observables object.
  7445. */
  7446. var MultiObserver = /** @class */ (function () {
  7447. function MultiObserver() {
  7448. }
  7449. /**
  7450. * Release associated resources
  7451. */
  7452. MultiObserver.prototype.dispose = function () {
  7453. if (this._observers && this._observables) {
  7454. for (var index = 0; index < this._observers.length; index++) {
  7455. this._observables[index].remove(this._observers[index]);
  7456. }
  7457. }
  7458. this._observers = null;
  7459. this._observables = null;
  7460. };
  7461. /**
  7462. * Raise a callback when one of the observable will notify
  7463. * @param observables defines a list of observables to watch
  7464. * @param callback defines the callback to call on notification
  7465. * @param mask defines the mask used to filter notifications
  7466. * @param scope defines the current scope used to restore the JS context
  7467. * @returns the new MultiObserver
  7468. */
  7469. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7470. if (mask === void 0) { mask = -1; }
  7471. if (scope === void 0) { scope = null; }
  7472. var result = new MultiObserver();
  7473. result._observers = new Array();
  7474. result._observables = observables;
  7475. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7476. var observable = observables_1[_i];
  7477. var observer = observable.add(callback, mask, false, scope);
  7478. if (observer) {
  7479. result._observers.push(observer);
  7480. }
  7481. }
  7482. return result;
  7483. };
  7484. return MultiObserver;
  7485. }());
  7486. BABYLON.MultiObserver = MultiObserver;
  7487. /**
  7488. * The Observable class is a simple implementation of the Observable pattern.
  7489. * 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.
  7490. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7491. * 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).
  7492. * 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.
  7493. */
  7494. var Observable = /** @class */ (function () {
  7495. /**
  7496. * Creates a new observable
  7497. * @param onObserverAdded defines a callback to call when a new observer is added
  7498. */
  7499. function Observable(onObserverAdded) {
  7500. this._observers = new Array();
  7501. this._eventState = new EventState(0);
  7502. if (onObserverAdded) {
  7503. this._onObserverAdded = onObserverAdded;
  7504. }
  7505. }
  7506. /**
  7507. * Create a new Observer with the specified callback
  7508. * @param callback the callback that will be executed for that Observer
  7509. * @param mask the mask used to filter observers
  7510. * @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.
  7511. * @param scope optional scope for the callback to be called from
  7512. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7513. * @returns the new observer created for the callback
  7514. */
  7515. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7516. if (mask === void 0) { mask = -1; }
  7517. if (insertFirst === void 0) { insertFirst = false; }
  7518. if (scope === void 0) { scope = null; }
  7519. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7520. if (!callback) {
  7521. return null;
  7522. }
  7523. var observer = new Observer(callback, mask, scope);
  7524. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7525. if (insertFirst) {
  7526. this._observers.unshift(observer);
  7527. }
  7528. else {
  7529. this._observers.push(observer);
  7530. }
  7531. if (this._onObserverAdded) {
  7532. this._onObserverAdded(observer);
  7533. }
  7534. return observer;
  7535. };
  7536. /**
  7537. * Remove an Observer from the Observable object
  7538. * @param observer the instance of the Observer to remove
  7539. * @returns false if it doesn't belong to this Observable
  7540. */
  7541. Observable.prototype.remove = function (observer) {
  7542. if (!observer) {
  7543. return false;
  7544. }
  7545. var index = this._observers.indexOf(observer);
  7546. if (index !== -1) {
  7547. this._observers.splice(index, 1);
  7548. return true;
  7549. }
  7550. return false;
  7551. };
  7552. /**
  7553. * Remove a callback from the Observable object
  7554. * @param callback the callback to remove
  7555. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7556. * @returns false if it doesn't belong to this Observable
  7557. */
  7558. Observable.prototype.removeCallback = function (callback, scope) {
  7559. for (var index = 0; index < this._observers.length; index++) {
  7560. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7561. this._observers.splice(index, 1);
  7562. return true;
  7563. }
  7564. }
  7565. return false;
  7566. };
  7567. Observable.prototype._deferUnregister = function (observer) {
  7568. var _this = this;
  7569. observer.unregisterOnNextCall = false;
  7570. observer._willBeUnregistered = true;
  7571. BABYLON.Tools.SetImmediate(function () {
  7572. _this.remove(observer);
  7573. });
  7574. };
  7575. /**
  7576. * Notify all Observers by calling their respective callback with the given data
  7577. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7578. * @param eventData defines the data to send to all observers
  7579. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7580. * @param target defines the original target of the state
  7581. * @param currentTarget defines the current target of the state
  7582. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7583. */
  7584. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7585. if (mask === void 0) { mask = -1; }
  7586. if (!this._observers.length) {
  7587. return true;
  7588. }
  7589. var state = this._eventState;
  7590. state.mask = mask;
  7591. state.target = target;
  7592. state.currentTarget = currentTarget;
  7593. state.skipNextObservers = false;
  7594. state.lastReturnValue = eventData;
  7595. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7596. var obs = _a[_i];
  7597. if (obs._willBeUnregistered) {
  7598. continue;
  7599. }
  7600. if (obs.mask & mask) {
  7601. if (obs.scope) {
  7602. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7603. }
  7604. else {
  7605. state.lastReturnValue = obs.callback(eventData, state);
  7606. }
  7607. if (obs.unregisterOnNextCall) {
  7608. this._deferUnregister(obs);
  7609. }
  7610. }
  7611. if (state.skipNextObservers) {
  7612. return false;
  7613. }
  7614. }
  7615. return true;
  7616. };
  7617. /**
  7618. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7619. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7620. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7621. * and it is crucial that all callbacks will be executed.
  7622. * The order of the callbacks is kept, callbacks are not executed parallel.
  7623. *
  7624. * @param eventData The data to be sent to each callback
  7625. * @param mask is used to filter observers defaults to -1
  7626. * @param target defines the callback target (see EventState)
  7627. * @param currentTarget defines he current object in the bubbling phase
  7628. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7629. */
  7630. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7631. var _this = this;
  7632. if (mask === void 0) { mask = -1; }
  7633. // create an empty promise
  7634. var p = Promise.resolve(eventData);
  7635. // no observers? return this promise.
  7636. if (!this._observers.length) {
  7637. return p;
  7638. }
  7639. var state = this._eventState;
  7640. state.mask = mask;
  7641. state.target = target;
  7642. state.currentTarget = currentTarget;
  7643. state.skipNextObservers = false;
  7644. // execute one callback after another (not using Promise.all, the order is important)
  7645. this._observers.forEach(function (obs) {
  7646. if (state.skipNextObservers) {
  7647. return;
  7648. }
  7649. if (obs._willBeUnregistered) {
  7650. return;
  7651. }
  7652. if (obs.mask & mask) {
  7653. if (obs.scope) {
  7654. p = p.then(function (lastReturnedValue) {
  7655. state.lastReturnValue = lastReturnedValue;
  7656. return obs.callback.apply(obs.scope, [eventData, state]);
  7657. });
  7658. }
  7659. else {
  7660. p = p.then(function (lastReturnedValue) {
  7661. state.lastReturnValue = lastReturnedValue;
  7662. return obs.callback(eventData, state);
  7663. });
  7664. }
  7665. if (obs.unregisterOnNextCall) {
  7666. _this._deferUnregister(obs);
  7667. }
  7668. }
  7669. });
  7670. // return the eventData
  7671. return p.then(function () { return eventData; });
  7672. };
  7673. /**
  7674. * Notify a specific observer
  7675. * @param observer defines the observer to notify
  7676. * @param eventData defines the data to be sent to each callback
  7677. * @param mask is used to filter observers defaults to -1
  7678. */
  7679. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7680. if (mask === void 0) { mask = -1; }
  7681. var state = this._eventState;
  7682. state.mask = mask;
  7683. state.skipNextObservers = false;
  7684. observer.callback(eventData, state);
  7685. };
  7686. /**
  7687. * Gets a boolean indicating if the observable has at least one observer
  7688. * @returns true is the Observable has at least one Observer registered
  7689. */
  7690. Observable.prototype.hasObservers = function () {
  7691. return this._observers.length > 0;
  7692. };
  7693. /**
  7694. * Clear the list of observers
  7695. */
  7696. Observable.prototype.clear = function () {
  7697. this._observers = new Array();
  7698. this._onObserverAdded = null;
  7699. };
  7700. /**
  7701. * Clone the current observable
  7702. * @returns a new observable
  7703. */
  7704. Observable.prototype.clone = function () {
  7705. var result = new Observable();
  7706. result._observers = this._observers.slice(0);
  7707. return result;
  7708. };
  7709. /**
  7710. * Does this observable handles observer registered with a given mask
  7711. * @param mask defines the mask to be tested
  7712. * @return whether or not one observer registered with the given mask is handeled
  7713. **/
  7714. Observable.prototype.hasSpecificMask = function (mask) {
  7715. if (mask === void 0) { mask = -1; }
  7716. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7717. var obs = _a[_i];
  7718. if (obs.mask & mask || obs.mask === mask) {
  7719. return true;
  7720. }
  7721. }
  7722. return false;
  7723. };
  7724. return Observable;
  7725. }());
  7726. BABYLON.Observable = Observable;
  7727. })(BABYLON || (BABYLON = {}));
  7728. //# sourceMappingURL=babylon.observable.js.map
  7729. "use strict";
  7730. var BABYLON;
  7731. (function (BABYLON) {
  7732. var SmartArray = /** @class */ (function () {
  7733. function SmartArray(capacity) {
  7734. this.length = 0;
  7735. this.data = new Array(capacity);
  7736. this._id = SmartArray._GlobalId++;
  7737. }
  7738. SmartArray.prototype.push = function (value) {
  7739. this.data[this.length++] = value;
  7740. if (this.length > this.data.length) {
  7741. this.data.length *= 2;
  7742. }
  7743. };
  7744. SmartArray.prototype.forEach = function (func) {
  7745. for (var index = 0; index < this.length; index++) {
  7746. func(this.data[index]);
  7747. }
  7748. };
  7749. SmartArray.prototype.sort = function (compareFn) {
  7750. this.data.sort(compareFn);
  7751. };
  7752. SmartArray.prototype.reset = function () {
  7753. this.length = 0;
  7754. };
  7755. SmartArray.prototype.dispose = function () {
  7756. this.reset();
  7757. if (this.data) {
  7758. this.data.length = 0;
  7759. this.data = [];
  7760. }
  7761. };
  7762. SmartArray.prototype.concat = function (array) {
  7763. if (array.length === 0) {
  7764. return;
  7765. }
  7766. if (this.length + array.length > this.data.length) {
  7767. this.data.length = (this.length + array.length) * 2;
  7768. }
  7769. for (var index = 0; index < array.length; index++) {
  7770. this.data[this.length++] = (array.data || array)[index];
  7771. }
  7772. };
  7773. SmartArray.prototype.indexOf = function (value) {
  7774. var position = this.data.indexOf(value);
  7775. if (position >= this.length) {
  7776. return -1;
  7777. }
  7778. return position;
  7779. };
  7780. SmartArray.prototype.contains = function (value) {
  7781. return this.data.indexOf(value) !== -1;
  7782. };
  7783. // Statics
  7784. SmartArray._GlobalId = 0;
  7785. return SmartArray;
  7786. }());
  7787. BABYLON.SmartArray = SmartArray;
  7788. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7789. __extends(SmartArrayNoDuplicate, _super);
  7790. function SmartArrayNoDuplicate() {
  7791. var _this = _super !== null && _super.apply(this, arguments) || this;
  7792. _this._duplicateId = 0;
  7793. return _this;
  7794. }
  7795. SmartArrayNoDuplicate.prototype.push = function (value) {
  7796. _super.prototype.push.call(this, value);
  7797. if (!value.__smartArrayFlags) {
  7798. value.__smartArrayFlags = {};
  7799. }
  7800. value.__smartArrayFlags[this._id] = this._duplicateId;
  7801. };
  7802. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7803. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7804. return false;
  7805. }
  7806. this.push(value);
  7807. return true;
  7808. };
  7809. SmartArrayNoDuplicate.prototype.reset = function () {
  7810. _super.prototype.reset.call(this);
  7811. this._duplicateId++;
  7812. };
  7813. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7814. if (array.length === 0) {
  7815. return;
  7816. }
  7817. if (this.length + array.length > this.data.length) {
  7818. this.data.length = (this.length + array.length) * 2;
  7819. }
  7820. for (var index = 0; index < array.length; index++) {
  7821. var item = (array.data || array)[index];
  7822. this.pushNoDuplicate(item);
  7823. }
  7824. };
  7825. return SmartArrayNoDuplicate;
  7826. }(SmartArray));
  7827. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7828. })(BABYLON || (BABYLON = {}));
  7829. //# sourceMappingURL=babylon.smartArray.js.map
  7830. "use strict";
  7831. var BABYLON;
  7832. (function (BABYLON) {
  7833. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7834. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7835. var LoadFileError = /** @class */ (function (_super) {
  7836. __extends(LoadFileError, _super);
  7837. function LoadFileError(message, request) {
  7838. var _this = _super.call(this, message) || this;
  7839. _this.request = request;
  7840. _this.name = "LoadFileError";
  7841. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7842. return _this;
  7843. }
  7844. // Polyfill for Object.setPrototypeOf if necessary.
  7845. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7846. return LoadFileError;
  7847. }(Error));
  7848. BABYLON.LoadFileError = LoadFileError;
  7849. var RetryStrategy = /** @class */ (function () {
  7850. function RetryStrategy() {
  7851. }
  7852. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7853. if (maxRetries === void 0) { maxRetries = 3; }
  7854. if (baseInterval === void 0) { baseInterval = 500; }
  7855. return function (url, request, retryIndex) {
  7856. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7857. return -1;
  7858. }
  7859. return Math.pow(2, retryIndex) * baseInterval;
  7860. };
  7861. };
  7862. return RetryStrategy;
  7863. }());
  7864. BABYLON.RetryStrategy = RetryStrategy;
  7865. // Screenshots
  7866. var screenshotCanvas;
  7867. var cloneValue = function (source, destinationObject) {
  7868. if (!source)
  7869. return null;
  7870. if (source instanceof BABYLON.Mesh) {
  7871. return null;
  7872. }
  7873. if (source instanceof BABYLON.SubMesh) {
  7874. return source.clone(destinationObject);
  7875. }
  7876. else if (source.clone) {
  7877. return source.clone();
  7878. }
  7879. return null;
  7880. };
  7881. var Tools = /** @class */ (function () {
  7882. function Tools() {
  7883. }
  7884. /**
  7885. * Interpolates between a and b via alpha
  7886. * @param a The lower value (returned when alpha = 0)
  7887. * @param b The upper value (returned when alpha = 1)
  7888. * @param alpha The interpolation-factor
  7889. * @return The mixed value
  7890. */
  7891. Tools.Mix = function (a, b, alpha) {
  7892. return a * (1 - alpha) + b * alpha;
  7893. };
  7894. Tools.Instantiate = function (className) {
  7895. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7896. return Tools.RegisteredExternalClasses[className];
  7897. }
  7898. var arr = className.split(".");
  7899. var fn = (window || this);
  7900. for (var i = 0, len = arr.length; i < len; i++) {
  7901. fn = fn[arr[i]];
  7902. }
  7903. if (typeof fn !== "function") {
  7904. return null;
  7905. }
  7906. return fn;
  7907. };
  7908. /**
  7909. * Provides a slice function that will work even on IE
  7910. * @param data defines the array to slice
  7911. * @returns the new sliced array
  7912. */
  7913. Tools.Slice = function (data) {
  7914. if (data.slice) {
  7915. return data.slice();
  7916. }
  7917. return Array.prototype.slice.call(data);
  7918. };
  7919. Tools.SetImmediate = function (action) {
  7920. if (window.setImmediate) {
  7921. window.setImmediate(action);
  7922. }
  7923. else {
  7924. setTimeout(action, 1);
  7925. }
  7926. };
  7927. Tools.IsExponentOfTwo = function (value) {
  7928. var count = 1;
  7929. do {
  7930. count *= 2;
  7931. } while (count < value);
  7932. return count === value;
  7933. };
  7934. /**
  7935. * Find the next highest power of two.
  7936. * @param x Number to start search from.
  7937. * @return Next highest power of two.
  7938. */
  7939. Tools.CeilingPOT = function (x) {
  7940. x--;
  7941. x |= x >> 1;
  7942. x |= x >> 2;
  7943. x |= x >> 4;
  7944. x |= x >> 8;
  7945. x |= x >> 16;
  7946. x++;
  7947. return x;
  7948. };
  7949. /**
  7950. * Find the next lowest power of two.
  7951. * @param x Number to start search from.
  7952. * @return Next lowest power of two.
  7953. */
  7954. Tools.FloorPOT = function (x) {
  7955. x = x | (x >> 1);
  7956. x = x | (x >> 2);
  7957. x = x | (x >> 4);
  7958. x = x | (x >> 8);
  7959. x = x | (x >> 16);
  7960. return x - (x >> 1);
  7961. };
  7962. /**
  7963. * Find the nearest power of two.
  7964. * @param x Number to start search from.
  7965. * @return Next nearest power of two.
  7966. */
  7967. Tools.NearestPOT = function (x) {
  7968. var c = Tools.CeilingPOT(x);
  7969. var f = Tools.FloorPOT(x);
  7970. return (c - x) > (x - f) ? f : c;
  7971. };
  7972. Tools.GetExponentOfTwo = function (value, max, mode) {
  7973. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7974. var pot;
  7975. switch (mode) {
  7976. case BABYLON.Engine.SCALEMODE_FLOOR:
  7977. pot = Tools.FloorPOT(value);
  7978. break;
  7979. case BABYLON.Engine.SCALEMODE_NEAREST:
  7980. pot = Tools.NearestPOT(value);
  7981. break;
  7982. case BABYLON.Engine.SCALEMODE_CEILING:
  7983. default:
  7984. pot = Tools.CeilingPOT(value);
  7985. break;
  7986. }
  7987. return Math.min(pot, max);
  7988. };
  7989. Tools.GetFilename = function (path) {
  7990. var index = path.lastIndexOf("/");
  7991. if (index < 0)
  7992. return path;
  7993. return path.substring(index + 1);
  7994. };
  7995. /**
  7996. * Extracts the "folder" part of a path (everything before the filename).
  7997. * @param uri The URI to extract the info from
  7998. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7999. * @returns The "folder" part of the path
  8000. */
  8001. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8002. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8003. var index = uri.lastIndexOf("/");
  8004. if (index < 0) {
  8005. if (returnUnchangedIfNoSlash) {
  8006. return uri;
  8007. }
  8008. return "";
  8009. }
  8010. return uri.substring(0, index + 1);
  8011. };
  8012. Tools.GetDOMTextContent = function (element) {
  8013. var result = "";
  8014. var child = element.firstChild;
  8015. while (child) {
  8016. if (child.nodeType === 3) {
  8017. result += child.textContent;
  8018. }
  8019. child = child.nextSibling;
  8020. }
  8021. return result;
  8022. };
  8023. Tools.ToDegrees = function (angle) {
  8024. return angle * 180 / Math.PI;
  8025. };
  8026. Tools.ToRadians = function (angle) {
  8027. return angle * Math.PI / 180;
  8028. };
  8029. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8030. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8031. var output = "";
  8032. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8033. var i = 0;
  8034. var bytes = new Uint8Array(buffer);
  8035. while (i < bytes.length) {
  8036. chr1 = bytes[i++];
  8037. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8038. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8039. enc1 = chr1 >> 2;
  8040. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8041. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8042. enc4 = chr3 & 63;
  8043. if (isNaN(chr2)) {
  8044. enc3 = enc4 = 64;
  8045. }
  8046. else if (isNaN(chr3)) {
  8047. enc4 = 64;
  8048. }
  8049. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8050. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8051. }
  8052. return "data:image/png;base64," + output;
  8053. };
  8054. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8055. if (bias === void 0) { bias = null; }
  8056. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8057. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8058. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8059. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8060. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8061. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8062. }
  8063. if (bias) {
  8064. minimum.x -= minimum.x * bias.x + bias.y;
  8065. minimum.y -= minimum.y * bias.x + bias.y;
  8066. minimum.z -= minimum.z * bias.x + bias.y;
  8067. maximum.x += maximum.x * bias.x + bias.y;
  8068. maximum.y += maximum.y * bias.x + bias.y;
  8069. maximum.z += maximum.z * bias.x + bias.y;
  8070. }
  8071. return {
  8072. minimum: minimum,
  8073. maximum: maximum
  8074. };
  8075. };
  8076. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8077. if (bias === void 0) { bias = null; }
  8078. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8079. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8080. if (!stride) {
  8081. stride = 3;
  8082. }
  8083. for (var index = start; index < start + count; index++) {
  8084. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8085. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8086. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8087. }
  8088. if (bias) {
  8089. minimum.x -= minimum.x * bias.x + bias.y;
  8090. minimum.y -= minimum.y * bias.x + bias.y;
  8091. minimum.z -= minimum.z * bias.x + bias.y;
  8092. maximum.x += maximum.x * bias.x + bias.y;
  8093. maximum.y += maximum.y * bias.x + bias.y;
  8094. maximum.z += maximum.z * bias.x + bias.y;
  8095. }
  8096. return {
  8097. minimum: minimum,
  8098. maximum: maximum
  8099. };
  8100. };
  8101. Tools.Vector2ArrayFeeder = function (array) {
  8102. return function (index) {
  8103. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8104. var length = isFloatArray ? array.length / 2 : array.length;
  8105. if (index >= length) {
  8106. return null;
  8107. }
  8108. if (isFloatArray) {
  8109. var fa = array;
  8110. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8111. }
  8112. var a = array;
  8113. return a[index];
  8114. };
  8115. };
  8116. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8117. if (bias === void 0) { bias = null; }
  8118. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8119. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8120. var i = 0;
  8121. var cur = feeder(i++);
  8122. while (cur) {
  8123. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8124. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8125. cur = feeder(i++);
  8126. }
  8127. if (bias) {
  8128. minimum.x -= minimum.x * bias.x + bias.y;
  8129. minimum.y -= minimum.y * bias.x + bias.y;
  8130. maximum.x += maximum.x * bias.x + bias.y;
  8131. maximum.y += maximum.y * bias.x + bias.y;
  8132. }
  8133. return {
  8134. minimum: minimum,
  8135. maximum: maximum
  8136. };
  8137. };
  8138. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8139. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8140. return null;
  8141. return Array.isArray(obj) ? obj : [obj];
  8142. };
  8143. // Misc.
  8144. Tools.GetPointerPrefix = function () {
  8145. var eventPrefix = "pointer";
  8146. // Check if pointer events are supported
  8147. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8148. eventPrefix = "mouse";
  8149. }
  8150. return eventPrefix;
  8151. };
  8152. /**
  8153. * @param func - the function to be called
  8154. * @param requester - the object that will request the next frame. Falls back to window.
  8155. */
  8156. Tools.QueueNewFrame = function (func, requester) {
  8157. if (!Tools.IsWindowObjectExist()) {
  8158. return setTimeout(func, 16);
  8159. }
  8160. if (!requester) {
  8161. requester = window;
  8162. }
  8163. if (requester.requestAnimationFrame) {
  8164. return requester.requestAnimationFrame(func);
  8165. }
  8166. else if (requester.msRequestAnimationFrame) {
  8167. return requester.msRequestAnimationFrame(func);
  8168. }
  8169. else if (requester.webkitRequestAnimationFrame) {
  8170. return requester.webkitRequestAnimationFrame(func);
  8171. }
  8172. else if (requester.mozRequestAnimationFrame) {
  8173. return requester.mozRequestAnimationFrame(func);
  8174. }
  8175. else if (requester.oRequestAnimationFrame) {
  8176. return requester.oRequestAnimationFrame(func);
  8177. }
  8178. else {
  8179. return window.setTimeout(func, 16);
  8180. }
  8181. };
  8182. Tools.RequestFullscreen = function (element) {
  8183. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8184. if (!requestFunction)
  8185. return;
  8186. requestFunction.call(element);
  8187. };
  8188. Tools.ExitFullscreen = function () {
  8189. if (document.exitFullscreen) {
  8190. document.exitFullscreen();
  8191. }
  8192. else if (document.mozCancelFullScreen) {
  8193. document.mozCancelFullScreen();
  8194. }
  8195. else if (document.webkitCancelFullScreen) {
  8196. document.webkitCancelFullScreen();
  8197. }
  8198. else if (document.msCancelFullScreen) {
  8199. document.msCancelFullScreen();
  8200. }
  8201. };
  8202. Tools.SetCorsBehavior = function (url, element) {
  8203. if (url && url.indexOf("data:") === 0) {
  8204. return;
  8205. }
  8206. if (Tools.CorsBehavior) {
  8207. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8208. element.crossOrigin = Tools.CorsBehavior;
  8209. }
  8210. else {
  8211. var result = Tools.CorsBehavior(url);
  8212. if (result) {
  8213. element.crossOrigin = result;
  8214. }
  8215. }
  8216. }
  8217. };
  8218. // External files
  8219. Tools.CleanUrl = function (url) {
  8220. url = url.replace(/#/mg, "%23");
  8221. return url;
  8222. };
  8223. Tools.LoadImage = function (url, onLoad, onError, database) {
  8224. if (url instanceof ArrayBuffer) {
  8225. url = Tools.EncodeArrayBufferTobase64(url);
  8226. }
  8227. url = Tools.CleanUrl(url);
  8228. url = Tools.PreprocessUrl(url);
  8229. var img = new Image();
  8230. Tools.SetCorsBehavior(url, img);
  8231. var loadHandler = function () {
  8232. img.removeEventListener("load", loadHandler);
  8233. img.removeEventListener("error", errorHandler);
  8234. onLoad(img);
  8235. };
  8236. var errorHandler = function (err) {
  8237. img.removeEventListener("load", loadHandler);
  8238. img.removeEventListener("error", errorHandler);
  8239. Tools.Error("Error while trying to load image: " + url);
  8240. if (onError) {
  8241. onError("Error while trying to load image: " + url, err);
  8242. }
  8243. };
  8244. img.addEventListener("load", loadHandler);
  8245. img.addEventListener("error", errorHandler);
  8246. var noIndexedDB = function () {
  8247. img.src = url;
  8248. };
  8249. var loadFromIndexedDB = function () {
  8250. if (database) {
  8251. database.loadImageFromDB(url, img);
  8252. }
  8253. };
  8254. //ANY database to do!
  8255. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8256. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8257. }
  8258. else {
  8259. if (url.indexOf("file:") !== -1) {
  8260. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8261. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8262. try {
  8263. var blobURL;
  8264. try {
  8265. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8266. }
  8267. catch (ex) {
  8268. // Chrome doesn't support oneTimeOnly parameter
  8269. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8270. }
  8271. img.src = blobURL;
  8272. }
  8273. catch (e) {
  8274. img.src = "";
  8275. }
  8276. return img;
  8277. }
  8278. }
  8279. noIndexedDB();
  8280. }
  8281. return img;
  8282. };
  8283. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8284. url = Tools.CleanUrl(url);
  8285. url = Tools.PreprocessUrl(url);
  8286. // If file and file input are set
  8287. if (url.indexOf("file:") !== -1) {
  8288. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8289. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8290. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8291. }
  8292. }
  8293. var loadUrl = Tools.BaseUrl + url;
  8294. var aborted = false;
  8295. var fileRequest = {
  8296. onCompleteObservable: new BABYLON.Observable(),
  8297. abort: function () { return aborted = true; },
  8298. };
  8299. var requestFile = function () {
  8300. var request = new XMLHttpRequest();
  8301. var retryHandle = null;
  8302. fileRequest.abort = function () {
  8303. aborted = true;
  8304. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8305. request.abort();
  8306. }
  8307. if (retryHandle !== null) {
  8308. clearTimeout(retryHandle);
  8309. retryHandle = null;
  8310. }
  8311. };
  8312. var retryLoop = function (retryIndex) {
  8313. request.open('GET', loadUrl, true);
  8314. if (useArrayBuffer) {
  8315. request.responseType = "arraybuffer";
  8316. }
  8317. if (onProgress) {
  8318. request.addEventListener("progress", onProgress);
  8319. }
  8320. var onLoadEnd = function () {
  8321. request.removeEventListener("loadend", onLoadEnd);
  8322. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8323. fileRequest.onCompleteObservable.clear();
  8324. };
  8325. request.addEventListener("loadend", onLoadEnd);
  8326. var onReadyStateChange = function () {
  8327. if (aborted) {
  8328. return;
  8329. }
  8330. // In case of undefined state in some browsers.
  8331. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8332. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8333. request.removeEventListener("readystatechange", onReadyStateChange);
  8334. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8335. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8336. return;
  8337. }
  8338. var retryStrategy = Tools.DefaultRetryStrategy;
  8339. if (retryStrategy) {
  8340. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8341. if (waitTime !== -1) {
  8342. // Prevent the request from completing for retry.
  8343. request.removeEventListener("loadend", onLoadEnd);
  8344. request = new XMLHttpRequest();
  8345. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8346. return;
  8347. }
  8348. }
  8349. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8350. if (onError) {
  8351. onError(request, e);
  8352. }
  8353. else {
  8354. throw e;
  8355. }
  8356. }
  8357. };
  8358. request.addEventListener("readystatechange", onReadyStateChange);
  8359. request.send();
  8360. };
  8361. retryLoop(0);
  8362. };
  8363. // Caching all files
  8364. if (database && database.enableSceneOffline) {
  8365. var noIndexedDB_1 = function () {
  8366. if (!aborted) {
  8367. requestFile();
  8368. }
  8369. };
  8370. var loadFromIndexedDB = function () {
  8371. // TODO: database needs to support aborting and should return a IFileRequest
  8372. if (aborted) {
  8373. return;
  8374. }
  8375. if (database) {
  8376. database.loadFileFromDB(url, function (data) {
  8377. if (!aborted) {
  8378. onSuccess(data);
  8379. }
  8380. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8381. }, onProgress ? function (event) {
  8382. if (!aborted) {
  8383. onProgress(event);
  8384. }
  8385. } : undefined, noIndexedDB_1, useArrayBuffer);
  8386. }
  8387. };
  8388. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8389. }
  8390. else {
  8391. requestFile();
  8392. }
  8393. return fileRequest;
  8394. };
  8395. /**
  8396. * Load a script (identified by an url). When the url returns, the
  8397. * content of this file is added into a new script element, attached to the DOM (body element)
  8398. */
  8399. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8400. var head = document.getElementsByTagName('head')[0];
  8401. var script = document.createElement('script');
  8402. script.type = 'text/javascript';
  8403. script.src = scriptUrl;
  8404. script.onload = function () {
  8405. if (onSuccess) {
  8406. onSuccess();
  8407. }
  8408. };
  8409. script.onerror = function (e) {
  8410. if (onError) {
  8411. onError("Unable to load script", e);
  8412. }
  8413. };
  8414. head.appendChild(script);
  8415. };
  8416. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8417. var reader = new FileReader();
  8418. var request = {
  8419. onCompleteObservable: new BABYLON.Observable(),
  8420. abort: function () { return reader.abort(); },
  8421. };
  8422. reader.onloadend = function (e) {
  8423. request.onCompleteObservable.notifyObservers(request);
  8424. };
  8425. reader.onload = function (e) {
  8426. //target doesn't have result from ts 1.3
  8427. callback(e.target['result']);
  8428. };
  8429. reader.onprogress = progressCallback;
  8430. reader.readAsDataURL(fileToLoad);
  8431. return request;
  8432. };
  8433. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8434. var reader = new FileReader();
  8435. var request = {
  8436. onCompleteObservable: new BABYLON.Observable(),
  8437. abort: function () { return reader.abort(); },
  8438. };
  8439. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8440. reader.onerror = function (e) {
  8441. Tools.Log("Error while reading file: " + fileToLoad.name);
  8442. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8443. };
  8444. reader.onload = function (e) {
  8445. //target doesn't have result from ts 1.3
  8446. callback(e.target['result']);
  8447. };
  8448. if (progressCallBack) {
  8449. reader.onprogress = progressCallBack;
  8450. }
  8451. if (!useArrayBuffer) {
  8452. // Asynchronous read
  8453. reader.readAsText(fileToLoad);
  8454. }
  8455. else {
  8456. reader.readAsArrayBuffer(fileToLoad);
  8457. }
  8458. return request;
  8459. };
  8460. //returns a downloadable url to a file content.
  8461. Tools.FileAsURL = function (content) {
  8462. var fileBlob = new Blob([content]);
  8463. var url = window.URL || window.webkitURL;
  8464. var link = url.createObjectURL(fileBlob);
  8465. return link;
  8466. };
  8467. // Misc.
  8468. Tools.Format = function (value, decimals) {
  8469. if (decimals === void 0) { decimals = 2; }
  8470. return value.toFixed(decimals);
  8471. };
  8472. Tools.CheckExtends = function (v, min, max) {
  8473. if (v.x < min.x)
  8474. min.x = v.x;
  8475. if (v.y < min.y)
  8476. min.y = v.y;
  8477. if (v.z < min.z)
  8478. min.z = v.z;
  8479. if (v.x > max.x)
  8480. max.x = v.x;
  8481. if (v.y > max.y)
  8482. max.y = v.y;
  8483. if (v.z > max.z)
  8484. max.z = v.z;
  8485. };
  8486. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8487. for (var prop in source) {
  8488. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8489. continue;
  8490. }
  8491. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8492. continue;
  8493. }
  8494. var sourceValue = source[prop];
  8495. var typeOfSourceValue = typeof sourceValue;
  8496. if (typeOfSourceValue === "function") {
  8497. continue;
  8498. }
  8499. try {
  8500. if (typeOfSourceValue === "object") {
  8501. if (sourceValue instanceof Array) {
  8502. destination[prop] = [];
  8503. if (sourceValue.length > 0) {
  8504. if (typeof sourceValue[0] == "object") {
  8505. for (var index = 0; index < sourceValue.length; index++) {
  8506. var clonedValue = cloneValue(sourceValue[index], destination);
  8507. if (destination[prop].indexOf(clonedValue) === -1) {
  8508. destination[prop].push(clonedValue);
  8509. }
  8510. }
  8511. }
  8512. else {
  8513. destination[prop] = sourceValue.slice(0);
  8514. }
  8515. }
  8516. }
  8517. else {
  8518. destination[prop] = cloneValue(sourceValue, destination);
  8519. }
  8520. }
  8521. else {
  8522. destination[prop] = sourceValue;
  8523. }
  8524. }
  8525. catch (e) {
  8526. // Just ignore error (it could be because of a read-only property)
  8527. }
  8528. }
  8529. };
  8530. Tools.IsEmpty = function (obj) {
  8531. for (var i in obj) {
  8532. if (obj.hasOwnProperty(i)) {
  8533. return false;
  8534. }
  8535. }
  8536. return true;
  8537. };
  8538. Tools.RegisterTopRootEvents = function (events) {
  8539. for (var index = 0; index < events.length; index++) {
  8540. var event = events[index];
  8541. window.addEventListener(event.name, event.handler, false);
  8542. try {
  8543. if (window.parent) {
  8544. window.parent.addEventListener(event.name, event.handler, false);
  8545. }
  8546. }
  8547. catch (e) {
  8548. // Silently fails...
  8549. }
  8550. }
  8551. };
  8552. Tools.UnregisterTopRootEvents = function (events) {
  8553. for (var index = 0; index < events.length; index++) {
  8554. var event = events[index];
  8555. window.removeEventListener(event.name, event.handler);
  8556. try {
  8557. if (window.parent) {
  8558. window.parent.removeEventListener(event.name, event.handler);
  8559. }
  8560. }
  8561. catch (e) {
  8562. // Silently fails...
  8563. }
  8564. }
  8565. };
  8566. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8567. if (mimeType === void 0) { mimeType = "image/png"; }
  8568. // Read the contents of the framebuffer
  8569. var numberOfChannelsByLine = width * 4;
  8570. var halfHeight = height / 2;
  8571. //Reading datas from WebGL
  8572. var data = engine.readPixels(0, 0, width, height);
  8573. //To flip image on Y axis.
  8574. for (var i = 0; i < halfHeight; i++) {
  8575. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8576. var currentCell = j + i * numberOfChannelsByLine;
  8577. var targetLine = height - i - 1;
  8578. var targetCell = j + targetLine * numberOfChannelsByLine;
  8579. var temp = data[currentCell];
  8580. data[currentCell] = data[targetCell];
  8581. data[targetCell] = temp;
  8582. }
  8583. }
  8584. // Create a 2D canvas to store the result
  8585. if (!screenshotCanvas) {
  8586. screenshotCanvas = document.createElement('canvas');
  8587. }
  8588. screenshotCanvas.width = width;
  8589. screenshotCanvas.height = height;
  8590. var context = screenshotCanvas.getContext('2d');
  8591. if (context) {
  8592. // Copy the pixels to a 2D canvas
  8593. var imageData = context.createImageData(width, height);
  8594. var castData = (imageData.data);
  8595. castData.set(data);
  8596. context.putImageData(imageData, 0, 0);
  8597. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8598. }
  8599. };
  8600. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8601. if (mimeType === void 0) { mimeType = "image/png"; }
  8602. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8603. if (successCallback) {
  8604. successCallback(base64Image);
  8605. }
  8606. else {
  8607. // We need HTMLCanvasElement.toBlob for HD screenshots
  8608. if (!screenshotCanvas.toBlob) {
  8609. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8610. screenshotCanvas.toBlob = function (callback, type, quality) {
  8611. var _this = this;
  8612. setTimeout(function () {
  8613. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8614. for (var i = 0; i < len; i++) {
  8615. arr[i] = binStr.charCodeAt(i);
  8616. }
  8617. callback(new Blob([arr], { type: type || 'image/png' }));
  8618. });
  8619. };
  8620. }
  8621. screenshotCanvas.toBlob(function (blob) {
  8622. var url = URL.createObjectURL(blob);
  8623. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8624. if (("download" in document.createElement("a"))) {
  8625. var a = window.document.createElement("a");
  8626. a.href = url;
  8627. if (fileName) {
  8628. a.setAttribute("download", fileName);
  8629. }
  8630. else {
  8631. var date = new Date();
  8632. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8633. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8634. }
  8635. window.document.body.appendChild(a);
  8636. a.addEventListener("click", function () {
  8637. if (a.parentElement) {
  8638. a.parentElement.removeChild(a);
  8639. }
  8640. });
  8641. a.click();
  8642. }
  8643. else {
  8644. var newWindow = window.open("");
  8645. if (!newWindow)
  8646. return;
  8647. var img = newWindow.document.createElement("img");
  8648. img.onload = function () {
  8649. // no longer need to read the blob so it's revoked
  8650. URL.revokeObjectURL(url);
  8651. };
  8652. img.src = url;
  8653. newWindow.document.body.appendChild(img);
  8654. }
  8655. });
  8656. }
  8657. };
  8658. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8659. if (mimeType === void 0) { mimeType = "image/png"; }
  8660. var width;
  8661. var height;
  8662. // If a precision value is specified
  8663. if (size.precision) {
  8664. width = Math.round(engine.getRenderWidth() * size.precision);
  8665. height = Math.round(width / engine.getAspectRatio(camera));
  8666. }
  8667. else if (size.width && size.height) {
  8668. width = size.width;
  8669. height = size.height;
  8670. }
  8671. else if (size.width && !size.height) {
  8672. width = size.width;
  8673. height = Math.round(width / engine.getAspectRatio(camera));
  8674. }
  8675. else if (size.height && !size.width) {
  8676. height = size.height;
  8677. width = Math.round(height * engine.getAspectRatio(camera));
  8678. }
  8679. else if (!isNaN(size)) {
  8680. height = size;
  8681. width = size;
  8682. }
  8683. else {
  8684. Tools.Error("Invalid 'size' parameter !");
  8685. return;
  8686. }
  8687. if (!screenshotCanvas) {
  8688. screenshotCanvas = document.createElement('canvas');
  8689. }
  8690. screenshotCanvas.width = width;
  8691. screenshotCanvas.height = height;
  8692. var renderContext = screenshotCanvas.getContext("2d");
  8693. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8694. var newWidth = width;
  8695. var newHeight = newWidth / ratio;
  8696. if (newHeight > height) {
  8697. newHeight = height;
  8698. newWidth = newHeight * ratio;
  8699. }
  8700. var offsetX = Math.max(0, width - newWidth) / 2;
  8701. var offsetY = Math.max(0, height - newHeight) / 2;
  8702. var renderingCanvas = engine.getRenderingCanvas();
  8703. if (renderContext && renderingCanvas) {
  8704. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8705. }
  8706. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8707. };
  8708. /**
  8709. * Generates an image screenshot from the specified camera.
  8710. *
  8711. * @param engine The engine to use for rendering
  8712. * @param camera The camera to use for rendering
  8713. * @param size This parameter can be set to a single number or to an object with the
  8714. * following (optional) properties: precision, width, height. If a single number is passed,
  8715. * it will be used for both width and height. If an object is passed, the screenshot size
  8716. * will be derived from the parameters. The precision property is a multiplier allowing
  8717. * rendering at a higher or lower resolution.
  8718. * @param successCallback The callback receives a single parameter which contains the
  8719. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8720. * src parameter of an <img> to display it.
  8721. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8722. * Check your browser for supported MIME types.
  8723. * @param samples Texture samples (default: 1)
  8724. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8725. * @param fileName A name for for the downloaded file.
  8726. * @constructor
  8727. */
  8728. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8729. if (mimeType === void 0) { mimeType = "image/png"; }
  8730. if (samples === void 0) { samples = 1; }
  8731. if (antialiasing === void 0) { antialiasing = false; }
  8732. var width;
  8733. var height;
  8734. //If a precision value is specified
  8735. if (size.precision) {
  8736. width = Math.round(engine.getRenderWidth() * size.precision);
  8737. height = Math.round(width / engine.getAspectRatio(camera));
  8738. size = { width: width, height: height };
  8739. }
  8740. else if (size.width && size.height) {
  8741. width = size.width;
  8742. height = size.height;
  8743. }
  8744. else if (size.width && !size.height) {
  8745. width = size.width;
  8746. height = Math.round(width / engine.getAspectRatio(camera));
  8747. size = { width: width, height: height };
  8748. }
  8749. else if (size.height && !size.width) {
  8750. height = size.height;
  8751. width = Math.round(height * engine.getAspectRatio(camera));
  8752. size = { width: width, height: height };
  8753. }
  8754. else if (!isNaN(size)) {
  8755. height = size;
  8756. width = size;
  8757. }
  8758. else {
  8759. Tools.Error("Invalid 'size' parameter !");
  8760. return;
  8761. }
  8762. var scene = camera.getScene();
  8763. var previousCamera = null;
  8764. if (scene.activeCamera !== camera) {
  8765. previousCamera = scene.activeCamera;
  8766. scene.activeCamera = camera;
  8767. }
  8768. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8769. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8770. texture.renderList = null;
  8771. texture.samples = samples;
  8772. if (antialiasing) {
  8773. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8774. }
  8775. texture.onAfterRenderObservable.add(function () {
  8776. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8777. });
  8778. scene.incrementRenderId();
  8779. scene.resetCachedMaterial();
  8780. texture.render(true);
  8781. texture.dispose();
  8782. if (previousCamera) {
  8783. scene.activeCamera = previousCamera;
  8784. }
  8785. camera.getProjectionMatrix(true); // Force cache refresh;
  8786. };
  8787. // XHR response validator for local file scenario
  8788. Tools.ValidateXHRData = function (xhr, dataType) {
  8789. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8790. if (dataType === void 0) { dataType = 7; }
  8791. try {
  8792. if (dataType & 1) {
  8793. if (xhr.responseText && xhr.responseText.length > 0) {
  8794. return true;
  8795. }
  8796. else if (dataType === 1) {
  8797. return false;
  8798. }
  8799. }
  8800. if (dataType & 2) {
  8801. // Check header width and height since there is no "TGA" magic number
  8802. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8803. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8804. return true;
  8805. }
  8806. else if (dataType === 2) {
  8807. return false;
  8808. }
  8809. }
  8810. if (dataType & 4) {
  8811. // Check for the "DDS" magic number
  8812. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8813. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8814. return true;
  8815. }
  8816. else {
  8817. return false;
  8818. }
  8819. }
  8820. }
  8821. catch (e) {
  8822. // Global protection
  8823. }
  8824. return false;
  8825. };
  8826. /**
  8827. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8828. * Be aware Math.random() could cause collisions, but:
  8829. * "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"
  8830. */
  8831. Tools.RandomId = function () {
  8832. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8833. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8834. return v.toString(16);
  8835. });
  8836. };
  8837. /**
  8838. * Test if the given uri is a base64 string.
  8839. * @param uri The uri to test
  8840. * @return True if the uri is a base64 string or false otherwise.
  8841. */
  8842. Tools.IsBase64 = function (uri) {
  8843. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8844. };
  8845. /**
  8846. * Decode the given base64 uri.
  8847. * @param uri The uri to decode
  8848. * @return The decoded base64 data.
  8849. */
  8850. Tools.DecodeBase64 = function (uri) {
  8851. var decodedString = atob(uri.split(",")[1]);
  8852. var bufferLength = decodedString.length;
  8853. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8854. for (var i = 0; i < bufferLength; i++) {
  8855. bufferView[i] = decodedString.charCodeAt(i);
  8856. }
  8857. return bufferView.buffer;
  8858. };
  8859. Object.defineProperty(Tools, "NoneLogLevel", {
  8860. get: function () {
  8861. return Tools._NoneLogLevel;
  8862. },
  8863. enumerable: true,
  8864. configurable: true
  8865. });
  8866. Object.defineProperty(Tools, "MessageLogLevel", {
  8867. get: function () {
  8868. return Tools._MessageLogLevel;
  8869. },
  8870. enumerable: true,
  8871. configurable: true
  8872. });
  8873. Object.defineProperty(Tools, "WarningLogLevel", {
  8874. get: function () {
  8875. return Tools._WarningLogLevel;
  8876. },
  8877. enumerable: true,
  8878. configurable: true
  8879. });
  8880. Object.defineProperty(Tools, "ErrorLogLevel", {
  8881. get: function () {
  8882. return Tools._ErrorLogLevel;
  8883. },
  8884. enumerable: true,
  8885. configurable: true
  8886. });
  8887. Object.defineProperty(Tools, "AllLogLevel", {
  8888. get: function () {
  8889. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8890. },
  8891. enumerable: true,
  8892. configurable: true
  8893. });
  8894. Tools._AddLogEntry = function (entry) {
  8895. Tools._LogCache = entry + Tools._LogCache;
  8896. if (Tools.OnNewCacheEntry) {
  8897. Tools.OnNewCacheEntry(entry);
  8898. }
  8899. };
  8900. Tools._FormatMessage = function (message) {
  8901. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8902. var date = new Date();
  8903. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8904. };
  8905. Tools._LogDisabled = function (message) {
  8906. // nothing to do
  8907. };
  8908. Tools._LogEnabled = function (message) {
  8909. var formattedMessage = Tools._FormatMessage(message);
  8910. console.log("BJS - " + formattedMessage);
  8911. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8912. Tools._AddLogEntry(entry);
  8913. };
  8914. Tools._WarnDisabled = function (message) {
  8915. // nothing to do
  8916. };
  8917. Tools._WarnEnabled = function (message) {
  8918. var formattedMessage = Tools._FormatMessage(message);
  8919. console.warn("BJS - " + formattedMessage);
  8920. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8921. Tools._AddLogEntry(entry);
  8922. };
  8923. Tools._ErrorDisabled = function (message) {
  8924. // nothing to do
  8925. };
  8926. Tools._ErrorEnabled = function (message) {
  8927. Tools.errorsCount++;
  8928. var formattedMessage = Tools._FormatMessage(message);
  8929. console.error("BJS - " + formattedMessage);
  8930. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8931. Tools._AddLogEntry(entry);
  8932. };
  8933. Object.defineProperty(Tools, "LogCache", {
  8934. get: function () {
  8935. return Tools._LogCache;
  8936. },
  8937. enumerable: true,
  8938. configurable: true
  8939. });
  8940. Tools.ClearLogCache = function () {
  8941. Tools._LogCache = "";
  8942. Tools.errorsCount = 0;
  8943. };
  8944. Object.defineProperty(Tools, "LogLevels", {
  8945. set: function (level) {
  8946. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8947. Tools.Log = Tools._LogEnabled;
  8948. }
  8949. else {
  8950. Tools.Log = Tools._LogDisabled;
  8951. }
  8952. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8953. Tools.Warn = Tools._WarnEnabled;
  8954. }
  8955. else {
  8956. Tools.Warn = Tools._WarnDisabled;
  8957. }
  8958. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8959. Tools.Error = Tools._ErrorEnabled;
  8960. }
  8961. else {
  8962. Tools.Error = Tools._ErrorDisabled;
  8963. }
  8964. },
  8965. enumerable: true,
  8966. configurable: true
  8967. });
  8968. Tools.IsWindowObjectExist = function () {
  8969. return (typeof window) !== "undefined";
  8970. };
  8971. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8972. get: function () {
  8973. return Tools._PerformanceNoneLogLevel;
  8974. },
  8975. enumerable: true,
  8976. configurable: true
  8977. });
  8978. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8979. get: function () {
  8980. return Tools._PerformanceUserMarkLogLevel;
  8981. },
  8982. enumerable: true,
  8983. configurable: true
  8984. });
  8985. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8986. get: function () {
  8987. return Tools._PerformanceConsoleLogLevel;
  8988. },
  8989. enumerable: true,
  8990. configurable: true
  8991. });
  8992. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8993. set: function (level) {
  8994. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8995. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8996. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8997. return;
  8998. }
  8999. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9000. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9001. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9002. return;
  9003. }
  9004. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9005. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9006. },
  9007. enumerable: true,
  9008. configurable: true
  9009. });
  9010. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9011. };
  9012. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9013. };
  9014. Tools._StartUserMark = function (counterName, condition) {
  9015. if (condition === void 0) { condition = true; }
  9016. if (!Tools._performance) {
  9017. if (!Tools.IsWindowObjectExist()) {
  9018. return;
  9019. }
  9020. Tools._performance = window.performance;
  9021. }
  9022. if (!condition || !Tools._performance.mark) {
  9023. return;
  9024. }
  9025. Tools._performance.mark(counterName + "-Begin");
  9026. };
  9027. Tools._EndUserMark = function (counterName, condition) {
  9028. if (condition === void 0) { condition = true; }
  9029. if (!condition || !Tools._performance.mark) {
  9030. return;
  9031. }
  9032. Tools._performance.mark(counterName + "-End");
  9033. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9034. };
  9035. Tools._StartPerformanceConsole = function (counterName, condition) {
  9036. if (condition === void 0) { condition = true; }
  9037. if (!condition) {
  9038. return;
  9039. }
  9040. Tools._StartUserMark(counterName, condition);
  9041. if (console.time) {
  9042. console.time(counterName);
  9043. }
  9044. };
  9045. Tools._EndPerformanceConsole = function (counterName, condition) {
  9046. if (condition === void 0) { condition = true; }
  9047. if (!condition) {
  9048. return;
  9049. }
  9050. Tools._EndUserMark(counterName, condition);
  9051. if (console.time) {
  9052. console.timeEnd(counterName);
  9053. }
  9054. };
  9055. Object.defineProperty(Tools, "Now", {
  9056. get: function () {
  9057. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9058. return window.performance.now();
  9059. }
  9060. return new Date().getTime();
  9061. },
  9062. enumerable: true,
  9063. configurable: true
  9064. });
  9065. /**
  9066. * This method will return the name of the class used to create the instance of the given object.
  9067. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9068. * @param object the object to get the class name from
  9069. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9070. */
  9071. Tools.GetClassName = function (object, isType) {
  9072. if (isType === void 0) { isType = false; }
  9073. var name = null;
  9074. if (!isType && object.getClassName) {
  9075. name = object.getClassName();
  9076. }
  9077. else {
  9078. if (object instanceof Object) {
  9079. var classObj = isType ? object : Object.getPrototypeOf(object);
  9080. name = classObj.constructor["__bjsclassName__"];
  9081. }
  9082. if (!name) {
  9083. name = typeof object;
  9084. }
  9085. }
  9086. return name;
  9087. };
  9088. Tools.First = function (array, predicate) {
  9089. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9090. var el = array_1[_i];
  9091. if (predicate(el)) {
  9092. return el;
  9093. }
  9094. }
  9095. return null;
  9096. };
  9097. /**
  9098. * This method will return the name of the full name of the class, including its owning module (if any).
  9099. * 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).
  9100. * @param object the object to get the class name from
  9101. * @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.
  9102. */
  9103. Tools.getFullClassName = function (object, isType) {
  9104. if (isType === void 0) { isType = false; }
  9105. var className = null;
  9106. var moduleName = null;
  9107. if (!isType && object.getClassName) {
  9108. className = object.getClassName();
  9109. }
  9110. else {
  9111. if (object instanceof Object) {
  9112. var classObj = isType ? object : Object.getPrototypeOf(object);
  9113. className = classObj.constructor["__bjsclassName__"];
  9114. moduleName = classObj.constructor["__bjsmoduleName__"];
  9115. }
  9116. if (!className) {
  9117. className = typeof object;
  9118. }
  9119. }
  9120. if (!className) {
  9121. return null;
  9122. }
  9123. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9124. };
  9125. /**
  9126. * 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.
  9127. * @param array
  9128. */
  9129. Tools.arrayOrStringFeeder = function (array) {
  9130. return function (index) {
  9131. if (index >= array.length) {
  9132. return null;
  9133. }
  9134. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9135. if (val && val.getHashCode) {
  9136. val = val.getHashCode();
  9137. }
  9138. if (typeof val === "string") {
  9139. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9140. }
  9141. return val;
  9142. };
  9143. };
  9144. /**
  9145. * Compute the hashCode of a stream of number
  9146. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9147. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9148. * @return the hash code computed
  9149. */
  9150. Tools.hashCodeFromStream = function (feeder) {
  9151. // Based from here: http://stackoverflow.com/a/7616484/802124
  9152. var hash = 0;
  9153. var index = 0;
  9154. var chr = feeder(index++);
  9155. while (chr != null) {
  9156. hash = ((hash << 5) - hash) + chr;
  9157. hash |= 0; // Convert to 32bit integer
  9158. chr = feeder(index++);
  9159. }
  9160. return hash;
  9161. };
  9162. /**
  9163. * Returns a promise that resolves after the given amount of time.
  9164. * @param delay Number of milliseconds to delay
  9165. * @returns Promise that resolves after the given amount of time
  9166. */
  9167. Tools.DelayAsync = function (delay) {
  9168. return new Promise(function (resolve) {
  9169. setTimeout(function () {
  9170. resolve();
  9171. }, delay);
  9172. });
  9173. };
  9174. Tools.BaseUrl = "";
  9175. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9176. /**
  9177. * Default behaviour for cors in the application.
  9178. * It can be a string if the expected behavior is identical in the entire app.
  9179. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9180. */
  9181. Tools.CorsBehavior = "anonymous";
  9182. Tools.UseFallbackTexture = true;
  9183. /**
  9184. * Use this object to register external classes like custom textures or material
  9185. * to allow the laoders to instantiate them
  9186. */
  9187. Tools.RegisteredExternalClasses = {};
  9188. // Used in case of a texture loading problem
  9189. 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";
  9190. Tools.PreprocessUrl = function (url) {
  9191. return url;
  9192. };
  9193. // Logs
  9194. Tools._NoneLogLevel = 0;
  9195. Tools._MessageLogLevel = 1;
  9196. Tools._WarningLogLevel = 2;
  9197. Tools._ErrorLogLevel = 4;
  9198. Tools._LogCache = "";
  9199. Tools.errorsCount = 0;
  9200. Tools.Log = Tools._LogEnabled;
  9201. Tools.Warn = Tools._WarnEnabled;
  9202. Tools.Error = Tools._ErrorEnabled;
  9203. // Performances
  9204. Tools._PerformanceNoneLogLevel = 0;
  9205. Tools._PerformanceUserMarkLogLevel = 1;
  9206. Tools._PerformanceConsoleLogLevel = 2;
  9207. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9208. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9209. return Tools;
  9210. }());
  9211. BABYLON.Tools = Tools;
  9212. /**
  9213. * This class is used to track a performance counter which is number based.
  9214. * The user has access to many properties which give statistics of different nature
  9215. *
  9216. * The implementer can track two kinds of Performance Counter: time and count
  9217. * 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.
  9218. * 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.
  9219. */
  9220. var PerfCounter = /** @class */ (function () {
  9221. function PerfCounter() {
  9222. this._startMonitoringTime = 0;
  9223. this._min = 0;
  9224. this._max = 0;
  9225. this._average = 0;
  9226. this._lastSecAverage = 0;
  9227. this._current = 0;
  9228. this._totalValueCount = 0;
  9229. this._totalAccumulated = 0;
  9230. this._lastSecAccumulated = 0;
  9231. this._lastSecTime = 0;
  9232. this._lastSecValueCount = 0;
  9233. }
  9234. Object.defineProperty(PerfCounter.prototype, "min", {
  9235. /**
  9236. * Returns the smallest value ever
  9237. */
  9238. get: function () {
  9239. return this._min;
  9240. },
  9241. enumerable: true,
  9242. configurable: true
  9243. });
  9244. Object.defineProperty(PerfCounter.prototype, "max", {
  9245. /**
  9246. * Returns the biggest value ever
  9247. */
  9248. get: function () {
  9249. return this._max;
  9250. },
  9251. enumerable: true,
  9252. configurable: true
  9253. });
  9254. Object.defineProperty(PerfCounter.prototype, "average", {
  9255. /**
  9256. * Returns the average value since the performance counter is running
  9257. */
  9258. get: function () {
  9259. return this._average;
  9260. },
  9261. enumerable: true,
  9262. configurable: true
  9263. });
  9264. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9265. /**
  9266. * Returns the average value of the last second the counter was monitored
  9267. */
  9268. get: function () {
  9269. return this._lastSecAverage;
  9270. },
  9271. enumerable: true,
  9272. configurable: true
  9273. });
  9274. Object.defineProperty(PerfCounter.prototype, "current", {
  9275. /**
  9276. * Returns the current value
  9277. */
  9278. get: function () {
  9279. return this._current;
  9280. },
  9281. enumerable: true,
  9282. configurable: true
  9283. });
  9284. Object.defineProperty(PerfCounter.prototype, "total", {
  9285. get: function () {
  9286. return this._totalAccumulated;
  9287. },
  9288. enumerable: true,
  9289. configurable: true
  9290. });
  9291. Object.defineProperty(PerfCounter.prototype, "count", {
  9292. get: function () {
  9293. return this._totalValueCount;
  9294. },
  9295. enumerable: true,
  9296. configurable: true
  9297. });
  9298. /**
  9299. * Call this method to start monitoring a new frame.
  9300. * 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.
  9301. */
  9302. PerfCounter.prototype.fetchNewFrame = function () {
  9303. this._totalValueCount++;
  9304. this._current = 0;
  9305. this._lastSecValueCount++;
  9306. };
  9307. /**
  9308. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9309. * @param newCount the count value to add to the monitored count
  9310. * @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.
  9311. */
  9312. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9313. if (!PerfCounter.Enabled) {
  9314. return;
  9315. }
  9316. this._current += newCount;
  9317. if (fetchResult) {
  9318. this._fetchResult();
  9319. }
  9320. };
  9321. /**
  9322. * Start monitoring this performance counter
  9323. */
  9324. PerfCounter.prototype.beginMonitoring = function () {
  9325. if (!PerfCounter.Enabled) {
  9326. return;
  9327. }
  9328. this._startMonitoringTime = Tools.Now;
  9329. };
  9330. /**
  9331. * Compute the time lapsed since the previous beginMonitoring() call.
  9332. * @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
  9333. */
  9334. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9335. if (newFrame === void 0) { newFrame = true; }
  9336. if (!PerfCounter.Enabled) {
  9337. return;
  9338. }
  9339. if (newFrame) {
  9340. this.fetchNewFrame();
  9341. }
  9342. var currentTime = Tools.Now;
  9343. this._current = currentTime - this._startMonitoringTime;
  9344. if (newFrame) {
  9345. this._fetchResult();
  9346. }
  9347. };
  9348. PerfCounter.prototype._fetchResult = function () {
  9349. this._totalAccumulated += this._current;
  9350. this._lastSecAccumulated += this._current;
  9351. // Min/Max update
  9352. this._min = Math.min(this._min, this._current);
  9353. this._max = Math.max(this._max, this._current);
  9354. this._average = this._totalAccumulated / this._totalValueCount;
  9355. // Reset last sec?
  9356. var now = Tools.Now;
  9357. if ((now - this._lastSecTime) > 1000) {
  9358. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9359. this._lastSecTime = now;
  9360. this._lastSecAccumulated = 0;
  9361. this._lastSecValueCount = 0;
  9362. }
  9363. };
  9364. PerfCounter.Enabled = true;
  9365. return PerfCounter;
  9366. }());
  9367. BABYLON.PerfCounter = PerfCounter;
  9368. /**
  9369. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9370. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9371. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9372. * @param name The name of the class, case should be preserved
  9373. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9374. */
  9375. function className(name, module) {
  9376. return function (target) {
  9377. target["__bjsclassName__"] = name;
  9378. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9379. };
  9380. }
  9381. BABYLON.className = className;
  9382. /**
  9383. * An implementation of a loop for asynchronous functions.
  9384. */
  9385. var AsyncLoop = /** @class */ (function () {
  9386. /**
  9387. * Constroctor.
  9388. * @param iterations the number of iterations.
  9389. * @param _fn the function to run each iteration
  9390. * @param _successCallback the callback that will be called upon succesful execution
  9391. * @param offset starting offset.
  9392. */
  9393. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9394. if (offset === void 0) { offset = 0; }
  9395. this.iterations = iterations;
  9396. this._fn = _fn;
  9397. this._successCallback = _successCallback;
  9398. this.index = offset - 1;
  9399. this._done = false;
  9400. }
  9401. /**
  9402. * Execute the next iteration. Must be called after the last iteration was finished.
  9403. */
  9404. AsyncLoop.prototype.executeNext = function () {
  9405. if (!this._done) {
  9406. if (this.index + 1 < this.iterations) {
  9407. ++this.index;
  9408. this._fn(this);
  9409. }
  9410. else {
  9411. this.breakLoop();
  9412. }
  9413. }
  9414. };
  9415. /**
  9416. * Break the loop and run the success callback.
  9417. */
  9418. AsyncLoop.prototype.breakLoop = function () {
  9419. this._done = true;
  9420. this._successCallback();
  9421. };
  9422. /**
  9423. * Helper function
  9424. */
  9425. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9426. if (offset === void 0) { offset = 0; }
  9427. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9428. loop.executeNext();
  9429. return loop;
  9430. };
  9431. /**
  9432. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9433. * @param iterations total number of iterations
  9434. * @param syncedIterations number of synchronous iterations in each async iteration.
  9435. * @param fn the function to call each iteration.
  9436. * @param callback a success call back that will be called when iterating stops.
  9437. * @param breakFunction a break condition (optional)
  9438. * @param timeout timeout settings for the setTimeout function. default - 0.
  9439. * @constructor
  9440. */
  9441. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9442. if (timeout === void 0) { timeout = 0; }
  9443. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9444. if (breakFunction && breakFunction())
  9445. loop.breakLoop();
  9446. else {
  9447. setTimeout(function () {
  9448. for (var i = 0; i < syncedIterations; ++i) {
  9449. var iteration = (loop.index * syncedIterations) + i;
  9450. if (iteration >= iterations)
  9451. break;
  9452. fn(iteration);
  9453. if (breakFunction && breakFunction()) {
  9454. loop.breakLoop();
  9455. break;
  9456. }
  9457. }
  9458. loop.executeNext();
  9459. }, timeout);
  9460. }
  9461. }, callback);
  9462. };
  9463. return AsyncLoop;
  9464. }());
  9465. BABYLON.AsyncLoop = AsyncLoop;
  9466. })(BABYLON || (BABYLON = {}));
  9467. //# sourceMappingURL=babylon.tools.js.map
  9468. "use strict";
  9469. var BABYLON;
  9470. (function (BABYLON) {
  9471. var PromiseStates;
  9472. (function (PromiseStates) {
  9473. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9474. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9475. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9476. })(PromiseStates || (PromiseStates = {}));
  9477. var FulFillmentAgregator = /** @class */ (function () {
  9478. function FulFillmentAgregator() {
  9479. this.count = 0;
  9480. this.target = 0;
  9481. this.results = [];
  9482. }
  9483. return FulFillmentAgregator;
  9484. }());
  9485. var InternalPromise = /** @class */ (function () {
  9486. function InternalPromise(resolver) {
  9487. var _this = this;
  9488. this._state = PromiseStates.Pending;
  9489. this._children = new Array();
  9490. this._rejectWasConsumed = false;
  9491. if (!resolver) {
  9492. return;
  9493. }
  9494. try {
  9495. resolver(function (value) {
  9496. _this._resolve(value);
  9497. }, function (reason) {
  9498. _this._reject(reason);
  9499. });
  9500. }
  9501. catch (e) {
  9502. this._reject(e);
  9503. }
  9504. }
  9505. InternalPromise.prototype.catch = function (onRejected) {
  9506. return this.then(undefined, onRejected);
  9507. };
  9508. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9509. var _this = this;
  9510. var newPromise = new InternalPromise();
  9511. newPromise._onFulfilled = onFulfilled;
  9512. newPromise._onRejected = onRejected;
  9513. // Composition
  9514. this._children.push(newPromise);
  9515. if (this._state !== PromiseStates.Pending) {
  9516. BABYLON.Tools.SetImmediate(function () {
  9517. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9518. var returnedValue = newPromise._resolve(_this._result);
  9519. if (returnedValue !== undefined && returnedValue !== null) {
  9520. if (returnedValue._state !== undefined) {
  9521. var returnedPromise = returnedValue;
  9522. newPromise._children.push(returnedPromise);
  9523. newPromise = returnedPromise;
  9524. }
  9525. else {
  9526. newPromise._result = returnedValue;
  9527. }
  9528. }
  9529. }
  9530. else {
  9531. newPromise._reject(_this._reason);
  9532. }
  9533. });
  9534. }
  9535. return newPromise;
  9536. };
  9537. InternalPromise.prototype._moveChildren = function (children) {
  9538. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9539. if (this._state === PromiseStates.Fulfilled) {
  9540. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9541. var child = _b[_i];
  9542. child._resolve(this._result);
  9543. }
  9544. }
  9545. else if (this._state === PromiseStates.Rejected) {
  9546. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9547. var child = _d[_c];
  9548. child._reject(this._reason);
  9549. }
  9550. }
  9551. var _a;
  9552. };
  9553. InternalPromise.prototype._resolve = function (value) {
  9554. try {
  9555. this._state = PromiseStates.Fulfilled;
  9556. var returnedValue = null;
  9557. if (this._onFulfilled) {
  9558. returnedValue = this._onFulfilled(value);
  9559. }
  9560. if (returnedValue !== undefined && returnedValue !== null) {
  9561. if (returnedValue._state !== undefined) {
  9562. // Transmit children
  9563. var returnedPromise = returnedValue;
  9564. returnedPromise._moveChildren(this._children);
  9565. value = returnedPromise._result;
  9566. }
  9567. else {
  9568. value = returnedValue;
  9569. }
  9570. }
  9571. this._result = value;
  9572. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9573. var child = _a[_i];
  9574. child._resolve(value);
  9575. }
  9576. this._children.length = 0;
  9577. delete this._onFulfilled;
  9578. delete this._onRejected;
  9579. }
  9580. catch (e) {
  9581. this._reject(e, true);
  9582. }
  9583. };
  9584. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9585. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9586. this._state = PromiseStates.Rejected;
  9587. this._reason = reason;
  9588. if (this._onRejected && !onLocalThrow) {
  9589. try {
  9590. this._onRejected(reason);
  9591. this._rejectWasConsumed = true;
  9592. }
  9593. catch (e) {
  9594. reason = e;
  9595. }
  9596. }
  9597. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9598. var child = _a[_i];
  9599. if (this._rejectWasConsumed) {
  9600. child._resolve(null);
  9601. }
  9602. else {
  9603. child._reject(reason);
  9604. }
  9605. }
  9606. this._children.length = 0;
  9607. delete this._onFulfilled;
  9608. delete this._onRejected;
  9609. };
  9610. InternalPromise.resolve = function (value) {
  9611. var newPromise = new InternalPromise();
  9612. newPromise._resolve(value);
  9613. return newPromise;
  9614. };
  9615. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9616. promise.then(function (value) {
  9617. agregator.results[index] = value;
  9618. agregator.count++;
  9619. if (agregator.count === agregator.target) {
  9620. agregator.rootPromise._resolve(agregator.results);
  9621. }
  9622. return null;
  9623. }, function (reason) {
  9624. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9625. agregator.rootPromise._reject(reason);
  9626. }
  9627. });
  9628. };
  9629. InternalPromise.all = function (promises) {
  9630. var newPromise = new InternalPromise();
  9631. var agregator = new FulFillmentAgregator();
  9632. agregator.target = promises.length;
  9633. agregator.rootPromise = newPromise;
  9634. if (promises.length) {
  9635. for (var index = 0; index < promises.length; index++) {
  9636. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9637. }
  9638. }
  9639. else {
  9640. newPromise._resolve([]);
  9641. }
  9642. return newPromise;
  9643. };
  9644. InternalPromise.race = function (promises) {
  9645. var newPromise = new InternalPromise();
  9646. if (promises.length) {
  9647. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9648. var promise = promises_1[_i];
  9649. promise.then(function (value) {
  9650. if (newPromise) {
  9651. newPromise._resolve(value);
  9652. newPromise = null;
  9653. }
  9654. return null;
  9655. }, function (reason) {
  9656. if (newPromise) {
  9657. newPromise._reject(reason);
  9658. newPromise = null;
  9659. }
  9660. });
  9661. }
  9662. }
  9663. return newPromise;
  9664. };
  9665. return InternalPromise;
  9666. }());
  9667. /**
  9668. * Helper class that provides a small promise polyfill
  9669. */
  9670. var PromisePolyfill = /** @class */ (function () {
  9671. function PromisePolyfill() {
  9672. }
  9673. /**
  9674. * Static function used to check if the polyfill is required
  9675. * If this is the case then the function will inject the polyfill to window.Promise
  9676. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9677. */
  9678. PromisePolyfill.Apply = function (force) {
  9679. if (force === void 0) { force = false; }
  9680. if (force || typeof Promise === 'undefined') {
  9681. var root = window;
  9682. root.Promise = InternalPromise;
  9683. }
  9684. };
  9685. return PromisePolyfill;
  9686. }());
  9687. BABYLON.PromisePolyfill = PromisePolyfill;
  9688. })(BABYLON || (BABYLON = {}));
  9689. //# sourceMappingURL=babylon.promise.js.map
  9690. "use strict";
  9691. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9692. var BABYLON;
  9693. (function (BABYLON) {
  9694. /**
  9695. * Helper class to push actions to a pool of workers.
  9696. */
  9697. var WorkerPool = /** @class */ (function () {
  9698. /**
  9699. * Constructor
  9700. * @param workers Array of workers to use for actions
  9701. */
  9702. function WorkerPool(workers) {
  9703. this._pendingActions = new Array();
  9704. this._workerInfos = workers.map(function (worker) { return ({
  9705. worker: worker,
  9706. active: false
  9707. }); });
  9708. }
  9709. /**
  9710. * Terminates all workers and clears any pending actions.
  9711. */
  9712. WorkerPool.prototype.dispose = function () {
  9713. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9714. var workerInfo = _a[_i];
  9715. workerInfo.worker.terminate();
  9716. }
  9717. delete this._workerInfos;
  9718. delete this._pendingActions;
  9719. };
  9720. /**
  9721. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9722. * pended until a worker has completed its action.
  9723. * @param action The action to perform. Call onComplete when the action is complete.
  9724. */
  9725. WorkerPool.prototype.push = function (action) {
  9726. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9727. var workerInfo = _a[_i];
  9728. if (!workerInfo.active) {
  9729. this._execute(workerInfo, action);
  9730. return;
  9731. }
  9732. }
  9733. this._pendingActions.push(action);
  9734. };
  9735. WorkerPool.prototype._execute = function (workerInfo, action) {
  9736. var _this = this;
  9737. workerInfo.active = true;
  9738. action(workerInfo.worker, function () {
  9739. workerInfo.active = false;
  9740. var nextAction = _this._pendingActions.shift();
  9741. if (nextAction) {
  9742. _this._execute(workerInfo, nextAction);
  9743. }
  9744. });
  9745. };
  9746. return WorkerPool;
  9747. }());
  9748. BABYLON.WorkerPool = WorkerPool;
  9749. })(BABYLON || (BABYLON = {}));
  9750. //# sourceMappingURL=babylon.workerPool.js.map
  9751. "use strict";
  9752. var BABYLON;
  9753. (function (BABYLON) {
  9754. var _AlphaState = /** @class */ (function () {
  9755. /**
  9756. * Initializes the state.
  9757. */
  9758. function _AlphaState() {
  9759. this._isAlphaBlendDirty = false;
  9760. this._isBlendFunctionParametersDirty = false;
  9761. this._isBlendEquationParametersDirty = false;
  9762. this._isBlendConstantsDirty = false;
  9763. this._alphaBlend = false;
  9764. this._blendFunctionParameters = new Array(4);
  9765. this._blendEquationParameters = new Array(2);
  9766. this._blendConstants = new Array(4);
  9767. this.reset();
  9768. }
  9769. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9770. get: function () {
  9771. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9772. },
  9773. enumerable: true,
  9774. configurable: true
  9775. });
  9776. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9777. get: function () {
  9778. return this._alphaBlend;
  9779. },
  9780. set: function (value) {
  9781. if (this._alphaBlend === value) {
  9782. return;
  9783. }
  9784. this._alphaBlend = value;
  9785. this._isAlphaBlendDirty = true;
  9786. },
  9787. enumerable: true,
  9788. configurable: true
  9789. });
  9790. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9791. if (this._blendConstants[0] === r &&
  9792. this._blendConstants[1] === g &&
  9793. this._blendConstants[2] === b &&
  9794. this._blendConstants[3] === a) {
  9795. return;
  9796. }
  9797. this._blendConstants[0] = r;
  9798. this._blendConstants[1] = g;
  9799. this._blendConstants[2] = b;
  9800. this._blendConstants[3] = a;
  9801. this._isBlendConstantsDirty = true;
  9802. };
  9803. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9804. if (this._blendFunctionParameters[0] === value0 &&
  9805. this._blendFunctionParameters[1] === value1 &&
  9806. this._blendFunctionParameters[2] === value2 &&
  9807. this._blendFunctionParameters[3] === value3) {
  9808. return;
  9809. }
  9810. this._blendFunctionParameters[0] = value0;
  9811. this._blendFunctionParameters[1] = value1;
  9812. this._blendFunctionParameters[2] = value2;
  9813. this._blendFunctionParameters[3] = value3;
  9814. this._isBlendFunctionParametersDirty = true;
  9815. };
  9816. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9817. if (this._blendEquationParameters[0] === rgb &&
  9818. this._blendEquationParameters[1] === alpha) {
  9819. return;
  9820. }
  9821. this._blendEquationParameters[0] = rgb;
  9822. this._blendEquationParameters[1] = alpha;
  9823. this._isBlendEquationParametersDirty = true;
  9824. };
  9825. _AlphaState.prototype.reset = function () {
  9826. this._alphaBlend = false;
  9827. this._blendFunctionParameters[0] = null;
  9828. this._blendFunctionParameters[1] = null;
  9829. this._blendFunctionParameters[2] = null;
  9830. this._blendFunctionParameters[3] = null;
  9831. this._blendEquationParameters[0] = null;
  9832. this._blendEquationParameters[1] = null;
  9833. this._blendConstants[0] = null;
  9834. this._blendConstants[1] = null;
  9835. this._blendConstants[2] = null;
  9836. this._blendConstants[3] = null;
  9837. this._isAlphaBlendDirty = true;
  9838. this._isBlendFunctionParametersDirty = false;
  9839. this._isBlendEquationParametersDirty = false;
  9840. this._isBlendConstantsDirty = false;
  9841. };
  9842. _AlphaState.prototype.apply = function (gl) {
  9843. if (!this.isDirty) {
  9844. return;
  9845. }
  9846. // Alpha blend
  9847. if (this._isAlphaBlendDirty) {
  9848. if (this._alphaBlend) {
  9849. gl.enable(gl.BLEND);
  9850. }
  9851. else {
  9852. gl.disable(gl.BLEND);
  9853. }
  9854. this._isAlphaBlendDirty = false;
  9855. }
  9856. // Alpha function
  9857. if (this._isBlendFunctionParametersDirty) {
  9858. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9859. this._isBlendFunctionParametersDirty = false;
  9860. }
  9861. // Alpha equation
  9862. if (this._isBlendEquationParametersDirty) {
  9863. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9864. this._isBlendEquationParametersDirty = false;
  9865. }
  9866. // Constants
  9867. if (this._isBlendConstantsDirty) {
  9868. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9869. this._isBlendConstantsDirty = false;
  9870. }
  9871. };
  9872. return _AlphaState;
  9873. }());
  9874. BABYLON._AlphaState = _AlphaState;
  9875. })(BABYLON || (BABYLON = {}));
  9876. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9877. "use strict";
  9878. var BABYLON;
  9879. (function (BABYLON) {
  9880. var _DepthCullingState = /** @class */ (function () {
  9881. /**
  9882. * Initializes the state.
  9883. */
  9884. function _DepthCullingState() {
  9885. this._isDepthTestDirty = false;
  9886. this._isDepthMaskDirty = false;
  9887. this._isDepthFuncDirty = false;
  9888. this._isCullFaceDirty = false;
  9889. this._isCullDirty = false;
  9890. this._isZOffsetDirty = false;
  9891. this._isFrontFaceDirty = false;
  9892. this.reset();
  9893. }
  9894. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9895. get: function () {
  9896. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9897. },
  9898. enumerable: true,
  9899. configurable: true
  9900. });
  9901. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9902. get: function () {
  9903. return this._zOffset;
  9904. },
  9905. set: function (value) {
  9906. if (this._zOffset === value) {
  9907. return;
  9908. }
  9909. this._zOffset = value;
  9910. this._isZOffsetDirty = true;
  9911. },
  9912. enumerable: true,
  9913. configurable: true
  9914. });
  9915. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9916. get: function () {
  9917. return this._cullFace;
  9918. },
  9919. set: function (value) {
  9920. if (this._cullFace === value) {
  9921. return;
  9922. }
  9923. this._cullFace = value;
  9924. this._isCullFaceDirty = true;
  9925. },
  9926. enumerable: true,
  9927. configurable: true
  9928. });
  9929. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9930. get: function () {
  9931. return this._cull;
  9932. },
  9933. set: function (value) {
  9934. if (this._cull === value) {
  9935. return;
  9936. }
  9937. this._cull = value;
  9938. this._isCullDirty = true;
  9939. },
  9940. enumerable: true,
  9941. configurable: true
  9942. });
  9943. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9944. get: function () {
  9945. return this._depthFunc;
  9946. },
  9947. set: function (value) {
  9948. if (this._depthFunc === value) {
  9949. return;
  9950. }
  9951. this._depthFunc = value;
  9952. this._isDepthFuncDirty = true;
  9953. },
  9954. enumerable: true,
  9955. configurable: true
  9956. });
  9957. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9958. get: function () {
  9959. return this._depthMask;
  9960. },
  9961. set: function (value) {
  9962. if (this._depthMask === value) {
  9963. return;
  9964. }
  9965. this._depthMask = value;
  9966. this._isDepthMaskDirty = true;
  9967. },
  9968. enumerable: true,
  9969. configurable: true
  9970. });
  9971. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9972. get: function () {
  9973. return this._depthTest;
  9974. },
  9975. set: function (value) {
  9976. if (this._depthTest === value) {
  9977. return;
  9978. }
  9979. this._depthTest = value;
  9980. this._isDepthTestDirty = true;
  9981. },
  9982. enumerable: true,
  9983. configurable: true
  9984. });
  9985. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9986. get: function () {
  9987. return this._frontFace;
  9988. },
  9989. set: function (value) {
  9990. if (this._frontFace === value) {
  9991. return;
  9992. }
  9993. this._frontFace = value;
  9994. this._isFrontFaceDirty = true;
  9995. },
  9996. enumerable: true,
  9997. configurable: true
  9998. });
  9999. _DepthCullingState.prototype.reset = function () {
  10000. this._depthMask = true;
  10001. this._depthTest = true;
  10002. this._depthFunc = null;
  10003. this._cullFace = null;
  10004. this._cull = null;
  10005. this._zOffset = 0;
  10006. this._frontFace = null;
  10007. this._isDepthTestDirty = true;
  10008. this._isDepthMaskDirty = true;
  10009. this._isDepthFuncDirty = false;
  10010. this._isCullFaceDirty = false;
  10011. this._isCullDirty = false;
  10012. this._isZOffsetDirty = false;
  10013. this._isFrontFaceDirty = false;
  10014. };
  10015. _DepthCullingState.prototype.apply = function (gl) {
  10016. if (!this.isDirty) {
  10017. return;
  10018. }
  10019. // Cull
  10020. if (this._isCullDirty) {
  10021. if (this.cull) {
  10022. gl.enable(gl.CULL_FACE);
  10023. }
  10024. else {
  10025. gl.disable(gl.CULL_FACE);
  10026. }
  10027. this._isCullDirty = false;
  10028. }
  10029. // Cull face
  10030. if (this._isCullFaceDirty) {
  10031. gl.cullFace(this.cullFace);
  10032. this._isCullFaceDirty = false;
  10033. }
  10034. // Depth mask
  10035. if (this._isDepthMaskDirty) {
  10036. gl.depthMask(this.depthMask);
  10037. this._isDepthMaskDirty = false;
  10038. }
  10039. // Depth test
  10040. if (this._isDepthTestDirty) {
  10041. if (this.depthTest) {
  10042. gl.enable(gl.DEPTH_TEST);
  10043. }
  10044. else {
  10045. gl.disable(gl.DEPTH_TEST);
  10046. }
  10047. this._isDepthTestDirty = false;
  10048. }
  10049. // Depth func
  10050. if (this._isDepthFuncDirty) {
  10051. gl.depthFunc(this.depthFunc);
  10052. this._isDepthFuncDirty = false;
  10053. }
  10054. // zOffset
  10055. if (this._isZOffsetDirty) {
  10056. if (this.zOffset) {
  10057. gl.enable(gl.POLYGON_OFFSET_FILL);
  10058. gl.polygonOffset(this.zOffset, 0);
  10059. }
  10060. else {
  10061. gl.disable(gl.POLYGON_OFFSET_FILL);
  10062. }
  10063. this._isZOffsetDirty = false;
  10064. }
  10065. // Front face
  10066. if (this._isFrontFaceDirty) {
  10067. gl.frontFace(this.frontFace);
  10068. this._isFrontFaceDirty = false;
  10069. }
  10070. };
  10071. return _DepthCullingState;
  10072. }());
  10073. BABYLON._DepthCullingState = _DepthCullingState;
  10074. })(BABYLON || (BABYLON = {}));
  10075. //# sourceMappingURL=babylon.depthCullingState.js.map
  10076. "use strict";
  10077. var BABYLON;
  10078. (function (BABYLON) {
  10079. var _StencilState = /** @class */ (function () {
  10080. function _StencilState() {
  10081. this._isStencilTestDirty = false;
  10082. this._isStencilMaskDirty = false;
  10083. this._isStencilFuncDirty = false;
  10084. this._isStencilOpDirty = false;
  10085. this.reset();
  10086. }
  10087. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10088. get: function () {
  10089. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10090. },
  10091. enumerable: true,
  10092. configurable: true
  10093. });
  10094. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10095. get: function () {
  10096. return this._stencilFunc;
  10097. },
  10098. set: function (value) {
  10099. if (this._stencilFunc === value) {
  10100. return;
  10101. }
  10102. this._stencilFunc = value;
  10103. this._isStencilFuncDirty = true;
  10104. },
  10105. enumerable: true,
  10106. configurable: true
  10107. });
  10108. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10109. get: function () {
  10110. return this._stencilFuncRef;
  10111. },
  10112. set: function (value) {
  10113. if (this._stencilFuncRef === value) {
  10114. return;
  10115. }
  10116. this._stencilFuncRef = value;
  10117. this._isStencilFuncDirty = true;
  10118. },
  10119. enumerable: true,
  10120. configurable: true
  10121. });
  10122. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10123. get: function () {
  10124. return this._stencilFuncMask;
  10125. },
  10126. set: function (value) {
  10127. if (this._stencilFuncMask === value) {
  10128. return;
  10129. }
  10130. this._stencilFuncMask = value;
  10131. this._isStencilFuncDirty = true;
  10132. },
  10133. enumerable: true,
  10134. configurable: true
  10135. });
  10136. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10137. get: function () {
  10138. return this._stencilOpStencilFail;
  10139. },
  10140. set: function (value) {
  10141. if (this._stencilOpStencilFail === value) {
  10142. return;
  10143. }
  10144. this._stencilOpStencilFail = value;
  10145. this._isStencilOpDirty = true;
  10146. },
  10147. enumerable: true,
  10148. configurable: true
  10149. });
  10150. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10151. get: function () {
  10152. return this._stencilOpDepthFail;
  10153. },
  10154. set: function (value) {
  10155. if (this._stencilOpDepthFail === value) {
  10156. return;
  10157. }
  10158. this._stencilOpDepthFail = value;
  10159. this._isStencilOpDirty = true;
  10160. },
  10161. enumerable: true,
  10162. configurable: true
  10163. });
  10164. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10165. get: function () {
  10166. return this._stencilOpStencilDepthPass;
  10167. },
  10168. set: function (value) {
  10169. if (this._stencilOpStencilDepthPass === value) {
  10170. return;
  10171. }
  10172. this._stencilOpStencilDepthPass = value;
  10173. this._isStencilOpDirty = true;
  10174. },
  10175. enumerable: true,
  10176. configurable: true
  10177. });
  10178. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10179. get: function () {
  10180. return this._stencilMask;
  10181. },
  10182. set: function (value) {
  10183. if (this._stencilMask === value) {
  10184. return;
  10185. }
  10186. this._stencilMask = value;
  10187. this._isStencilMaskDirty = true;
  10188. },
  10189. enumerable: true,
  10190. configurable: true
  10191. });
  10192. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10193. get: function () {
  10194. return this._stencilTest;
  10195. },
  10196. set: function (value) {
  10197. if (this._stencilTest === value) {
  10198. return;
  10199. }
  10200. this._stencilTest = value;
  10201. this._isStencilTestDirty = true;
  10202. },
  10203. enumerable: true,
  10204. configurable: true
  10205. });
  10206. _StencilState.prototype.reset = function () {
  10207. this._stencilTest = false;
  10208. this._stencilMask = 0xFF;
  10209. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10210. this._stencilFuncRef = 1;
  10211. this._stencilFuncMask = 0xFF;
  10212. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10213. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10214. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10215. this._isStencilTestDirty = true;
  10216. this._isStencilMaskDirty = true;
  10217. this._isStencilFuncDirty = true;
  10218. this._isStencilOpDirty = true;
  10219. };
  10220. _StencilState.prototype.apply = function (gl) {
  10221. if (!this.isDirty) {
  10222. return;
  10223. }
  10224. // Stencil test
  10225. if (this._isStencilTestDirty) {
  10226. if (this.stencilTest) {
  10227. gl.enable(gl.STENCIL_TEST);
  10228. }
  10229. else {
  10230. gl.disable(gl.STENCIL_TEST);
  10231. }
  10232. this._isStencilTestDirty = false;
  10233. }
  10234. // Stencil mask
  10235. if (this._isStencilMaskDirty) {
  10236. gl.stencilMask(this.stencilMask);
  10237. this._isStencilMaskDirty = false;
  10238. }
  10239. // Stencil func
  10240. if (this._isStencilFuncDirty) {
  10241. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10242. this._isStencilFuncDirty = false;
  10243. }
  10244. // Stencil op
  10245. if (this._isStencilOpDirty) {
  10246. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10247. this._isStencilOpDirty = false;
  10248. }
  10249. };
  10250. return _StencilState;
  10251. }());
  10252. BABYLON._StencilState = _StencilState;
  10253. })(BABYLON || (BABYLON = {}));
  10254. //# sourceMappingURL=babylon.stencilState.js.map
  10255. "use strict";
  10256. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10257. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10258. s = arguments[i];
  10259. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10260. t[p] = s[p];
  10261. }
  10262. return t;
  10263. };
  10264. var BABYLON;
  10265. (function (BABYLON) {
  10266. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10267. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10268. };
  10269. var compileRawShader = function (gl, source, type) {
  10270. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10271. gl.shaderSource(shader, source);
  10272. gl.compileShader(shader);
  10273. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10274. var log = gl.getShaderInfoLog(shader);
  10275. if (log) {
  10276. throw new Error(log);
  10277. }
  10278. }
  10279. if (!shader) {
  10280. throw new Error("Something went wrong while compile the shader.");
  10281. }
  10282. return shader;
  10283. };
  10284. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10285. var magFilter = gl.NEAREST;
  10286. var minFilter = gl.NEAREST;
  10287. switch (samplingMode) {
  10288. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10289. magFilter = gl.LINEAR;
  10290. if (generateMipMaps) {
  10291. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10292. }
  10293. else {
  10294. minFilter = gl.LINEAR;
  10295. }
  10296. break;
  10297. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10298. magFilter = gl.LINEAR;
  10299. if (generateMipMaps) {
  10300. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10301. }
  10302. else {
  10303. minFilter = gl.LINEAR;
  10304. }
  10305. break;
  10306. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10307. magFilter = gl.NEAREST;
  10308. if (generateMipMaps) {
  10309. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10310. }
  10311. else {
  10312. minFilter = gl.NEAREST;
  10313. }
  10314. break;
  10315. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10316. magFilter = gl.NEAREST;
  10317. if (generateMipMaps) {
  10318. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10319. }
  10320. else {
  10321. minFilter = gl.NEAREST;
  10322. }
  10323. break;
  10324. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10325. magFilter = gl.NEAREST;
  10326. if (generateMipMaps) {
  10327. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10328. }
  10329. else {
  10330. minFilter = gl.LINEAR;
  10331. }
  10332. break;
  10333. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10334. magFilter = gl.NEAREST;
  10335. if (generateMipMaps) {
  10336. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10337. }
  10338. else {
  10339. minFilter = gl.LINEAR;
  10340. }
  10341. break;
  10342. case BABYLON.Texture.NEAREST_LINEAR:
  10343. magFilter = gl.NEAREST;
  10344. minFilter = gl.LINEAR;
  10345. break;
  10346. case BABYLON.Texture.NEAREST_NEAREST:
  10347. magFilter = gl.NEAREST;
  10348. minFilter = gl.NEAREST;
  10349. break;
  10350. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10351. magFilter = gl.LINEAR;
  10352. if (generateMipMaps) {
  10353. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10354. }
  10355. else {
  10356. minFilter = gl.NEAREST;
  10357. }
  10358. break;
  10359. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10360. magFilter = gl.LINEAR;
  10361. if (generateMipMaps) {
  10362. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10363. }
  10364. else {
  10365. minFilter = gl.NEAREST;
  10366. }
  10367. break;
  10368. case BABYLON.Texture.LINEAR_LINEAR:
  10369. magFilter = gl.LINEAR;
  10370. minFilter = gl.LINEAR;
  10371. break;
  10372. case BABYLON.Texture.LINEAR_NEAREST:
  10373. magFilter = gl.LINEAR;
  10374. minFilter = gl.NEAREST;
  10375. break;
  10376. }
  10377. return {
  10378. min: minFilter,
  10379. mag: magFilter
  10380. };
  10381. };
  10382. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10383. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10384. var img;
  10385. var onload = function () {
  10386. loadedImages[index] = img;
  10387. loadedImages._internalCount++;
  10388. if (scene) {
  10389. scene._removePendingData(img);
  10390. }
  10391. if (loadedImages._internalCount === 6) {
  10392. onfinish(loadedImages);
  10393. }
  10394. };
  10395. var onerror = function (message, exception) {
  10396. if (scene) {
  10397. scene._removePendingData(img);
  10398. }
  10399. if (onErrorCallBack) {
  10400. onErrorCallBack(message, exception);
  10401. }
  10402. };
  10403. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10404. if (scene) {
  10405. scene._addPendingData(img);
  10406. }
  10407. };
  10408. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10409. if (onError === void 0) { onError = null; }
  10410. var loadedImages = [];
  10411. loadedImages._internalCount = 0;
  10412. for (var index = 0; index < 6; index++) {
  10413. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10414. }
  10415. };
  10416. var BufferPointer = /** @class */ (function () {
  10417. function BufferPointer() {
  10418. }
  10419. return BufferPointer;
  10420. }());
  10421. var InstancingAttributeInfo = /** @class */ (function () {
  10422. function InstancingAttributeInfo() {
  10423. }
  10424. return InstancingAttributeInfo;
  10425. }());
  10426. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10427. /**
  10428. * Define options used to create a render target texture
  10429. */
  10430. var RenderTargetCreationOptions = /** @class */ (function () {
  10431. function RenderTargetCreationOptions() {
  10432. }
  10433. return RenderTargetCreationOptions;
  10434. }());
  10435. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10436. /**
  10437. * Define options used to create a depth texture
  10438. */
  10439. var DepthTextureCreationOptions = /** @class */ (function () {
  10440. function DepthTextureCreationOptions() {
  10441. }
  10442. return DepthTextureCreationOptions;
  10443. }());
  10444. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10445. /**
  10446. * Regroup several parameters relative to the browser in use
  10447. */
  10448. var EngineCapabilities = /** @class */ (function () {
  10449. function EngineCapabilities() {
  10450. }
  10451. return EngineCapabilities;
  10452. }());
  10453. BABYLON.EngineCapabilities = EngineCapabilities;
  10454. /**
  10455. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10456. */
  10457. var Engine = /** @class */ (function () {
  10458. /**
  10459. * @constructor
  10460. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10461. * @param antialias defines enable antialiasing (default: false)
  10462. * @param options defines further options to be sent to the getContext() function
  10463. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10464. */
  10465. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10466. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10467. var _this = this;
  10468. // Public members
  10469. this.forcePOTTextures = false;
  10470. this.isFullscreen = false;
  10471. this.isPointerLock = false;
  10472. this.cullBackFaces = true;
  10473. this.renderEvenInBackground = true;
  10474. this.preventCacheWipeBetweenFrames = false;
  10475. /**
  10476. * To enable/disable IDB support and avoid XHR on .manifest
  10477. **/
  10478. this.enableOfflineSupport = false;
  10479. this.scenes = new Array();
  10480. this.postProcesses = new Array();
  10481. // Observables
  10482. /**
  10483. * Observable event triggered each time the rendering canvas is resized
  10484. */
  10485. this.onResizeObservable = new BABYLON.Observable();
  10486. /**
  10487. * Observable event triggered each time the canvas loses focus
  10488. */
  10489. this.onCanvasBlurObservable = new BABYLON.Observable();
  10490. /**
  10491. * Observable event triggered each time the canvas gains focus
  10492. */
  10493. this.onCanvasFocusObservable = new BABYLON.Observable();
  10494. /**
  10495. * Observable event triggered each time the canvas receives pointerout event
  10496. */
  10497. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10498. /**
  10499. * Observable event triggered before each texture is initialized
  10500. */
  10501. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10502. //WebVR
  10503. this._vrDisplay = undefined;
  10504. this._vrSupported = false;
  10505. this._vrExclusivePointerMode = false;
  10506. // Uniform buffers list
  10507. this.disableUniformBuffers = false;
  10508. this._uniformBuffers = new Array();
  10509. // Observables
  10510. /**
  10511. * Observable raised when the engine begins a new frame
  10512. */
  10513. this.onBeginFrameObservable = new BABYLON.Observable();
  10514. /**
  10515. * Observable raised when the engine ends the current frame
  10516. */
  10517. this.onEndFrameObservable = new BABYLON.Observable();
  10518. /**
  10519. * Observable raised when the engine is about to compile a shader
  10520. */
  10521. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10522. /**
  10523. * Observable raised when the engine has jsut compiled a shader
  10524. */
  10525. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10526. this._windowIsBackground = false;
  10527. this._webGLVersion = 1.0;
  10528. this._badOS = false;
  10529. this._badDesktopOS = false;
  10530. /**
  10531. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10532. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10533. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10534. */
  10535. this.disableTextureBindingOptimization = false;
  10536. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10537. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10538. this.onVRRequestPresentStart = new BABYLON.Observable();
  10539. this._colorWrite = true;
  10540. this._drawCalls = new BABYLON.PerfCounter();
  10541. this._textureCollisions = new BABYLON.PerfCounter();
  10542. this._renderingQueueLaunched = false;
  10543. this._activeRenderLoops = new Array();
  10544. // Deterministic lockstepMaxSteps
  10545. this._deterministicLockstep = false;
  10546. this._lockstepMaxSteps = 4;
  10547. // Lost context
  10548. this.onContextLostObservable = new BABYLON.Observable();
  10549. this.onContextRestoredObservable = new BABYLON.Observable();
  10550. this._contextWasLost = false;
  10551. this._doNotHandleContextLost = false;
  10552. // FPS
  10553. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10554. this._fps = 60;
  10555. this._deltaTime = 0;
  10556. /**
  10557. * Turn this value on if you want to pause FPS computation when in background
  10558. */
  10559. this.disablePerformanceMonitorInBackground = false;
  10560. // States
  10561. this._depthCullingState = new BABYLON._DepthCullingState();
  10562. this._stencilState = new BABYLON._StencilState();
  10563. this._alphaState = new BABYLON._AlphaState();
  10564. this._alphaMode = Engine.ALPHA_DISABLE;
  10565. // Cache
  10566. this._internalTexturesCache = new Array();
  10567. this._activeChannel = 0;
  10568. this._currentTextureChannel = -1;
  10569. this._boundTexturesCache = {};
  10570. this._compiledEffects = {};
  10571. this._vertexAttribArraysEnabled = [];
  10572. this._uintIndicesCurrentlySet = false;
  10573. this._currentBoundBuffer = new Array();
  10574. this._currentBufferPointers = new Array();
  10575. this._currentInstanceLocations = new Array();
  10576. this._currentInstanceBuffers = new Array();
  10577. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10578. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10579. this._vaoRecordInProgress = false;
  10580. this._mustWipeVertexAttributes = false;
  10581. this._nextFreeTextureSlots = new Array();
  10582. this._maxSimultaneousTextures = 0;
  10583. this._activeRequests = new Array();
  10584. // Hardware supported Compressed Textures
  10585. this._texturesSupported = new Array();
  10586. this._onVRFullScreenTriggered = function () {
  10587. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10588. //get the old size before we change
  10589. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10590. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10591. //get the width and height, change the render size
  10592. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10593. _this.setHardwareScalingLevel(1);
  10594. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10595. }
  10596. else {
  10597. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10598. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10599. }
  10600. };
  10601. this._boundUniforms = {};
  10602. // Register promises
  10603. BABYLON.PromisePolyfill.Apply();
  10604. var canvas = null;
  10605. Engine.Instances.push(this);
  10606. if (!canvasOrContext) {
  10607. return;
  10608. }
  10609. options = options || {};
  10610. if (canvasOrContext.getContext) {
  10611. canvas = canvasOrContext;
  10612. this._renderingCanvas = canvas;
  10613. if (antialias != null) {
  10614. options.antialias = antialias;
  10615. }
  10616. if (options.deterministicLockstep === undefined) {
  10617. options.deterministicLockstep = false;
  10618. }
  10619. if (options.lockstepMaxSteps === undefined) {
  10620. options.lockstepMaxSteps = 4;
  10621. }
  10622. if (options.preserveDrawingBuffer === undefined) {
  10623. options.preserveDrawingBuffer = false;
  10624. }
  10625. if (options.audioEngine === undefined) {
  10626. options.audioEngine = true;
  10627. }
  10628. if (options.stencil === undefined) {
  10629. options.stencil = true;
  10630. }
  10631. this._deterministicLockstep = options.deterministicLockstep;
  10632. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10633. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10634. // Exceptions
  10635. if (navigator && navigator.userAgent) {
  10636. var ua = navigator.userAgent;
  10637. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10638. var exception = _a[_i];
  10639. var key = exception.key;
  10640. var targets = exception.targets;
  10641. if (ua.indexOf(key) > -1) {
  10642. if (exception.capture && exception.captureConstraint) {
  10643. var capture = exception.capture;
  10644. var constraint = exception.captureConstraint;
  10645. var regex = new RegExp(capture);
  10646. var matches = regex.exec(ua);
  10647. if (matches && matches.length > 0) {
  10648. var capturedValue = parseInt(matches[matches.length - 1]);
  10649. if (capturedValue >= constraint) {
  10650. continue;
  10651. }
  10652. }
  10653. }
  10654. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10655. var target = targets_1[_b];
  10656. switch (target) {
  10657. case "uniformBuffer":
  10658. this.disableUniformBuffers = true;
  10659. break;
  10660. case "textureBindingOptimization":
  10661. this.disableTextureBindingOptimization = true;
  10662. break;
  10663. }
  10664. }
  10665. }
  10666. }
  10667. }
  10668. // GL
  10669. if (!options.disableWebGL2Support) {
  10670. try {
  10671. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10672. if (this._gl) {
  10673. this._webGLVersion = 2.0;
  10674. }
  10675. }
  10676. catch (e) {
  10677. // Do nothing
  10678. }
  10679. }
  10680. if (!this._gl) {
  10681. if (!canvas) {
  10682. throw new Error("The provided canvas is null or undefined.");
  10683. }
  10684. try {
  10685. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10686. }
  10687. catch (e) {
  10688. throw new Error("WebGL not supported");
  10689. }
  10690. }
  10691. if (!this._gl) {
  10692. throw new Error("WebGL not supported");
  10693. }
  10694. this._onCanvasFocus = function () {
  10695. _this.onCanvasFocusObservable.notifyObservers(_this);
  10696. };
  10697. this._onCanvasBlur = function () {
  10698. _this.onCanvasBlurObservable.notifyObservers(_this);
  10699. };
  10700. canvas.addEventListener("focus", this._onCanvasFocus);
  10701. canvas.addEventListener("blur", this._onCanvasBlur);
  10702. this._onBlur = function () {
  10703. if (_this.disablePerformanceMonitorInBackground) {
  10704. _this._performanceMonitor.disable();
  10705. }
  10706. _this._windowIsBackground = true;
  10707. };
  10708. this._onFocus = function () {
  10709. if (_this.disablePerformanceMonitorInBackground) {
  10710. _this._performanceMonitor.enable();
  10711. }
  10712. _this._windowIsBackground = false;
  10713. };
  10714. this._onCanvasPointerOut = function (ev) {
  10715. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10716. };
  10717. window.addEventListener("blur", this._onBlur);
  10718. window.addEventListener("focus", this._onFocus);
  10719. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10720. // Context lost
  10721. if (!this._doNotHandleContextLost) {
  10722. this._onContextLost = function (evt) {
  10723. evt.preventDefault();
  10724. _this._contextWasLost = true;
  10725. BABYLON.Tools.Warn("WebGL context lost.");
  10726. _this.onContextLostObservable.notifyObservers(_this);
  10727. };
  10728. this._onContextRestored = function (evt) {
  10729. // Adding a timeout to avoid race condition at browser level
  10730. setTimeout(function () {
  10731. // Rebuild gl context
  10732. _this._initGLContext();
  10733. // Rebuild effects
  10734. _this._rebuildEffects();
  10735. // Rebuild textures
  10736. _this._rebuildInternalTextures();
  10737. // Rebuild buffers
  10738. _this._rebuildBuffers();
  10739. // Cache
  10740. _this.wipeCaches(true);
  10741. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10742. _this.onContextRestoredObservable.notifyObservers(_this);
  10743. _this._contextWasLost = false;
  10744. }, 0);
  10745. };
  10746. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10747. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10748. }
  10749. }
  10750. else {
  10751. this._gl = canvasOrContext;
  10752. this._renderingCanvas = this._gl.canvas;
  10753. if (this._gl.renderbufferStorageMultisample) {
  10754. this._webGLVersion = 2.0;
  10755. }
  10756. options.stencil = this._gl.getContextAttributes().stencil;
  10757. }
  10758. // Viewport
  10759. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10760. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10761. this.resize();
  10762. this._isStencilEnable = options.stencil ? true : false;
  10763. this._initGLContext();
  10764. if (canvas) {
  10765. // Fullscreen
  10766. this._onFullscreenChange = function () {
  10767. if (document.fullscreen !== undefined) {
  10768. _this.isFullscreen = document.fullscreen;
  10769. }
  10770. else if (document.mozFullScreen !== undefined) {
  10771. _this.isFullscreen = document.mozFullScreen;
  10772. }
  10773. else if (document.webkitIsFullScreen !== undefined) {
  10774. _this.isFullscreen = document.webkitIsFullScreen;
  10775. }
  10776. else if (document.msIsFullScreen !== undefined) {
  10777. _this.isFullscreen = document.msIsFullScreen;
  10778. }
  10779. // Pointer lock
  10780. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10781. canvas.requestPointerLock = canvas.requestPointerLock ||
  10782. canvas.msRequestPointerLock ||
  10783. canvas.mozRequestPointerLock ||
  10784. canvas.webkitRequestPointerLock;
  10785. if (canvas.requestPointerLock) {
  10786. canvas.requestPointerLock();
  10787. }
  10788. }
  10789. };
  10790. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10791. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10792. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10793. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10794. // Pointer lock
  10795. this._onPointerLockChange = function () {
  10796. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10797. document.webkitPointerLockElement === canvas ||
  10798. document.msPointerLockElement === canvas ||
  10799. document.pointerLockElement === canvas);
  10800. };
  10801. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10802. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10803. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10804. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10805. this._onVRDisplayPointerRestricted = function () {
  10806. if (canvas) {
  10807. canvas.requestPointerLock();
  10808. }
  10809. };
  10810. this._onVRDisplayPointerUnrestricted = function () {
  10811. document.exitPointerLock();
  10812. };
  10813. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10814. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10815. }
  10816. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10817. Engine.audioEngine = new BABYLON.AudioEngine();
  10818. }
  10819. // Prepare buffer pointers
  10820. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10821. this._currentBufferPointers[i] = new BufferPointer();
  10822. }
  10823. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10824. // Load WebVR Devices
  10825. if (options.autoEnableWebVR) {
  10826. this.initWebVR();
  10827. }
  10828. // Detect if we are running on a faulty buggy OS.
  10829. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10830. // Detect if we are running on a faulty buggy desktop OS.
  10831. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10832. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10833. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10834. }
  10835. Object.defineProperty(Engine, "LastCreatedEngine", {
  10836. get: function () {
  10837. if (Engine.Instances.length === 0) {
  10838. return null;
  10839. }
  10840. return Engine.Instances[Engine.Instances.length - 1];
  10841. },
  10842. enumerable: true,
  10843. configurable: true
  10844. });
  10845. Object.defineProperty(Engine, "LastCreatedScene", {
  10846. get: function () {
  10847. var lastCreatedEngine = Engine.LastCreatedEngine;
  10848. if (!lastCreatedEngine) {
  10849. return null;
  10850. }
  10851. if (lastCreatedEngine.scenes.length === 0) {
  10852. return null;
  10853. }
  10854. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10855. },
  10856. enumerable: true,
  10857. configurable: true
  10858. });
  10859. /**
  10860. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10861. */
  10862. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10863. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10864. var engine = Engine.Instances[engineIndex];
  10865. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10866. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10867. }
  10868. }
  10869. };
  10870. Object.defineProperty(Engine, "NEVER", {
  10871. get: function () {
  10872. return Engine._NEVER;
  10873. },
  10874. enumerable: true,
  10875. configurable: true
  10876. });
  10877. Object.defineProperty(Engine, "ALWAYS", {
  10878. get: function () {
  10879. return Engine._ALWAYS;
  10880. },
  10881. enumerable: true,
  10882. configurable: true
  10883. });
  10884. Object.defineProperty(Engine, "LESS", {
  10885. get: function () {
  10886. return Engine._LESS;
  10887. },
  10888. enumerable: true,
  10889. configurable: true
  10890. });
  10891. Object.defineProperty(Engine, "EQUAL", {
  10892. get: function () {
  10893. return Engine._EQUAL;
  10894. },
  10895. enumerable: true,
  10896. configurable: true
  10897. });
  10898. Object.defineProperty(Engine, "LEQUAL", {
  10899. get: function () {
  10900. return Engine._LEQUAL;
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. Object.defineProperty(Engine, "GREATER", {
  10906. get: function () {
  10907. return Engine._GREATER;
  10908. },
  10909. enumerable: true,
  10910. configurable: true
  10911. });
  10912. Object.defineProperty(Engine, "GEQUAL", {
  10913. get: function () {
  10914. return Engine._GEQUAL;
  10915. },
  10916. enumerable: true,
  10917. configurable: true
  10918. });
  10919. Object.defineProperty(Engine, "NOTEQUAL", {
  10920. get: function () {
  10921. return Engine._NOTEQUAL;
  10922. },
  10923. enumerable: true,
  10924. configurable: true
  10925. });
  10926. Object.defineProperty(Engine, "KEEP", {
  10927. get: function () {
  10928. return Engine._KEEP;
  10929. },
  10930. enumerable: true,
  10931. configurable: true
  10932. });
  10933. Object.defineProperty(Engine, "REPLACE", {
  10934. get: function () {
  10935. return Engine._REPLACE;
  10936. },
  10937. enumerable: true,
  10938. configurable: true
  10939. });
  10940. Object.defineProperty(Engine, "INCR", {
  10941. get: function () {
  10942. return Engine._INCR;
  10943. },
  10944. enumerable: true,
  10945. configurable: true
  10946. });
  10947. Object.defineProperty(Engine, "DECR", {
  10948. get: function () {
  10949. return Engine._DECR;
  10950. },
  10951. enumerable: true,
  10952. configurable: true
  10953. });
  10954. Object.defineProperty(Engine, "INVERT", {
  10955. get: function () {
  10956. return Engine._INVERT;
  10957. },
  10958. enumerable: true,
  10959. configurable: true
  10960. });
  10961. Object.defineProperty(Engine, "INCR_WRAP", {
  10962. get: function () {
  10963. return Engine._INCR_WRAP;
  10964. },
  10965. enumerable: true,
  10966. configurable: true
  10967. });
  10968. Object.defineProperty(Engine, "DECR_WRAP", {
  10969. get: function () {
  10970. return Engine._DECR_WRAP;
  10971. },
  10972. enumerable: true,
  10973. configurable: true
  10974. });
  10975. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10976. get: function () {
  10977. return Engine._ALPHA_DISABLE;
  10978. },
  10979. enumerable: true,
  10980. configurable: true
  10981. });
  10982. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10983. get: function () {
  10984. return Engine._ALPHA_ONEONE;
  10985. },
  10986. enumerable: true,
  10987. configurable: true
  10988. });
  10989. Object.defineProperty(Engine, "ALPHA_ADD", {
  10990. get: function () {
  10991. return Engine._ALPHA_ADD;
  10992. },
  10993. enumerable: true,
  10994. configurable: true
  10995. });
  10996. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10997. get: function () {
  10998. return Engine._ALPHA_COMBINE;
  10999. },
  11000. enumerable: true,
  11001. configurable: true
  11002. });
  11003. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11004. get: function () {
  11005. return Engine._ALPHA_SUBTRACT;
  11006. },
  11007. enumerable: true,
  11008. configurable: true
  11009. });
  11010. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11011. get: function () {
  11012. return Engine._ALPHA_MULTIPLY;
  11013. },
  11014. enumerable: true,
  11015. configurable: true
  11016. });
  11017. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11018. get: function () {
  11019. return Engine._ALPHA_MAXIMIZED;
  11020. },
  11021. enumerable: true,
  11022. configurable: true
  11023. });
  11024. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11025. get: function () {
  11026. return Engine._ALPHA_PREMULTIPLIED;
  11027. },
  11028. enumerable: true,
  11029. configurable: true
  11030. });
  11031. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11032. get: function () {
  11033. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11034. },
  11035. enumerable: true,
  11036. configurable: true
  11037. });
  11038. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11039. get: function () {
  11040. return Engine._ALPHA_INTERPOLATE;
  11041. },
  11042. enumerable: true,
  11043. configurable: true
  11044. });
  11045. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11046. get: function () {
  11047. return Engine._ALPHA_SCREENMODE;
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11053. get: function () {
  11054. return Engine._DELAYLOADSTATE_NONE;
  11055. },
  11056. enumerable: true,
  11057. configurable: true
  11058. });
  11059. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11060. get: function () {
  11061. return Engine._DELAYLOADSTATE_LOADED;
  11062. },
  11063. enumerable: true,
  11064. configurable: true
  11065. });
  11066. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11067. get: function () {
  11068. return Engine._DELAYLOADSTATE_LOADING;
  11069. },
  11070. enumerable: true,
  11071. configurable: true
  11072. });
  11073. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11074. get: function () {
  11075. return Engine._DELAYLOADSTATE_NOTLOADED;
  11076. },
  11077. enumerable: true,
  11078. configurable: true
  11079. });
  11080. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11081. get: function () {
  11082. return Engine._TEXTUREFORMAT_ALPHA;
  11083. },
  11084. enumerable: true,
  11085. configurable: true
  11086. });
  11087. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11088. get: function () {
  11089. return Engine._TEXTUREFORMAT_LUMINANCE;
  11090. },
  11091. enumerable: true,
  11092. configurable: true
  11093. });
  11094. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11095. /**
  11096. * R32F
  11097. */
  11098. get: function () {
  11099. return Engine._TEXTUREFORMAT_R32F;
  11100. },
  11101. enumerable: true,
  11102. configurable: true
  11103. });
  11104. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11105. /**
  11106. * RG32F
  11107. */
  11108. get: function () {
  11109. return Engine._TEXTUREFORMAT_RG32F;
  11110. },
  11111. enumerable: true,
  11112. configurable: true
  11113. });
  11114. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11115. /**
  11116. * RGB32F
  11117. */
  11118. get: function () {
  11119. return Engine._TEXTUREFORMAT_RGB32F;
  11120. },
  11121. enumerable: true,
  11122. configurable: true
  11123. });
  11124. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11125. /**
  11126. * RGBA32F
  11127. */
  11128. get: function () {
  11129. return Engine._TEXTUREFORMAT_RGBA32F;
  11130. },
  11131. enumerable: true,
  11132. configurable: true
  11133. });
  11134. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11135. get: function () {
  11136. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11137. },
  11138. enumerable: true,
  11139. configurable: true
  11140. });
  11141. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11142. get: function () {
  11143. return Engine._TEXTUREFORMAT_RGB;
  11144. },
  11145. enumerable: true,
  11146. configurable: true
  11147. });
  11148. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11149. get: function () {
  11150. return Engine._TEXTUREFORMAT_RGBA;
  11151. },
  11152. enumerable: true,
  11153. configurable: true
  11154. });
  11155. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11156. get: function () {
  11157. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11158. },
  11159. enumerable: true,
  11160. configurable: true
  11161. });
  11162. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11163. get: function () {
  11164. return Engine._TEXTURETYPE_FLOAT;
  11165. },
  11166. enumerable: true,
  11167. configurable: true
  11168. });
  11169. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11170. get: function () {
  11171. return Engine._TEXTURETYPE_HALF_FLOAT;
  11172. },
  11173. enumerable: true,
  11174. configurable: true
  11175. });
  11176. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11177. get: function () {
  11178. return Engine._SCALEMODE_FLOOR;
  11179. },
  11180. enumerable: true,
  11181. configurable: true
  11182. });
  11183. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11184. get: function () {
  11185. return Engine._SCALEMODE_NEAREST;
  11186. },
  11187. enumerable: true,
  11188. configurable: true
  11189. });
  11190. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11191. get: function () {
  11192. return Engine._SCALEMODE_CEILING;
  11193. },
  11194. enumerable: true,
  11195. configurable: true
  11196. });
  11197. Object.defineProperty(Engine, "Version", {
  11198. get: function () {
  11199. return "3.2.0-beta.2";
  11200. },
  11201. enumerable: true,
  11202. configurable: true
  11203. });
  11204. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11205. get: function () {
  11206. return this._vrExclusivePointerMode;
  11207. },
  11208. enumerable: true,
  11209. configurable: true
  11210. });
  11211. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11212. get: function () {
  11213. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11214. },
  11215. enumerable: true,
  11216. configurable: true
  11217. });
  11218. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11219. get: function () {
  11220. return this._webGLVersion < 2 || this.forcePOTTextures;
  11221. },
  11222. enumerable: true,
  11223. configurable: true
  11224. });
  11225. Object.defineProperty(Engine.prototype, "badOS", {
  11226. get: function () {
  11227. return this._badOS;
  11228. },
  11229. enumerable: true,
  11230. configurable: true
  11231. });
  11232. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11233. get: function () {
  11234. return this._badDesktopOS;
  11235. },
  11236. enumerable: true,
  11237. configurable: true
  11238. });
  11239. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11240. get: function () {
  11241. return this._performanceMonitor;
  11242. },
  11243. enumerable: true,
  11244. configurable: true
  11245. });
  11246. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11247. get: function () {
  11248. return this._texturesSupported;
  11249. },
  11250. enumerable: true,
  11251. configurable: true
  11252. });
  11253. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11254. get: function () {
  11255. return this._textureFormatInUse;
  11256. },
  11257. enumerable: true,
  11258. configurable: true
  11259. });
  11260. Object.defineProperty(Engine.prototype, "currentViewport", {
  11261. get: function () {
  11262. return this._cachedViewport;
  11263. },
  11264. enumerable: true,
  11265. configurable: true
  11266. });
  11267. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11268. // Empty texture
  11269. get: function () {
  11270. if (!this._emptyTexture) {
  11271. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11272. }
  11273. return this._emptyTexture;
  11274. },
  11275. enumerable: true,
  11276. configurable: true
  11277. });
  11278. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11279. get: function () {
  11280. if (!this._emptyTexture3D) {
  11281. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11282. }
  11283. return this._emptyTexture3D;
  11284. },
  11285. enumerable: true,
  11286. configurable: true
  11287. });
  11288. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11289. get: function () {
  11290. if (!this._emptyCubeTexture) {
  11291. var faceData = new Uint8Array(4);
  11292. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11293. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11294. }
  11295. return this._emptyCubeTexture;
  11296. },
  11297. enumerable: true,
  11298. configurable: true
  11299. });
  11300. Engine.prototype._rebuildInternalTextures = function () {
  11301. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11302. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11303. var internalTexture = currentState_1[_i];
  11304. internalTexture._rebuild();
  11305. }
  11306. };
  11307. Engine.prototype._rebuildEffects = function () {
  11308. for (var key in this._compiledEffects) {
  11309. var effect = this._compiledEffects[key];
  11310. effect._prepareEffect();
  11311. }
  11312. BABYLON.Effect.ResetCache();
  11313. };
  11314. Engine.prototype._rebuildBuffers = function () {
  11315. // Index / Vertex
  11316. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11317. var scene = _a[_i];
  11318. scene.resetCachedMaterial();
  11319. scene._rebuildGeometries();
  11320. scene._rebuildTextures();
  11321. }
  11322. // Uniforms
  11323. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11324. var uniformBuffer = _c[_b];
  11325. uniformBuffer._rebuild();
  11326. }
  11327. };
  11328. Engine.prototype._initGLContext = function () {
  11329. // Caps
  11330. this._caps = new EngineCapabilities();
  11331. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11332. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11333. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11334. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11335. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11336. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11337. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11338. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11339. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11340. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11341. // Infos
  11342. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11343. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11344. if (rendererInfo != null) {
  11345. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11346. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11347. }
  11348. if (!this._glVendor) {
  11349. this._glVendor = "Unknown vendor";
  11350. }
  11351. if (!this._glRenderer) {
  11352. this._glRenderer = "Unknown renderer";
  11353. }
  11354. // Constants
  11355. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11356. if (this._gl.RGBA16F !== 0x881A) {
  11357. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11358. }
  11359. if (this._gl.RGBA32F !== 0x8814) {
  11360. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11361. }
  11362. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11363. this._gl.DEPTH24_STENCIL8 = 35056;
  11364. }
  11365. // Extensions
  11366. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11367. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11368. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11369. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11370. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11371. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11372. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11373. 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');
  11374. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11375. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11376. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11377. this._caps.highPrecisionShaderSupported = true;
  11378. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11379. if (this._caps.timerQuery) {
  11380. if (this._webGLVersion === 1) {
  11381. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11382. }
  11383. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11384. }
  11385. // Checks if some of the format renders first to allow the use of webgl inspector.
  11386. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11387. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11388. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11389. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11390. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11391. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11392. if (this._webGLVersion > 1) {
  11393. this._gl.HALF_FLOAT_OES = 0x140B;
  11394. }
  11395. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11396. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11397. // Draw buffers
  11398. if (this._webGLVersion > 1) {
  11399. this._caps.drawBuffersExtension = true;
  11400. }
  11401. else {
  11402. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11403. if (drawBuffersExtension !== null) {
  11404. this._caps.drawBuffersExtension = true;
  11405. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11406. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11407. for (var i = 0; i < 16; i++) {
  11408. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11409. }
  11410. }
  11411. else {
  11412. this._caps.drawBuffersExtension = false;
  11413. }
  11414. }
  11415. // Depth Texture
  11416. if (this._webGLVersion > 1) {
  11417. this._caps.depthTextureExtension = true;
  11418. }
  11419. else {
  11420. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11421. if (depthTextureExtension != null) {
  11422. this._caps.depthTextureExtension = true;
  11423. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11424. }
  11425. }
  11426. // Vertex array object
  11427. if (this._webGLVersion > 1) {
  11428. this._caps.vertexArrayObject = true;
  11429. }
  11430. else {
  11431. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11432. if (vertexArrayObjectExtension != null) {
  11433. this._caps.vertexArrayObject = true;
  11434. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11435. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11436. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11437. }
  11438. else {
  11439. this._caps.vertexArrayObject = false;
  11440. }
  11441. }
  11442. // Instances count
  11443. if (this._webGLVersion > 1) {
  11444. this._caps.instancedArrays = true;
  11445. }
  11446. else {
  11447. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11448. if (instanceExtension != null) {
  11449. this._caps.instancedArrays = true;
  11450. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11451. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11452. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11453. }
  11454. else {
  11455. this._caps.instancedArrays = false;
  11456. }
  11457. }
  11458. // Intelligently add supported compressed formats in order to check for.
  11459. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11460. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11461. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11462. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11463. if (this._caps.astc)
  11464. this.texturesSupported.push('-astc.ktx');
  11465. if (this._caps.s3tc)
  11466. this.texturesSupported.push('-dxt.ktx');
  11467. if (this._caps.pvrtc)
  11468. this.texturesSupported.push('-pvrtc.ktx');
  11469. if (this._caps.etc2)
  11470. this.texturesSupported.push('-etc2.ktx');
  11471. if (this._caps.etc1)
  11472. this.texturesSupported.push('-etc1.ktx');
  11473. if (this._gl.getShaderPrecisionFormat) {
  11474. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11475. if (highp) {
  11476. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11477. }
  11478. }
  11479. // Depth buffer
  11480. this.setDepthBuffer(true);
  11481. this.setDepthFunctionToLessOrEqual();
  11482. this.setDepthWrite(true);
  11483. // Texture maps
  11484. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11485. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11486. this._nextFreeTextureSlots.push(slot);
  11487. }
  11488. };
  11489. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11490. get: function () {
  11491. return this._webGLVersion;
  11492. },
  11493. enumerable: true,
  11494. configurable: true
  11495. });
  11496. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11497. /**
  11498. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11499. */
  11500. get: function () {
  11501. return this._isStencilEnable;
  11502. },
  11503. enumerable: true,
  11504. configurable: true
  11505. });
  11506. Engine.prototype._prepareWorkingCanvas = function () {
  11507. if (this._workingCanvas) {
  11508. return;
  11509. }
  11510. this._workingCanvas = document.createElement("canvas");
  11511. var context = this._workingCanvas.getContext("2d");
  11512. if (context) {
  11513. this._workingContext = context;
  11514. }
  11515. };
  11516. Engine.prototype.resetTextureCache = function () {
  11517. for (var key in this._boundTexturesCache) {
  11518. var boundTexture = this._boundTexturesCache[key];
  11519. if (boundTexture) {
  11520. this._removeDesignatedSlot(boundTexture);
  11521. }
  11522. this._boundTexturesCache[key] = null;
  11523. }
  11524. if (!this.disableTextureBindingOptimization) {
  11525. this._nextFreeTextureSlots = [];
  11526. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11527. this._nextFreeTextureSlots.push(slot);
  11528. }
  11529. }
  11530. this._currentTextureChannel = -1;
  11531. };
  11532. Engine.prototype.isDeterministicLockStep = function () {
  11533. return this._deterministicLockstep;
  11534. };
  11535. Engine.prototype.getLockstepMaxSteps = function () {
  11536. return this._lockstepMaxSteps;
  11537. };
  11538. Engine.prototype.getGlInfo = function () {
  11539. return {
  11540. vendor: this._glVendor,
  11541. renderer: this._glRenderer,
  11542. version: this._glVersion
  11543. };
  11544. };
  11545. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11546. if (useScreen === void 0) { useScreen = false; }
  11547. var viewport = camera.viewport;
  11548. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11549. };
  11550. Engine.prototype.getRenderWidth = function (useScreen) {
  11551. if (useScreen === void 0) { useScreen = false; }
  11552. if (!useScreen && this._currentRenderTarget) {
  11553. return this._currentRenderTarget.width;
  11554. }
  11555. return this._gl.drawingBufferWidth;
  11556. };
  11557. Engine.prototype.getRenderHeight = function (useScreen) {
  11558. if (useScreen === void 0) { useScreen = false; }
  11559. if (!useScreen && this._currentRenderTarget) {
  11560. return this._currentRenderTarget.height;
  11561. }
  11562. return this._gl.drawingBufferHeight;
  11563. };
  11564. Engine.prototype.getRenderingCanvas = function () {
  11565. return this._renderingCanvas;
  11566. };
  11567. Engine.prototype.getRenderingCanvasClientRect = function () {
  11568. if (!this._renderingCanvas) {
  11569. return null;
  11570. }
  11571. return this._renderingCanvas.getBoundingClientRect();
  11572. };
  11573. Engine.prototype.setHardwareScalingLevel = function (level) {
  11574. this._hardwareScalingLevel = level;
  11575. this.resize();
  11576. };
  11577. Engine.prototype.getHardwareScalingLevel = function () {
  11578. return this._hardwareScalingLevel;
  11579. };
  11580. Engine.prototype.getLoadedTexturesCache = function () {
  11581. return this._internalTexturesCache;
  11582. };
  11583. Engine.prototype.getCaps = function () {
  11584. return this._caps;
  11585. };
  11586. Object.defineProperty(Engine.prototype, "drawCalls", {
  11587. /** The number of draw calls submitted last frame */
  11588. get: function () {
  11589. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11590. return 0;
  11591. },
  11592. enumerable: true,
  11593. configurable: true
  11594. });
  11595. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11596. get: function () {
  11597. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11598. return null;
  11599. },
  11600. enumerable: true,
  11601. configurable: true
  11602. });
  11603. Engine.prototype.getDepthFunction = function () {
  11604. return this._depthCullingState.depthFunc;
  11605. };
  11606. Engine.prototype.setDepthFunction = function (depthFunc) {
  11607. this._depthCullingState.depthFunc = depthFunc;
  11608. };
  11609. Engine.prototype.setDepthFunctionToGreater = function () {
  11610. this._depthCullingState.depthFunc = this._gl.GREATER;
  11611. };
  11612. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11613. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11614. };
  11615. Engine.prototype.setDepthFunctionToLess = function () {
  11616. this._depthCullingState.depthFunc = this._gl.LESS;
  11617. };
  11618. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11619. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11620. };
  11621. Engine.prototype.getStencilBuffer = function () {
  11622. return this._stencilState.stencilTest;
  11623. };
  11624. Engine.prototype.setStencilBuffer = function (enable) {
  11625. this._stencilState.stencilTest = enable;
  11626. };
  11627. Engine.prototype.getStencilMask = function () {
  11628. return this._stencilState.stencilMask;
  11629. };
  11630. Engine.prototype.setStencilMask = function (mask) {
  11631. this._stencilState.stencilMask = mask;
  11632. };
  11633. Engine.prototype.getStencilFunction = function () {
  11634. return this._stencilState.stencilFunc;
  11635. };
  11636. Engine.prototype.getStencilFunctionReference = function () {
  11637. return this._stencilState.stencilFuncRef;
  11638. };
  11639. Engine.prototype.getStencilFunctionMask = function () {
  11640. return this._stencilState.stencilFuncMask;
  11641. };
  11642. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11643. this._stencilState.stencilFunc = stencilFunc;
  11644. };
  11645. Engine.prototype.setStencilFunctionReference = function (reference) {
  11646. this._stencilState.stencilFuncRef = reference;
  11647. };
  11648. Engine.prototype.setStencilFunctionMask = function (mask) {
  11649. this._stencilState.stencilFuncMask = mask;
  11650. };
  11651. Engine.prototype.getStencilOperationFail = function () {
  11652. return this._stencilState.stencilOpStencilFail;
  11653. };
  11654. Engine.prototype.getStencilOperationDepthFail = function () {
  11655. return this._stencilState.stencilOpDepthFail;
  11656. };
  11657. Engine.prototype.getStencilOperationPass = function () {
  11658. return this._stencilState.stencilOpStencilDepthPass;
  11659. };
  11660. Engine.prototype.setStencilOperationFail = function (operation) {
  11661. this._stencilState.stencilOpStencilFail = operation;
  11662. };
  11663. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11664. this._stencilState.stencilOpDepthFail = operation;
  11665. };
  11666. Engine.prototype.setStencilOperationPass = function (operation) {
  11667. this._stencilState.stencilOpStencilDepthPass = operation;
  11668. };
  11669. Engine.prototype.setDitheringState = function (value) {
  11670. if (value) {
  11671. this._gl.enable(this._gl.DITHER);
  11672. }
  11673. else {
  11674. this._gl.disable(this._gl.DITHER);
  11675. }
  11676. };
  11677. Engine.prototype.setRasterizerState = function (value) {
  11678. if (value) {
  11679. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11680. }
  11681. else {
  11682. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11683. }
  11684. };
  11685. /**
  11686. * stop executing a render loop function and remove it from the execution array
  11687. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11688. */
  11689. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11690. if (!renderFunction) {
  11691. this._activeRenderLoops = [];
  11692. return;
  11693. }
  11694. var index = this._activeRenderLoops.indexOf(renderFunction);
  11695. if (index >= 0) {
  11696. this._activeRenderLoops.splice(index, 1);
  11697. }
  11698. };
  11699. Engine.prototype._renderLoop = function () {
  11700. if (!this._contextWasLost) {
  11701. var shouldRender = true;
  11702. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11703. shouldRender = false;
  11704. }
  11705. if (shouldRender) {
  11706. // Start new frame
  11707. this.beginFrame();
  11708. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11709. var renderFunction = this._activeRenderLoops[index];
  11710. renderFunction();
  11711. }
  11712. // Present
  11713. this.endFrame();
  11714. }
  11715. }
  11716. if (this._activeRenderLoops.length > 0) {
  11717. // Register new frame
  11718. var requester = null;
  11719. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11720. requester = this._vrDisplay;
  11721. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11722. }
  11723. else {
  11724. this._renderingQueueLaunched = false;
  11725. }
  11726. };
  11727. /**
  11728. * Register and execute a render loop. The engine can have more than one render function.
  11729. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11730. * @example
  11731. * engine.runRenderLoop(function () {
  11732. * scene.render()
  11733. * })
  11734. */
  11735. Engine.prototype.runRenderLoop = function (renderFunction) {
  11736. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11737. return;
  11738. }
  11739. this._activeRenderLoops.push(renderFunction);
  11740. if (!this._renderingQueueLaunched) {
  11741. this._renderingQueueLaunched = true;
  11742. this._bindedRenderFunction = this._renderLoop.bind(this);
  11743. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11744. }
  11745. };
  11746. /**
  11747. * Toggle full screen mode.
  11748. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11749. * @param {any} options - an options object to be sent to the requestFullscreen function
  11750. */
  11751. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11752. if (this.isFullscreen) {
  11753. BABYLON.Tools.ExitFullscreen();
  11754. }
  11755. else {
  11756. this._pointerLockRequested = requestPointerLock;
  11757. if (this._renderingCanvas) {
  11758. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11759. }
  11760. }
  11761. };
  11762. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11763. if (stencil === void 0) { stencil = false; }
  11764. this.applyStates();
  11765. var mode = 0;
  11766. if (backBuffer && color) {
  11767. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11768. mode |= this._gl.COLOR_BUFFER_BIT;
  11769. }
  11770. if (depth) {
  11771. this._gl.clearDepth(1.0);
  11772. mode |= this._gl.DEPTH_BUFFER_BIT;
  11773. }
  11774. if (stencil) {
  11775. this._gl.clearStencil(0);
  11776. mode |= this._gl.STENCIL_BUFFER_BIT;
  11777. }
  11778. this._gl.clear(mode);
  11779. };
  11780. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11781. var gl = this._gl;
  11782. // Save state
  11783. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11784. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11785. // Change state
  11786. gl.enable(gl.SCISSOR_TEST);
  11787. gl.scissor(x, y, width, height);
  11788. // Clear
  11789. this.clear(clearColor, true, true, true);
  11790. // Restore state
  11791. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11792. if (curScissor === true) {
  11793. gl.enable(gl.SCISSOR_TEST);
  11794. }
  11795. else {
  11796. gl.disable(gl.SCISSOR_TEST);
  11797. }
  11798. };
  11799. /**
  11800. * Set the WebGL's viewport
  11801. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11802. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11803. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11804. */
  11805. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11806. var width = requiredWidth || this.getRenderWidth();
  11807. var height = requiredHeight || this.getRenderHeight();
  11808. var x = viewport.x || 0;
  11809. var y = viewport.y || 0;
  11810. this._cachedViewport = viewport;
  11811. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11812. };
  11813. /**
  11814. * Directly set the WebGL Viewport
  11815. * The x, y, width & height are directly passed to the WebGL call
  11816. * @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.
  11817. */
  11818. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11819. var currentViewport = this._cachedViewport;
  11820. this._cachedViewport = null;
  11821. this._gl.viewport(x, y, width, height);
  11822. return currentViewport;
  11823. };
  11824. Engine.prototype.beginFrame = function () {
  11825. this.onBeginFrameObservable.notifyObservers(this);
  11826. this._measureFps();
  11827. };
  11828. Engine.prototype.endFrame = function () {
  11829. //force a flush in case we are using a bad OS.
  11830. if (this._badOS) {
  11831. this.flushFramebuffer();
  11832. }
  11833. //submit frame to the vr device, if enabled
  11834. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11835. // TODO: We should only submit the frame if we read frameData successfully.
  11836. this._vrDisplay.submitFrame();
  11837. }
  11838. this.onEndFrameObservable.notifyObservers(this);
  11839. };
  11840. /**
  11841. * resize the view according to the canvas' size.
  11842. * @example
  11843. * window.addEventListener("resize", function () {
  11844. * engine.resize();
  11845. * });
  11846. */
  11847. Engine.prototype.resize = function () {
  11848. // We're not resizing the size of the canvas while in VR mode & presenting
  11849. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11850. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11851. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11852. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11853. }
  11854. };
  11855. /**
  11856. * force a specific size of the canvas
  11857. * @param {number} width - the new canvas' width
  11858. * @param {number} height - the new canvas' height
  11859. */
  11860. Engine.prototype.setSize = function (width, height) {
  11861. if (!this._renderingCanvas) {
  11862. return;
  11863. }
  11864. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11865. return;
  11866. }
  11867. this._renderingCanvas.width = width;
  11868. this._renderingCanvas.height = height;
  11869. for (var index = 0; index < this.scenes.length; index++) {
  11870. var scene = this.scenes[index];
  11871. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11872. var cam = scene.cameras[camIndex];
  11873. cam._currentRenderId = 0;
  11874. }
  11875. }
  11876. if (this.onResizeObservable.hasObservers) {
  11877. this.onResizeObservable.notifyObservers(this);
  11878. }
  11879. };
  11880. // WebVR functions
  11881. Engine.prototype.isVRDevicePresent = function () {
  11882. return !!this._vrDisplay;
  11883. };
  11884. Engine.prototype.getVRDevice = function () {
  11885. return this._vrDisplay;
  11886. };
  11887. /**
  11888. * Initializes a webVR display and starts listening to display change events.
  11889. * The onVRDisplayChangedObservable will be notified upon these changes.
  11890. * @returns The onVRDisplayChangedObservable.
  11891. */
  11892. Engine.prototype.initWebVR = function () {
  11893. this.initWebVRAsync();
  11894. return this.onVRDisplayChangedObservable;
  11895. };
  11896. /**
  11897. * Initializes a webVR display and starts listening to display change events.
  11898. * The onVRDisplayChangedObservable will be notified upon these changes.
  11899. * @returns A promise containing a VRDisplay and if vr is supported.
  11900. */
  11901. Engine.prototype.initWebVRAsync = function () {
  11902. var _this = this;
  11903. var notifyObservers = function () {
  11904. var eventArgs = {
  11905. vrDisplay: _this._vrDisplay,
  11906. vrSupported: _this._vrSupported
  11907. };
  11908. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11909. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11910. };
  11911. if (!this._onVrDisplayConnect) {
  11912. this._onVrDisplayConnect = function (event) {
  11913. _this._vrDisplay = event.display;
  11914. notifyObservers();
  11915. };
  11916. this._onVrDisplayDisconnect = function () {
  11917. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11918. _this._vrDisplay = undefined;
  11919. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11920. notifyObservers();
  11921. };
  11922. this._onVrDisplayPresentChange = function () {
  11923. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11924. };
  11925. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11926. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11927. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11928. }
  11929. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11930. this._webVRInitPromise.then(notifyObservers);
  11931. return this._webVRInitPromise;
  11932. };
  11933. Engine.prototype.enableVR = function () {
  11934. var _this = this;
  11935. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11936. var onResolved = function () {
  11937. _this.onVRRequestPresentComplete.notifyObservers(true);
  11938. _this._onVRFullScreenTriggered();
  11939. };
  11940. var onRejected = function () {
  11941. _this.onVRRequestPresentComplete.notifyObservers(false);
  11942. };
  11943. this.onVRRequestPresentStart.notifyObservers(this);
  11944. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11945. }
  11946. };
  11947. Engine.prototype.disableVR = function () {
  11948. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11949. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11950. }
  11951. };
  11952. Engine.prototype._getVRDisplaysAsync = function () {
  11953. var _this = this;
  11954. return new Promise(function (res, rej) {
  11955. if (navigator.getVRDisplays) {
  11956. navigator.getVRDisplays().then(function (devices) {
  11957. _this._vrSupported = true;
  11958. // note that devices may actually be an empty array. This is fine;
  11959. // we expect this._vrDisplay to be undefined in this case.
  11960. _this._vrDisplay = devices[0];
  11961. res({
  11962. vrDisplay: _this._vrDisplay,
  11963. vrSupported: _this._vrSupported
  11964. });
  11965. });
  11966. }
  11967. else {
  11968. _this._vrDisplay = undefined;
  11969. _this._vrSupported = false;
  11970. res({
  11971. vrDisplay: _this._vrDisplay,
  11972. vrSupported: _this._vrSupported
  11973. });
  11974. }
  11975. });
  11976. };
  11977. /**
  11978. * Binds the frame buffer to the specified texture.
  11979. * @param texture The texture to render to or null for the default canvas
  11980. * @param faceIndex The face of the texture to render to in case of cube texture
  11981. * @param requiredWidth The width of the target to render to
  11982. * @param requiredHeight The height of the target to render to
  11983. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11984. * @param depthStencilTexture The depth stencil texture to use to render
  11985. */
  11986. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11987. if (this._currentRenderTarget) {
  11988. this.unBindFramebuffer(this._currentRenderTarget);
  11989. }
  11990. this._currentRenderTarget = texture;
  11991. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11992. var gl = this._gl;
  11993. if (texture.isCube) {
  11994. if (faceIndex === undefined) {
  11995. faceIndex = 0;
  11996. }
  11997. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11998. if (depthStencilTexture) {
  11999. if (depthStencilTexture._generateStencilBuffer) {
  12000. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12001. }
  12002. else {
  12003. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12004. }
  12005. }
  12006. }
  12007. if (this._cachedViewport && !forceFullscreenViewport) {
  12008. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12009. }
  12010. else {
  12011. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12012. }
  12013. this.wipeCaches();
  12014. };
  12015. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12016. if (this._currentFramebuffer !== framebuffer) {
  12017. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12018. this._currentFramebuffer = framebuffer;
  12019. }
  12020. };
  12021. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12022. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12023. this._currentRenderTarget = null;
  12024. // If MSAA, we need to bitblt back to main texture
  12025. var gl = this._gl;
  12026. if (texture._MSAAFramebuffer) {
  12027. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12028. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12029. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12030. }
  12031. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12032. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12033. gl.generateMipmap(gl.TEXTURE_2D);
  12034. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12035. }
  12036. if (onBeforeUnbind) {
  12037. if (texture._MSAAFramebuffer) {
  12038. // Bind the correct framebuffer
  12039. this.bindUnboundFramebuffer(texture._framebuffer);
  12040. }
  12041. onBeforeUnbind();
  12042. }
  12043. this.bindUnboundFramebuffer(null);
  12044. };
  12045. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12046. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12047. this._currentRenderTarget = null;
  12048. // If MSAA, we need to bitblt back to main texture
  12049. var gl = this._gl;
  12050. if (textures[0]._MSAAFramebuffer) {
  12051. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12052. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12053. var attachments = textures[0]._attachments;
  12054. if (!attachments) {
  12055. attachments = new Array(textures.length);
  12056. textures[0]._attachments = attachments;
  12057. }
  12058. for (var i = 0; i < textures.length; i++) {
  12059. var texture = textures[i];
  12060. for (var j = 0; j < attachments.length; j++) {
  12061. attachments[j] = gl.NONE;
  12062. }
  12063. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12064. gl.readBuffer(attachments[i]);
  12065. gl.drawBuffers(attachments);
  12066. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12067. }
  12068. for (var i = 0; i < attachments.length; i++) {
  12069. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12070. }
  12071. gl.drawBuffers(attachments);
  12072. }
  12073. for (var i = 0; i < textures.length; i++) {
  12074. var texture = textures[i];
  12075. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12076. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12077. gl.generateMipmap(gl.TEXTURE_2D);
  12078. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12079. }
  12080. }
  12081. if (onBeforeUnbind) {
  12082. if (textures[0]._MSAAFramebuffer) {
  12083. // Bind the correct framebuffer
  12084. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12085. }
  12086. onBeforeUnbind();
  12087. }
  12088. this.bindUnboundFramebuffer(null);
  12089. };
  12090. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12091. if (texture.generateMipMaps) {
  12092. var gl = this._gl;
  12093. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12094. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12095. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12096. }
  12097. };
  12098. Engine.prototype.flushFramebuffer = function () {
  12099. this._gl.flush();
  12100. };
  12101. Engine.prototype.restoreDefaultFramebuffer = function () {
  12102. if (this._currentRenderTarget) {
  12103. this.unBindFramebuffer(this._currentRenderTarget);
  12104. }
  12105. else {
  12106. this.bindUnboundFramebuffer(null);
  12107. }
  12108. if (this._cachedViewport) {
  12109. this.setViewport(this._cachedViewport);
  12110. }
  12111. this.wipeCaches();
  12112. };
  12113. // UBOs
  12114. Engine.prototype.createUniformBuffer = function (elements) {
  12115. var ubo = this._gl.createBuffer();
  12116. if (!ubo) {
  12117. throw new Error("Unable to create uniform buffer");
  12118. }
  12119. this.bindUniformBuffer(ubo);
  12120. if (elements instanceof Float32Array) {
  12121. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12122. }
  12123. else {
  12124. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12125. }
  12126. this.bindUniformBuffer(null);
  12127. ubo.references = 1;
  12128. return ubo;
  12129. };
  12130. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12131. var ubo = this._gl.createBuffer();
  12132. if (!ubo) {
  12133. throw new Error("Unable to create dynamic uniform buffer");
  12134. }
  12135. this.bindUniformBuffer(ubo);
  12136. if (elements instanceof Float32Array) {
  12137. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12138. }
  12139. else {
  12140. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12141. }
  12142. this.bindUniformBuffer(null);
  12143. ubo.references = 1;
  12144. return ubo;
  12145. };
  12146. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12147. this.bindUniformBuffer(uniformBuffer);
  12148. if (offset === undefined) {
  12149. offset = 0;
  12150. }
  12151. if (count === undefined) {
  12152. if (elements instanceof Float32Array) {
  12153. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12154. }
  12155. else {
  12156. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12157. }
  12158. }
  12159. else {
  12160. if (elements instanceof Float32Array) {
  12161. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12162. }
  12163. else {
  12164. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12165. }
  12166. }
  12167. this.bindUniformBuffer(null);
  12168. };
  12169. // VBOs
  12170. Engine.prototype._resetVertexBufferBinding = function () {
  12171. this.bindArrayBuffer(null);
  12172. this._cachedVertexBuffers = null;
  12173. };
  12174. Engine.prototype.createVertexBuffer = function (vertices) {
  12175. var vbo = this._gl.createBuffer();
  12176. if (!vbo) {
  12177. throw new Error("Unable to create vertex buffer");
  12178. }
  12179. this.bindArrayBuffer(vbo);
  12180. if (vertices instanceof Float32Array) {
  12181. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12182. }
  12183. else {
  12184. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12185. }
  12186. this._resetVertexBufferBinding();
  12187. vbo.references = 1;
  12188. return vbo;
  12189. };
  12190. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12191. var vbo = this._gl.createBuffer();
  12192. if (!vbo) {
  12193. throw new Error("Unable to create dynamic vertex buffer");
  12194. }
  12195. this.bindArrayBuffer(vbo);
  12196. if (vertices instanceof Float32Array) {
  12197. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12198. }
  12199. else {
  12200. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12201. }
  12202. this._resetVertexBufferBinding();
  12203. vbo.references = 1;
  12204. return vbo;
  12205. };
  12206. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12207. if (offset === void 0) { offset = 0; }
  12208. // Force cache update
  12209. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12210. this.bindIndexBuffer(indexBuffer);
  12211. var arrayBuffer;
  12212. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12213. arrayBuffer = indices;
  12214. }
  12215. else {
  12216. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12217. }
  12218. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12219. this._resetIndexBufferBinding();
  12220. };
  12221. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12222. this.bindArrayBuffer(vertexBuffer);
  12223. if (offset === undefined) {
  12224. offset = 0;
  12225. }
  12226. if (count === undefined) {
  12227. if (vertices instanceof Float32Array) {
  12228. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12229. }
  12230. else {
  12231. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12232. }
  12233. }
  12234. else {
  12235. if (vertices instanceof Float32Array) {
  12236. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12237. }
  12238. else {
  12239. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12240. }
  12241. }
  12242. this._resetVertexBufferBinding();
  12243. };
  12244. Engine.prototype._resetIndexBufferBinding = function () {
  12245. this.bindIndexBuffer(null);
  12246. this._cachedIndexBuffer = null;
  12247. };
  12248. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12249. var vbo = this._gl.createBuffer();
  12250. if (!vbo) {
  12251. throw new Error("Unable to create index buffer");
  12252. }
  12253. this.bindIndexBuffer(vbo);
  12254. // Check for 32 bits indices
  12255. var arrayBuffer;
  12256. var need32Bits = false;
  12257. if (indices instanceof Uint16Array) {
  12258. arrayBuffer = indices;
  12259. }
  12260. else {
  12261. //check 32 bit support
  12262. if (this._caps.uintIndices) {
  12263. if (indices instanceof Uint32Array) {
  12264. arrayBuffer = indices;
  12265. need32Bits = true;
  12266. }
  12267. else {
  12268. //number[] or Int32Array, check if 32 bit is necessary
  12269. for (var index = 0; index < indices.length; index++) {
  12270. if (indices[index] > 65535) {
  12271. need32Bits = true;
  12272. break;
  12273. }
  12274. }
  12275. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12276. }
  12277. }
  12278. else {
  12279. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12280. arrayBuffer = new Uint16Array(indices);
  12281. }
  12282. }
  12283. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12284. this._resetIndexBufferBinding();
  12285. vbo.references = 1;
  12286. vbo.is32Bits = need32Bits;
  12287. return vbo;
  12288. };
  12289. Engine.prototype.bindArrayBuffer = function (buffer) {
  12290. if (!this._vaoRecordInProgress) {
  12291. this._unbindVertexArrayObject();
  12292. }
  12293. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12294. };
  12295. Engine.prototype.bindUniformBuffer = function (buffer) {
  12296. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12297. };
  12298. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12299. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12300. };
  12301. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12302. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12303. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12304. };
  12305. ;
  12306. Engine.prototype.bindIndexBuffer = function (buffer) {
  12307. if (!this._vaoRecordInProgress) {
  12308. this._unbindVertexArrayObject();
  12309. }
  12310. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12311. };
  12312. Engine.prototype.bindBuffer = function (buffer, target) {
  12313. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12314. this._gl.bindBuffer(target, buffer);
  12315. this._currentBoundBuffer[target] = buffer;
  12316. }
  12317. };
  12318. Engine.prototype.updateArrayBuffer = function (data) {
  12319. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12320. };
  12321. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12322. var pointer = this._currentBufferPointers[indx];
  12323. var changed = false;
  12324. if (!pointer.active) {
  12325. changed = true;
  12326. pointer.active = true;
  12327. pointer.index = indx;
  12328. pointer.size = size;
  12329. pointer.type = type;
  12330. pointer.normalized = normalized;
  12331. pointer.stride = stride;
  12332. pointer.offset = offset;
  12333. pointer.buffer = buffer;
  12334. }
  12335. else {
  12336. if (pointer.buffer !== buffer) {
  12337. pointer.buffer = buffer;
  12338. changed = true;
  12339. }
  12340. if (pointer.size !== size) {
  12341. pointer.size = size;
  12342. changed = true;
  12343. }
  12344. if (pointer.type !== type) {
  12345. pointer.type = type;
  12346. changed = true;
  12347. }
  12348. if (pointer.normalized !== normalized) {
  12349. pointer.normalized = normalized;
  12350. changed = true;
  12351. }
  12352. if (pointer.stride !== stride) {
  12353. pointer.stride = stride;
  12354. changed = true;
  12355. }
  12356. if (pointer.offset !== offset) {
  12357. pointer.offset = offset;
  12358. changed = true;
  12359. }
  12360. }
  12361. if (changed || this._vaoRecordInProgress) {
  12362. this.bindArrayBuffer(buffer);
  12363. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12364. }
  12365. };
  12366. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12367. if (indexBuffer == null) {
  12368. return;
  12369. }
  12370. if (this._cachedIndexBuffer !== indexBuffer) {
  12371. this._cachedIndexBuffer = indexBuffer;
  12372. this.bindIndexBuffer(indexBuffer);
  12373. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12374. }
  12375. };
  12376. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12377. var attributes = effect.getAttributesNames();
  12378. if (!this._vaoRecordInProgress) {
  12379. this._unbindVertexArrayObject();
  12380. }
  12381. this.unbindAllAttributes();
  12382. for (var index = 0; index < attributes.length; index++) {
  12383. var order = effect.getAttributeLocation(index);
  12384. if (order >= 0) {
  12385. var vertexBuffer = vertexBuffers[attributes[index]];
  12386. if (!vertexBuffer) {
  12387. continue;
  12388. }
  12389. this._gl.enableVertexAttribArray(order);
  12390. if (!this._vaoRecordInProgress) {
  12391. this._vertexAttribArraysEnabled[order] = true;
  12392. }
  12393. var buffer = vertexBuffer.getBuffer();
  12394. if (buffer) {
  12395. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12396. if (vertexBuffer.getIsInstanced()) {
  12397. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12398. if (!this._vaoRecordInProgress) {
  12399. this._currentInstanceLocations.push(order);
  12400. this._currentInstanceBuffers.push(buffer);
  12401. }
  12402. }
  12403. }
  12404. }
  12405. }
  12406. };
  12407. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12408. var vao = this._gl.createVertexArray();
  12409. this._vaoRecordInProgress = true;
  12410. this._gl.bindVertexArray(vao);
  12411. this._mustWipeVertexAttributes = true;
  12412. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12413. this.bindIndexBuffer(indexBuffer);
  12414. this._vaoRecordInProgress = false;
  12415. this._gl.bindVertexArray(null);
  12416. return vao;
  12417. };
  12418. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12419. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12420. this._cachedVertexArrayObject = vertexArrayObject;
  12421. this._gl.bindVertexArray(vertexArrayObject);
  12422. this._cachedVertexBuffers = null;
  12423. this._cachedIndexBuffer = null;
  12424. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12425. this._mustWipeVertexAttributes = true;
  12426. }
  12427. };
  12428. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12429. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12430. this._cachedVertexBuffers = vertexBuffer;
  12431. this._cachedEffectForVertexBuffers = effect;
  12432. var attributesCount = effect.getAttributesCount();
  12433. this._unbindVertexArrayObject();
  12434. this.unbindAllAttributes();
  12435. var offset = 0;
  12436. for (var index = 0; index < attributesCount; index++) {
  12437. if (index < vertexDeclaration.length) {
  12438. var order = effect.getAttributeLocation(index);
  12439. if (order >= 0) {
  12440. this._gl.enableVertexAttribArray(order);
  12441. this._vertexAttribArraysEnabled[order] = true;
  12442. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12443. }
  12444. offset += vertexDeclaration[index] * 4;
  12445. }
  12446. }
  12447. }
  12448. this._bindIndexBufferWithCache(indexBuffer);
  12449. };
  12450. Engine.prototype._unbindVertexArrayObject = function () {
  12451. if (!this._cachedVertexArrayObject) {
  12452. return;
  12453. }
  12454. this._cachedVertexArrayObject = null;
  12455. this._gl.bindVertexArray(null);
  12456. };
  12457. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12458. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12459. this._cachedVertexBuffers = vertexBuffers;
  12460. this._cachedEffectForVertexBuffers = effect;
  12461. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12462. }
  12463. this._bindIndexBufferWithCache(indexBuffer);
  12464. };
  12465. Engine.prototype.unbindInstanceAttributes = function () {
  12466. var boundBuffer;
  12467. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12468. var instancesBuffer = this._currentInstanceBuffers[i];
  12469. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12470. boundBuffer = instancesBuffer;
  12471. this.bindArrayBuffer(instancesBuffer);
  12472. }
  12473. var offsetLocation = this._currentInstanceLocations[i];
  12474. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12475. }
  12476. this._currentInstanceBuffers.length = 0;
  12477. this._currentInstanceLocations.length = 0;
  12478. };
  12479. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12480. this._gl.deleteVertexArray(vao);
  12481. };
  12482. Engine.prototype._releaseBuffer = function (buffer) {
  12483. buffer.references--;
  12484. if (buffer.references === 0) {
  12485. this._gl.deleteBuffer(buffer);
  12486. return true;
  12487. }
  12488. return false;
  12489. };
  12490. Engine.prototype.createInstancesBuffer = function (capacity) {
  12491. var buffer = this._gl.createBuffer();
  12492. if (!buffer) {
  12493. throw new Error("Unable to create instance buffer");
  12494. }
  12495. buffer.capacity = capacity;
  12496. this.bindArrayBuffer(buffer);
  12497. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12498. return buffer;
  12499. };
  12500. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12501. this._gl.deleteBuffer(buffer);
  12502. };
  12503. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12504. this.bindArrayBuffer(instancesBuffer);
  12505. if (data) {
  12506. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12507. }
  12508. if (offsetLocations[0].index !== undefined) {
  12509. var stride = 0;
  12510. for (var i = 0; i < offsetLocations.length; i++) {
  12511. var ai = offsetLocations[i];
  12512. stride += ai.attributeSize * 4;
  12513. }
  12514. for (var i = 0; i < offsetLocations.length; i++) {
  12515. var ai = offsetLocations[i];
  12516. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12517. this._gl.enableVertexAttribArray(ai.index);
  12518. this._vertexAttribArraysEnabled[ai.index] = true;
  12519. }
  12520. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12521. this._gl.vertexAttribDivisor(ai.index, 1);
  12522. this._currentInstanceLocations.push(ai.index);
  12523. this._currentInstanceBuffers.push(instancesBuffer);
  12524. }
  12525. }
  12526. else {
  12527. for (var index = 0; index < 4; index++) {
  12528. var offsetLocation = offsetLocations[index];
  12529. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12530. this._gl.enableVertexAttribArray(offsetLocation);
  12531. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12532. }
  12533. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12534. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12535. this._currentInstanceLocations.push(offsetLocation);
  12536. this._currentInstanceBuffers.push(instancesBuffer);
  12537. }
  12538. }
  12539. };
  12540. Engine.prototype.applyStates = function () {
  12541. this._depthCullingState.apply(this._gl);
  12542. this._stencilState.apply(this._gl);
  12543. this._alphaState.apply(this._gl);
  12544. };
  12545. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12546. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12547. };
  12548. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12549. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12550. };
  12551. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12552. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12553. };
  12554. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12555. // Apply states
  12556. this.applyStates();
  12557. this._drawCalls.addCount(1, false);
  12558. // Render
  12559. var drawMode = this._drawMode(fillMode);
  12560. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12561. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12562. if (instancesCount) {
  12563. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12564. }
  12565. else {
  12566. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12567. }
  12568. };
  12569. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12570. // Apply states
  12571. this.applyStates();
  12572. this._drawCalls.addCount(1, false);
  12573. var drawMode = this._drawMode(fillMode);
  12574. if (instancesCount) {
  12575. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12576. }
  12577. else {
  12578. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12579. }
  12580. };
  12581. Engine.prototype._drawMode = function (fillMode) {
  12582. switch (fillMode) {
  12583. // Triangle views
  12584. case BABYLON.Material.TriangleFillMode:
  12585. return this._gl.TRIANGLES;
  12586. case BABYLON.Material.PointFillMode:
  12587. return this._gl.POINTS;
  12588. case BABYLON.Material.WireFrameFillMode:
  12589. return this._gl.LINES;
  12590. // Draw modes
  12591. case BABYLON.Material.PointListDrawMode:
  12592. return this._gl.POINTS;
  12593. case BABYLON.Material.LineListDrawMode:
  12594. return this._gl.LINES;
  12595. case BABYLON.Material.LineLoopDrawMode:
  12596. return this._gl.LINE_LOOP;
  12597. case BABYLON.Material.LineStripDrawMode:
  12598. return this._gl.LINE_STRIP;
  12599. case BABYLON.Material.TriangleStripDrawMode:
  12600. return this._gl.TRIANGLE_STRIP;
  12601. case BABYLON.Material.TriangleFanDrawMode:
  12602. return this._gl.TRIANGLE_FAN;
  12603. default:
  12604. return this._gl.TRIANGLES;
  12605. }
  12606. };
  12607. // Shaders
  12608. Engine.prototype._releaseEffect = function (effect) {
  12609. if (this._compiledEffects[effect._key]) {
  12610. delete this._compiledEffects[effect._key];
  12611. this._deleteProgram(effect.getProgram());
  12612. }
  12613. };
  12614. Engine.prototype._deleteProgram = function (program) {
  12615. if (program) {
  12616. program.__SPECTOR_rebuildProgram = null;
  12617. if (program.transformFeedback) {
  12618. this.deleteTransformFeedback(program.transformFeedback);
  12619. program.transformFeedback = null;
  12620. }
  12621. this._gl.deleteProgram(program);
  12622. }
  12623. };
  12624. /**
  12625. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12626. * @param samplers An array of string used to represent textures
  12627. */
  12628. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12629. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12630. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12631. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12632. if (this._compiledEffects[name]) {
  12633. var compiledEffect = this._compiledEffects[name];
  12634. if (onCompiled && compiledEffect.isReady()) {
  12635. onCompiled(compiledEffect);
  12636. }
  12637. return compiledEffect;
  12638. }
  12639. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12640. effect._key = name;
  12641. this._compiledEffects[name] = effect;
  12642. return effect;
  12643. };
  12644. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12645. if (uniformsNames === void 0) { uniformsNames = []; }
  12646. if (samplers === void 0) { samplers = []; }
  12647. if (defines === void 0) { defines = ""; }
  12648. return this.createEffect({
  12649. vertex: "particles",
  12650. fragmentElement: fragmentName
  12651. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12652. };
  12653. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12654. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12655. context = context || this._gl;
  12656. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12657. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12658. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12659. };
  12660. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12661. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12662. context = context || this._gl;
  12663. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12664. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12665. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12666. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12667. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12668. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12669. return program;
  12670. };
  12671. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12672. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12673. var shaderProgram = context.createProgram();
  12674. if (!shaderProgram) {
  12675. throw new Error("Unable to create program");
  12676. }
  12677. context.attachShader(shaderProgram, vertexShader);
  12678. context.attachShader(shaderProgram, fragmentShader);
  12679. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12680. var transformFeedback = this.createTransformFeedback();
  12681. this.bindTransformFeedback(transformFeedback);
  12682. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12683. shaderProgram.transformFeedback = transformFeedback;
  12684. }
  12685. context.linkProgram(shaderProgram);
  12686. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12687. this.bindTransformFeedback(null);
  12688. }
  12689. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12690. if (!linked) {
  12691. context.validateProgram(shaderProgram);
  12692. var error = context.getProgramInfoLog(shaderProgram);
  12693. if (error) {
  12694. throw new Error(error);
  12695. }
  12696. }
  12697. context.deleteShader(vertexShader);
  12698. context.deleteShader(fragmentShader);
  12699. return shaderProgram;
  12700. };
  12701. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12702. var results = new Array();
  12703. for (var index = 0; index < uniformsNames.length; index++) {
  12704. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12705. }
  12706. return results;
  12707. };
  12708. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12709. var results = [];
  12710. for (var index = 0; index < attributesNames.length; index++) {
  12711. try {
  12712. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12713. }
  12714. catch (e) {
  12715. results.push(-1);
  12716. }
  12717. }
  12718. return results;
  12719. };
  12720. Engine.prototype.enableEffect = function (effect) {
  12721. if (!effect) {
  12722. return;
  12723. }
  12724. // Use program
  12725. this.bindSamplers(effect);
  12726. this._currentEffect = effect;
  12727. if (effect.onBind) {
  12728. effect.onBind(effect);
  12729. }
  12730. effect.onBindObservable.notifyObservers(effect);
  12731. };
  12732. Engine.prototype.setIntArray = function (uniform, array) {
  12733. if (!uniform)
  12734. return;
  12735. this._gl.uniform1iv(uniform, array);
  12736. };
  12737. Engine.prototype.setIntArray2 = function (uniform, array) {
  12738. if (!uniform || array.length % 2 !== 0)
  12739. return;
  12740. this._gl.uniform2iv(uniform, array);
  12741. };
  12742. Engine.prototype.setIntArray3 = function (uniform, array) {
  12743. if (!uniform || array.length % 3 !== 0)
  12744. return;
  12745. this._gl.uniform3iv(uniform, array);
  12746. };
  12747. Engine.prototype.setIntArray4 = function (uniform, array) {
  12748. if (!uniform || array.length % 4 !== 0)
  12749. return;
  12750. this._gl.uniform4iv(uniform, array);
  12751. };
  12752. Engine.prototype.setFloatArray = function (uniform, array) {
  12753. if (!uniform)
  12754. return;
  12755. this._gl.uniform1fv(uniform, array);
  12756. };
  12757. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12758. if (!uniform || array.length % 2 !== 0)
  12759. return;
  12760. this._gl.uniform2fv(uniform, array);
  12761. };
  12762. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12763. if (!uniform || array.length % 3 !== 0)
  12764. return;
  12765. this._gl.uniform3fv(uniform, array);
  12766. };
  12767. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12768. if (!uniform || array.length % 4 !== 0)
  12769. return;
  12770. this._gl.uniform4fv(uniform, array);
  12771. };
  12772. Engine.prototype.setArray = function (uniform, array) {
  12773. if (!uniform)
  12774. return;
  12775. this._gl.uniform1fv(uniform, array);
  12776. };
  12777. Engine.prototype.setArray2 = function (uniform, array) {
  12778. if (!uniform || array.length % 2 !== 0)
  12779. return;
  12780. this._gl.uniform2fv(uniform, array);
  12781. };
  12782. Engine.prototype.setArray3 = function (uniform, array) {
  12783. if (!uniform || array.length % 3 !== 0)
  12784. return;
  12785. this._gl.uniform3fv(uniform, array);
  12786. };
  12787. Engine.prototype.setArray4 = function (uniform, array) {
  12788. if (!uniform || array.length % 4 !== 0)
  12789. return;
  12790. this._gl.uniform4fv(uniform, array);
  12791. };
  12792. Engine.prototype.setMatrices = function (uniform, matrices) {
  12793. if (!uniform)
  12794. return;
  12795. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12796. };
  12797. Engine.prototype.setMatrix = function (uniform, matrix) {
  12798. if (!uniform)
  12799. return;
  12800. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12801. };
  12802. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12803. if (!uniform)
  12804. return;
  12805. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12806. };
  12807. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12808. if (!uniform)
  12809. return;
  12810. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12811. };
  12812. Engine.prototype.setInt = function (uniform, value) {
  12813. if (!uniform)
  12814. return;
  12815. this._gl.uniform1i(uniform, value);
  12816. };
  12817. Engine.prototype.setFloat = function (uniform, value) {
  12818. if (!uniform)
  12819. return;
  12820. this._gl.uniform1f(uniform, value);
  12821. };
  12822. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12823. if (!uniform)
  12824. return;
  12825. this._gl.uniform2f(uniform, x, y);
  12826. };
  12827. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12828. if (!uniform)
  12829. return;
  12830. this._gl.uniform3f(uniform, x, y, z);
  12831. };
  12832. Engine.prototype.setBool = function (uniform, bool) {
  12833. if (!uniform)
  12834. return;
  12835. this._gl.uniform1i(uniform, bool);
  12836. };
  12837. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12838. if (!uniform)
  12839. return;
  12840. this._gl.uniform4f(uniform, x, y, z, w);
  12841. };
  12842. Engine.prototype.setColor3 = function (uniform, color3) {
  12843. if (!uniform)
  12844. return;
  12845. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12846. };
  12847. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12848. if (!uniform)
  12849. return;
  12850. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12851. };
  12852. /**
  12853. * Sets a Color4 on a uniform variable
  12854. * @param uniform defines the uniform location
  12855. * @param color4 defines the value to be set
  12856. */
  12857. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12858. if (!uniform)
  12859. return;
  12860. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12861. };
  12862. // States
  12863. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12864. if (zOffset === void 0) { zOffset = 0; }
  12865. if (reverseSide === void 0) { reverseSide = false; }
  12866. // Culling
  12867. if (this._depthCullingState.cull !== culling || force) {
  12868. this._depthCullingState.cull = culling;
  12869. }
  12870. // Cull face
  12871. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12872. if (this._depthCullingState.cullFace !== cullFace || force) {
  12873. this._depthCullingState.cullFace = cullFace;
  12874. }
  12875. // Z offset
  12876. this.setZOffset(zOffset);
  12877. // Front face
  12878. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12879. if (this._depthCullingState.frontFace !== frontFace || force) {
  12880. this._depthCullingState.frontFace = frontFace;
  12881. }
  12882. };
  12883. Engine.prototype.setZOffset = function (value) {
  12884. this._depthCullingState.zOffset = value;
  12885. };
  12886. Engine.prototype.getZOffset = function () {
  12887. return this._depthCullingState.zOffset;
  12888. };
  12889. Engine.prototype.setDepthBuffer = function (enable) {
  12890. this._depthCullingState.depthTest = enable;
  12891. };
  12892. Engine.prototype.getDepthWrite = function () {
  12893. return this._depthCullingState.depthMask;
  12894. };
  12895. Engine.prototype.setDepthWrite = function (enable) {
  12896. this._depthCullingState.depthMask = enable;
  12897. };
  12898. Engine.prototype.setColorWrite = function (enable) {
  12899. this._gl.colorMask(enable, enable, enable, enable);
  12900. this._colorWrite = enable;
  12901. };
  12902. Engine.prototype.getColorWrite = function () {
  12903. return this._colorWrite;
  12904. };
  12905. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12906. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12907. };
  12908. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12909. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12910. if (this._alphaMode === mode) {
  12911. return;
  12912. }
  12913. switch (mode) {
  12914. case Engine.ALPHA_DISABLE:
  12915. this._alphaState.alphaBlend = false;
  12916. break;
  12917. case Engine.ALPHA_PREMULTIPLIED:
  12918. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12919. this._alphaState.alphaBlend = true;
  12920. break;
  12921. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12922. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12923. this._alphaState.alphaBlend = true;
  12924. break;
  12925. case Engine.ALPHA_COMBINE:
  12926. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12927. this._alphaState.alphaBlend = true;
  12928. break;
  12929. case Engine.ALPHA_ONEONE:
  12930. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12931. this._alphaState.alphaBlend = true;
  12932. break;
  12933. case Engine.ALPHA_ADD:
  12934. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12935. this._alphaState.alphaBlend = true;
  12936. break;
  12937. case Engine.ALPHA_SUBTRACT:
  12938. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12939. this._alphaState.alphaBlend = true;
  12940. break;
  12941. case Engine.ALPHA_MULTIPLY:
  12942. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12943. this._alphaState.alphaBlend = true;
  12944. break;
  12945. case Engine.ALPHA_MAXIMIZED:
  12946. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12947. this._alphaState.alphaBlend = true;
  12948. break;
  12949. case Engine.ALPHA_INTERPOLATE:
  12950. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12951. this._alphaState.alphaBlend = true;
  12952. break;
  12953. case Engine.ALPHA_SCREENMODE:
  12954. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12955. this._alphaState.alphaBlend = true;
  12956. break;
  12957. }
  12958. if (!noDepthWriteChange) {
  12959. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12960. }
  12961. this._alphaMode = mode;
  12962. };
  12963. Engine.prototype.getAlphaMode = function () {
  12964. return this._alphaMode;
  12965. };
  12966. // Textures
  12967. Engine.prototype.wipeCaches = function (bruteForce) {
  12968. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12969. return;
  12970. }
  12971. this._currentEffect = null;
  12972. // 6/8/2017: deltakosh: Should not be required anymore.
  12973. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12974. if (bruteForce) {
  12975. this.resetTextureCache();
  12976. this._currentProgram = null;
  12977. this._stencilState.reset();
  12978. this._depthCullingState.reset();
  12979. this.setDepthFunctionToLessOrEqual();
  12980. this._alphaState.reset();
  12981. }
  12982. this._resetVertexBufferBinding();
  12983. this._cachedIndexBuffer = null;
  12984. this._cachedEffectForVertexBuffers = null;
  12985. this._unbindVertexArrayObject();
  12986. this.bindIndexBuffer(null);
  12987. };
  12988. /**
  12989. * Set the compressed texture format to use, based on the formats you have, and the formats
  12990. * supported by the hardware / browser.
  12991. *
  12992. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12993. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12994. * to API arguments needed to compressed textures. This puts the burden on the container
  12995. * generator to house the arcane code for determining these for current & future formats.
  12996. *
  12997. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12998. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12999. *
  13000. * Note: The result of this call is not taken into account when a texture is base64.
  13001. *
  13002. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13003. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13004. *
  13005. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13006. * @returns The extension selected.
  13007. */
  13008. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13009. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13010. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13011. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13012. return this._textureFormatInUse = this._texturesSupported[i];
  13013. }
  13014. }
  13015. }
  13016. // actively set format to nothing, to allow this to be called more than once
  13017. // and possibly fail the 2nd time
  13018. this._textureFormatInUse = null;
  13019. return null;
  13020. };
  13021. Engine.prototype._createTexture = function () {
  13022. var texture = this._gl.createTexture();
  13023. if (!texture) {
  13024. throw new Error("Unable to create texture");
  13025. }
  13026. return texture;
  13027. };
  13028. /**
  13029. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13030. * @param {string} urlArg- This contains one of the following:
  13031. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13032. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13033. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13034. *
  13035. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13036. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13037. * @param {Scene} scene- Needed for loading to the correct scene.
  13038. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13039. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13040. * @param {callback} onError- Optional callback to be called upon failure.
  13041. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13042. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13043. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13044. *
  13045. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13046. */
  13047. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13048. var _this = this;
  13049. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13050. if (onLoad === void 0) { onLoad = null; }
  13051. if (onError === void 0) { onError = null; }
  13052. if (buffer === void 0) { buffer = null; }
  13053. if (fallBack === void 0) { fallBack = null; }
  13054. if (format === void 0) { format = null; }
  13055. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13056. var fromData = url.substr(0, 5) === "data:";
  13057. var fromBlob = url.substr(0, 5) === "blob:";
  13058. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13059. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13060. // establish the file extension, if possible
  13061. var lastDot = url.lastIndexOf('.');
  13062. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13063. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13064. var isTGA = (extension.indexOf(".tga") === 0);
  13065. // determine if a ktx file should be substituted
  13066. var isKTX = false;
  13067. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13068. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13069. isKTX = true;
  13070. }
  13071. if (scene) {
  13072. scene._addPendingData(texture);
  13073. }
  13074. texture.url = url;
  13075. texture.generateMipMaps = !noMipmap;
  13076. texture.samplingMode = samplingMode;
  13077. texture.invertY = invertY;
  13078. if (!this._doNotHandleContextLost) {
  13079. // Keep a link to the buffer only if we plan to handle context lost
  13080. texture._buffer = buffer;
  13081. }
  13082. var onLoadObserver = null;
  13083. if (onLoad && !fallBack) {
  13084. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13085. }
  13086. if (!fallBack)
  13087. this._internalTexturesCache.push(texture);
  13088. var onerror = function (message, exception) {
  13089. if (scene) {
  13090. scene._removePendingData(texture);
  13091. }
  13092. if (onLoadObserver) {
  13093. texture.onLoadedObservable.remove(onLoadObserver);
  13094. }
  13095. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13096. if (isKTX) {
  13097. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13098. }
  13099. else if (BABYLON.Tools.UseFallbackTexture) {
  13100. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13101. }
  13102. if (onError) {
  13103. onError(message || "Unknown error", exception);
  13104. }
  13105. };
  13106. var callback = null;
  13107. // processing for non-image formats
  13108. if (isKTX || isTGA || isDDS) {
  13109. if (isKTX) {
  13110. callback = function (data) {
  13111. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13112. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13113. ktx.uploadLevels(_this._gl, !noMipmap);
  13114. return false;
  13115. }, samplingMode);
  13116. };
  13117. }
  13118. else if (isTGA) {
  13119. callback = function (arrayBuffer) {
  13120. var data = new Uint8Array(arrayBuffer);
  13121. var header = BABYLON.TGATools.GetTGAHeader(data);
  13122. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13123. BABYLON.TGATools.UploadContent(_this._gl, data);
  13124. return false;
  13125. }, samplingMode);
  13126. };
  13127. }
  13128. else if (isDDS) {
  13129. callback = function (data) {
  13130. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13131. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13132. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13133. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13134. return false;
  13135. }, samplingMode);
  13136. };
  13137. }
  13138. if (!buffer) {
  13139. this._loadFile(url, function (data) {
  13140. if (callback) {
  13141. callback(data);
  13142. }
  13143. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13144. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13145. });
  13146. }
  13147. else {
  13148. if (callback) {
  13149. callback(buffer);
  13150. }
  13151. }
  13152. // image format processing
  13153. }
  13154. else {
  13155. var onload = function (img) {
  13156. if (fromBlob && !_this._doNotHandleContextLost) {
  13157. // We need to store the image if we need to rebuild the texture
  13158. // in case of a webgl context lost
  13159. texture._buffer = img;
  13160. }
  13161. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13162. var gl = _this._gl;
  13163. var isPot = (img.width === potWidth && img.height === potHeight);
  13164. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13165. if (isPot) {
  13166. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13167. return false;
  13168. }
  13169. // Using shaders to rescale because canvas.drawImage is lossy
  13170. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13171. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13172. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13173. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13174. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13175. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13176. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13177. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13178. _this._releaseTexture(source);
  13179. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13180. continuationCallback();
  13181. });
  13182. return true;
  13183. }, samplingMode);
  13184. };
  13185. if (!fromData || isBase64)
  13186. if (buffer instanceof HTMLImageElement) {
  13187. onload(buffer);
  13188. }
  13189. else {
  13190. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13191. }
  13192. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13193. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13194. else
  13195. onload(buffer);
  13196. }
  13197. return texture;
  13198. };
  13199. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13200. var _this = this;
  13201. var rtt = this.createRenderTargetTexture({
  13202. width: destination.width,
  13203. height: destination.height,
  13204. }, {
  13205. generateMipMaps: false,
  13206. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13207. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13208. generateDepthBuffer: false,
  13209. generateStencilBuffer: false
  13210. });
  13211. if (!this._rescalePostProcess) {
  13212. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13213. }
  13214. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13215. _this._rescalePostProcess.onApply = function (effect) {
  13216. effect._bindTexture("textureSampler", source);
  13217. };
  13218. var hostingScene = scene;
  13219. if (!hostingScene) {
  13220. hostingScene = _this.scenes[_this.scenes.length - 1];
  13221. }
  13222. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13223. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13224. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13225. _this.unBindFramebuffer(rtt);
  13226. _this._releaseTexture(rtt);
  13227. if (onComplete) {
  13228. onComplete();
  13229. }
  13230. });
  13231. };
  13232. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13233. if (compression === void 0) { compression = null; }
  13234. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13235. if (!texture) {
  13236. return;
  13237. }
  13238. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13239. var internalFormat = this._getInternalFormat(format);
  13240. var textureType = this._getWebGLTextureType(type);
  13241. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13242. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13243. if (!this._doNotHandleContextLost) {
  13244. texture._bufferView = data;
  13245. texture.format = format;
  13246. texture.type = type;
  13247. texture.invertY = invertY;
  13248. texture._compression = compression;
  13249. }
  13250. if (texture.width % 4 !== 0) {
  13251. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13252. }
  13253. if (compression && data) {
  13254. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13255. }
  13256. else {
  13257. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13258. }
  13259. if (texture.generateMipMaps) {
  13260. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13261. }
  13262. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13263. // this.resetTextureCache();
  13264. texture.isReady = true;
  13265. };
  13266. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13267. if (compression === void 0) { compression = null; }
  13268. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13269. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13270. texture.baseWidth = width;
  13271. texture.baseHeight = height;
  13272. texture.width = width;
  13273. texture.height = height;
  13274. texture.format = format;
  13275. texture.generateMipMaps = generateMipMaps;
  13276. texture.samplingMode = samplingMode;
  13277. texture.invertY = invertY;
  13278. texture._compression = compression;
  13279. texture.type = type;
  13280. if (!this._doNotHandleContextLost) {
  13281. texture._bufferView = data;
  13282. }
  13283. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13284. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13285. // Filters
  13286. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13287. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13288. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13289. if (generateMipMaps) {
  13290. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13291. }
  13292. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13293. this._internalTexturesCache.push(texture);
  13294. return texture;
  13295. };
  13296. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13297. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13298. texture.baseWidth = width;
  13299. texture.baseHeight = height;
  13300. if (generateMipMaps) {
  13301. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13302. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13303. }
  13304. // this.resetTextureCache();
  13305. texture.width = width;
  13306. texture.height = height;
  13307. texture.isReady = false;
  13308. texture.generateMipMaps = generateMipMaps;
  13309. texture.samplingMode = samplingMode;
  13310. this.updateTextureSamplingMode(samplingMode, texture);
  13311. this._internalTexturesCache.push(texture);
  13312. return texture;
  13313. };
  13314. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13315. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13316. if (texture.isCube) {
  13317. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13318. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13319. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13320. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13321. }
  13322. else if (texture.is3D) {
  13323. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13324. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13325. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13326. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13327. }
  13328. else {
  13329. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13330. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13331. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13332. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13333. }
  13334. texture.samplingMode = samplingMode;
  13335. };
  13336. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13337. if (premulAlpha === void 0) { premulAlpha = false; }
  13338. if (!texture) {
  13339. return;
  13340. }
  13341. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13342. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13343. if (premulAlpha) {
  13344. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13345. }
  13346. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13347. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13348. if (texture.generateMipMaps) {
  13349. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13350. }
  13351. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13352. if (premulAlpha) {
  13353. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13354. }
  13355. texture.isReady = true;
  13356. };
  13357. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13358. if (!texture || texture._isDisabled) {
  13359. return;
  13360. }
  13361. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13362. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13363. try {
  13364. // Testing video texture support
  13365. if (this._videoTextureSupported === undefined) {
  13366. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13367. if (this._gl.getError() !== 0) {
  13368. this._videoTextureSupported = false;
  13369. }
  13370. else {
  13371. this._videoTextureSupported = true;
  13372. }
  13373. }
  13374. // Copy video through the current working canvas if video texture is not supported
  13375. if (!this._videoTextureSupported) {
  13376. if (!texture._workingCanvas) {
  13377. texture._workingCanvas = document.createElement("canvas");
  13378. var context = texture._workingCanvas.getContext("2d");
  13379. if (!context) {
  13380. throw new Error("Unable to get 2d context");
  13381. }
  13382. texture._workingContext = context;
  13383. texture._workingCanvas.width = texture.width;
  13384. texture._workingCanvas.height = texture.height;
  13385. }
  13386. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13387. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13388. }
  13389. else {
  13390. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13391. }
  13392. if (texture.generateMipMaps) {
  13393. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13394. }
  13395. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13396. // this.resetTextureCache();
  13397. texture.isReady = true;
  13398. }
  13399. catch (ex) {
  13400. // Something unexpected
  13401. // Let's disable the texture
  13402. texture._isDisabled = true;
  13403. }
  13404. };
  13405. /**
  13406. * Updates a depth texture Comparison Mode and Function.
  13407. * If the comparison Function is equal to 0, the mode will be set to none.
  13408. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13409. * @param texture The texture to set the comparison function for
  13410. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13411. */
  13412. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13413. if (this.webGLVersion === 1) {
  13414. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13415. return;
  13416. }
  13417. var gl = this._gl;
  13418. if (texture.isCube) {
  13419. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13420. if (comparisonFunction === 0) {
  13421. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13423. }
  13424. else {
  13425. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13426. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13427. }
  13428. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13429. }
  13430. else {
  13431. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13432. if (comparisonFunction === 0) {
  13433. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13434. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13435. }
  13436. else {
  13437. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13438. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13439. }
  13440. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13441. }
  13442. texture._comparisonFunction = comparisonFunction;
  13443. };
  13444. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13445. var width = size.width || size;
  13446. var height = size.height || size;
  13447. internalTexture.baseWidth = width;
  13448. internalTexture.baseHeight = height;
  13449. internalTexture.width = width;
  13450. internalTexture.height = height;
  13451. internalTexture.isReady = true;
  13452. internalTexture.samples = 1;
  13453. internalTexture.generateMipMaps = false;
  13454. internalTexture._generateDepthBuffer = true;
  13455. internalTexture._generateStencilBuffer = generateStencil;
  13456. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13457. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13458. internalTexture._comparisonFunction = comparisonFunction;
  13459. var gl = this._gl;
  13460. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13461. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13462. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13463. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13464. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13465. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13466. if (comparisonFunction === 0) {
  13467. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13468. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13469. }
  13470. else {
  13471. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13472. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13473. }
  13474. };
  13475. /**
  13476. * Creates a depth stencil texture.
  13477. * This is only available in WebGL 2 or with the depth texture extension available.
  13478. * @param size The size of face edge in the texture.
  13479. * @param options The options defining the texture.
  13480. * @returns The texture
  13481. */
  13482. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13483. if (options.isCube) {
  13484. var width = size.width || size;
  13485. return this._createDepthStencilCubeTexture(width, options);
  13486. }
  13487. else {
  13488. return this._createDepthStencilTexture(size, options);
  13489. }
  13490. };
  13491. /**
  13492. * Creates a depth stencil texture.
  13493. * This is only available in WebGL 2 or with the depth texture extension available.
  13494. * @param size The size of face edge in the texture.
  13495. * @param options The options defining the texture.
  13496. * @returns The texture
  13497. */
  13498. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13499. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13500. if (!this._caps.depthTextureExtension) {
  13501. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13502. return internalTexture;
  13503. }
  13504. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13505. var gl = this._gl;
  13506. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13507. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13508. if (this.webGLVersion > 1) {
  13509. if (internalOptions.generateStencil) {
  13510. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13511. }
  13512. else {
  13513. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13514. }
  13515. }
  13516. else {
  13517. if (internalOptions.generateStencil) {
  13518. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13519. }
  13520. else {
  13521. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13522. }
  13523. }
  13524. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13525. return internalTexture;
  13526. };
  13527. /**
  13528. * Creates a depth stencil cube texture.
  13529. * This is only available in WebGL 2.
  13530. * @param size The size of face edge in the cube texture.
  13531. * @param options The options defining the cube texture.
  13532. * @returns The cube texture
  13533. */
  13534. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13535. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13536. internalTexture.isCube = true;
  13537. if (this.webGLVersion === 1) {
  13538. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13539. return internalTexture;
  13540. }
  13541. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13542. var gl = this._gl;
  13543. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13544. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13545. // Create the depth/stencil buffer
  13546. for (var face = 0; face < 6; face++) {
  13547. if (internalOptions.generateStencil) {
  13548. 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);
  13549. }
  13550. else {
  13551. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13552. }
  13553. }
  13554. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13555. return internalTexture;
  13556. };
  13557. /**
  13558. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13559. * @param renderTarget The render target to set the frame buffer for
  13560. */
  13561. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13562. // Create the framebuffer
  13563. var internalTexture = renderTarget.getInternalTexture();
  13564. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13565. return;
  13566. }
  13567. var gl = this._gl;
  13568. var depthStencilTexture = renderTarget.depthStencilTexture;
  13569. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13570. if (depthStencilTexture.isCube) {
  13571. if (depthStencilTexture._generateStencilBuffer) {
  13572. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13573. }
  13574. else {
  13575. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13576. }
  13577. }
  13578. else {
  13579. if (depthStencilTexture._generateStencilBuffer) {
  13580. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13581. }
  13582. else {
  13583. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13584. }
  13585. }
  13586. this.bindUnboundFramebuffer(null);
  13587. };
  13588. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13589. var fullOptions = new RenderTargetCreationOptions();
  13590. if (options !== undefined && typeof options === "object") {
  13591. fullOptions.generateMipMaps = options.generateMipMaps;
  13592. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13593. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13594. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13595. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13596. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13597. }
  13598. else {
  13599. fullOptions.generateMipMaps = options;
  13600. fullOptions.generateDepthBuffer = true;
  13601. fullOptions.generateStencilBuffer = false;
  13602. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13603. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13604. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13605. }
  13606. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13607. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13608. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13609. }
  13610. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13611. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13612. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13613. }
  13614. var gl = this._gl;
  13615. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13616. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13617. var width = size.width || size;
  13618. var height = size.height || size;
  13619. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13620. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13621. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13622. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13623. }
  13624. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13625. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13626. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13627. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13628. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13629. // Create the framebuffer
  13630. var framebuffer = gl.createFramebuffer();
  13631. this.bindUnboundFramebuffer(framebuffer);
  13632. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13633. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13634. if (fullOptions.generateMipMaps) {
  13635. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13636. }
  13637. // Unbind
  13638. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13639. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13640. this.bindUnboundFramebuffer(null);
  13641. texture._framebuffer = framebuffer;
  13642. texture.baseWidth = width;
  13643. texture.baseHeight = height;
  13644. texture.width = width;
  13645. texture.height = height;
  13646. texture.isReady = true;
  13647. texture.samples = 1;
  13648. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13649. texture.samplingMode = fullOptions.samplingMode;
  13650. texture.type = fullOptions.type;
  13651. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13652. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13653. // this.resetTextureCache();
  13654. this._internalTexturesCache.push(texture);
  13655. return texture;
  13656. };
  13657. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13658. var generateMipMaps = false;
  13659. var generateDepthBuffer = true;
  13660. var generateStencilBuffer = false;
  13661. var generateDepthTexture = false;
  13662. var textureCount = 1;
  13663. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13664. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13665. var types = [], samplingModes = [];
  13666. if (options !== undefined) {
  13667. generateMipMaps = options.generateMipMaps;
  13668. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13669. generateStencilBuffer = options.generateStencilBuffer;
  13670. generateDepthTexture = options.generateDepthTexture;
  13671. textureCount = options.textureCount || 1;
  13672. if (options.types) {
  13673. types = options.types;
  13674. }
  13675. if (options.samplingModes) {
  13676. samplingModes = options.samplingModes;
  13677. }
  13678. }
  13679. var gl = this._gl;
  13680. // Create the framebuffer
  13681. var framebuffer = gl.createFramebuffer();
  13682. this.bindUnboundFramebuffer(framebuffer);
  13683. var width = size.width || size;
  13684. var height = size.height || size;
  13685. var textures = [];
  13686. var attachments = [];
  13687. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13688. for (var i = 0; i < textureCount; i++) {
  13689. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13690. var type = types[i] || defaultType;
  13691. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13692. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13693. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13694. }
  13695. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13696. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13697. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13698. }
  13699. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13700. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13701. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13702. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13703. }
  13704. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13705. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13706. textures.push(texture);
  13707. attachments.push(attachment);
  13708. gl.activeTexture(gl["TEXTURE" + i]);
  13709. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13710. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13711. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13712. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13713. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13714. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13715. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13716. if (generateMipMaps) {
  13717. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13718. }
  13719. // Unbind
  13720. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13721. texture._framebuffer = framebuffer;
  13722. texture._depthStencilBuffer = depthStencilBuffer;
  13723. texture.baseWidth = width;
  13724. texture.baseHeight = height;
  13725. texture.width = width;
  13726. texture.height = height;
  13727. texture.isReady = true;
  13728. texture.samples = 1;
  13729. texture.generateMipMaps = generateMipMaps;
  13730. texture.samplingMode = samplingMode;
  13731. texture.type = type;
  13732. texture._generateDepthBuffer = generateDepthBuffer;
  13733. texture._generateStencilBuffer = generateStencilBuffer;
  13734. texture._attachments = attachments;
  13735. this._internalTexturesCache.push(texture);
  13736. }
  13737. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13738. // Depth texture
  13739. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13740. gl.activeTexture(gl.TEXTURE0);
  13741. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13742. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13743. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13744. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13745. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13746. 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);
  13747. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13748. depthTexture._framebuffer = framebuffer;
  13749. depthTexture.baseWidth = width;
  13750. depthTexture.baseHeight = height;
  13751. depthTexture.width = width;
  13752. depthTexture.height = height;
  13753. depthTexture.isReady = true;
  13754. depthTexture.samples = 1;
  13755. depthTexture.generateMipMaps = generateMipMaps;
  13756. depthTexture.samplingMode = gl.NEAREST;
  13757. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13758. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13759. textures.push(depthTexture);
  13760. this._internalTexturesCache.push(depthTexture);
  13761. }
  13762. gl.drawBuffers(attachments);
  13763. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13764. this.bindUnboundFramebuffer(null);
  13765. this.resetTextureCache();
  13766. return textures;
  13767. };
  13768. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13769. if (samples === void 0) { samples = 1; }
  13770. var depthStencilBuffer = null;
  13771. var gl = this._gl;
  13772. // Create the depth/stencil buffer
  13773. if (generateStencilBuffer) {
  13774. depthStencilBuffer = gl.createRenderbuffer();
  13775. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13776. if (samples > 1) {
  13777. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13778. }
  13779. else {
  13780. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13781. }
  13782. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13783. }
  13784. else if (generateDepthBuffer) {
  13785. depthStencilBuffer = gl.createRenderbuffer();
  13786. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13787. if (samples > 1) {
  13788. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13789. }
  13790. else {
  13791. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13792. }
  13793. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13794. }
  13795. return depthStencilBuffer;
  13796. };
  13797. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13798. if (this.webGLVersion < 2 || !texture) {
  13799. return 1;
  13800. }
  13801. if (texture.samples === samples) {
  13802. return samples;
  13803. }
  13804. var gl = this._gl;
  13805. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13806. // Dispose previous render buffers
  13807. if (texture._depthStencilBuffer) {
  13808. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13809. texture._depthStencilBuffer = null;
  13810. }
  13811. if (texture._MSAAFramebuffer) {
  13812. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13813. texture._MSAAFramebuffer = null;
  13814. }
  13815. if (texture._MSAARenderBuffer) {
  13816. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13817. texture._MSAARenderBuffer = null;
  13818. }
  13819. if (samples > 1) {
  13820. var framebuffer = gl.createFramebuffer();
  13821. if (!framebuffer) {
  13822. throw new Error("Unable to create multi sampled framebuffer");
  13823. }
  13824. texture._MSAAFramebuffer = framebuffer;
  13825. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13826. var colorRenderbuffer = gl.createRenderbuffer();
  13827. if (!colorRenderbuffer) {
  13828. throw new Error("Unable to create multi sampled framebuffer");
  13829. }
  13830. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13831. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13832. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13833. texture._MSAARenderBuffer = colorRenderbuffer;
  13834. }
  13835. else {
  13836. this.bindUnboundFramebuffer(texture._framebuffer);
  13837. }
  13838. texture.samples = samples;
  13839. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13840. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13841. this.bindUnboundFramebuffer(null);
  13842. return samples;
  13843. };
  13844. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13845. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13846. return 1;
  13847. }
  13848. if (textures[0].samples === samples) {
  13849. return samples;
  13850. }
  13851. var gl = this._gl;
  13852. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13853. // Dispose previous render buffers
  13854. if (textures[0]._depthStencilBuffer) {
  13855. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13856. textures[0]._depthStencilBuffer = null;
  13857. }
  13858. if (textures[0]._MSAAFramebuffer) {
  13859. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13860. textures[0]._MSAAFramebuffer = null;
  13861. }
  13862. for (var i = 0; i < textures.length; i++) {
  13863. if (textures[i]._MSAARenderBuffer) {
  13864. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13865. textures[i]._MSAARenderBuffer = null;
  13866. }
  13867. }
  13868. if (samples > 1) {
  13869. var framebuffer = gl.createFramebuffer();
  13870. if (!framebuffer) {
  13871. throw new Error("Unable to create multi sampled framebuffer");
  13872. }
  13873. this.bindUnboundFramebuffer(framebuffer);
  13874. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13875. var attachments = [];
  13876. for (var i = 0; i < textures.length; i++) {
  13877. var texture = textures[i];
  13878. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13879. var colorRenderbuffer = gl.createRenderbuffer();
  13880. if (!colorRenderbuffer) {
  13881. throw new Error("Unable to create multi sampled framebuffer");
  13882. }
  13883. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13884. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13885. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13886. texture._MSAAFramebuffer = framebuffer;
  13887. texture._MSAARenderBuffer = colorRenderbuffer;
  13888. texture.samples = samples;
  13889. texture._depthStencilBuffer = depthStencilBuffer;
  13890. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13891. attachments.push(attachment);
  13892. }
  13893. gl.drawBuffers(attachments);
  13894. }
  13895. else {
  13896. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13897. }
  13898. this.bindUnboundFramebuffer(null);
  13899. return samples;
  13900. };
  13901. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13902. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13903. };
  13904. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13905. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13906. };
  13907. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13908. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  13909. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13910. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13911. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13912. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13913. }
  13914. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13915. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13916. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13917. }
  13918. var gl = this._gl;
  13919. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13920. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13921. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13922. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13923. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13924. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13925. }
  13926. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13927. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13928. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13929. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13930. for (var face = 0; face < 6; face++) {
  13931. 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);
  13932. }
  13933. // Create the framebuffer
  13934. var framebuffer = gl.createFramebuffer();
  13935. this.bindUnboundFramebuffer(framebuffer);
  13936. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13937. // MipMaps
  13938. if (fullOptions.generateMipMaps) {
  13939. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13940. }
  13941. // Unbind
  13942. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13943. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13944. this.bindUnboundFramebuffer(null);
  13945. texture._framebuffer = framebuffer;
  13946. texture.width = size;
  13947. texture.height = size;
  13948. texture.isReady = true;
  13949. texture.isCube = true;
  13950. texture.samples = 1;
  13951. texture.generateMipMaps = fullOptions.generateMipMaps;
  13952. texture.samplingMode = fullOptions.samplingMode;
  13953. texture.type = fullOptions.type;
  13954. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13955. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13956. this._internalTexturesCache.push(texture);
  13957. return texture;
  13958. };
  13959. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13960. var _this = this;
  13961. if (onLoad === void 0) { onLoad = null; }
  13962. if (onError === void 0) { onError = null; }
  13963. if (forcedExtension === void 0) { forcedExtension = null; }
  13964. var callback = function (loadData) {
  13965. if (!loadData) {
  13966. if (onLoad) {
  13967. onLoad(null);
  13968. }
  13969. return;
  13970. }
  13971. var texture = loadData.texture;
  13972. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13973. texture._lodGenerationScale = scale;
  13974. texture._lodGenerationOffset = offset;
  13975. if (_this._caps.textureLOD) {
  13976. // Do not add extra process if texture lod is supported.
  13977. if (onLoad) {
  13978. onLoad(texture);
  13979. }
  13980. return;
  13981. }
  13982. var mipSlices = 3;
  13983. var gl = _this._gl;
  13984. var width = loadData.width;
  13985. if (!width) {
  13986. return;
  13987. }
  13988. var textures = [];
  13989. for (var i = 0; i < mipSlices; i++) {
  13990. //compute LOD from even spacing in smoothness (matching shader calculation)
  13991. var smoothness = i / (mipSlices - 1);
  13992. var roughness = 1 - smoothness;
  13993. var minLODIndex = offset; // roughness = 0
  13994. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13995. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13996. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13997. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13998. glTextureFromLod.isCube = true;
  13999. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14000. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14001. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14002. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14003. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14004. if (loadData.isDDS) {
  14005. var info = loadData.info;
  14006. var data = loadData.data;
  14007. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14008. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14009. }
  14010. else {
  14011. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14012. }
  14013. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14014. // Wrap in a base texture for easy binding.
  14015. var lodTexture = new BABYLON.BaseTexture(scene);
  14016. lodTexture.isCube = true;
  14017. lodTexture._texture = glTextureFromLod;
  14018. glTextureFromLod.isReady = true;
  14019. textures.push(lodTexture);
  14020. }
  14021. texture._lodTextureHigh = textures[2];
  14022. texture._lodTextureMid = textures[1];
  14023. texture._lodTextureLow = textures[0];
  14024. if (onLoad) {
  14025. onLoad(texture);
  14026. }
  14027. };
  14028. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14029. };
  14030. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14031. var _this = this;
  14032. if (onLoad === void 0) { onLoad = null; }
  14033. if (onError === void 0) { onError = null; }
  14034. if (forcedExtension === void 0) { forcedExtension = null; }
  14035. var gl = this._gl;
  14036. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14037. texture.isCube = true;
  14038. texture.url = rootUrl;
  14039. texture.generateMipMaps = !noMipmap;
  14040. if (!this._doNotHandleContextLost) {
  14041. texture._extension = forcedExtension;
  14042. texture._files = files;
  14043. }
  14044. var isKTX = false;
  14045. var isDDS = false;
  14046. var lastDot = rootUrl.lastIndexOf('.');
  14047. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14048. if (this._textureFormatInUse) {
  14049. extension = this._textureFormatInUse;
  14050. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14051. isKTX = true;
  14052. }
  14053. else {
  14054. isDDS = (extension === ".dds");
  14055. }
  14056. var onerror = function (request, exception) {
  14057. if (onError && request) {
  14058. onError(request.status + " " + request.statusText, exception);
  14059. }
  14060. };
  14061. if (isKTX) {
  14062. this._loadFile(rootUrl, function (data) {
  14063. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14064. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14065. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14066. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14067. ktx.uploadLevels(_this._gl, !noMipmap);
  14068. _this.setCubeMapTextureParams(gl, loadMipmap);
  14069. texture.width = ktx.pixelWidth;
  14070. texture.height = ktx.pixelHeight;
  14071. texture.isReady = true;
  14072. }, undefined, undefined, true, onerror);
  14073. }
  14074. else if (isDDS) {
  14075. if (files && files.length === 6) {
  14076. this._cascadeLoadFiles(scene, function (imgs) {
  14077. var info;
  14078. var loadMipmap = false;
  14079. var width = 0;
  14080. for (var index = 0; index < imgs.length; index++) {
  14081. var data = imgs[index];
  14082. info = BABYLON.DDSTools.GetDDSInfo(data);
  14083. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14084. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14085. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14086. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14087. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14088. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14089. }
  14090. texture.width = info.width;
  14091. texture.height = info.height;
  14092. texture.type = info.textureType;
  14093. width = info.width;
  14094. }
  14095. _this.setCubeMapTextureParams(gl, loadMipmap);
  14096. texture.isReady = true;
  14097. if (onLoad) {
  14098. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14099. }
  14100. }, files, onError);
  14101. }
  14102. else {
  14103. this._loadFile(rootUrl, function (data) {
  14104. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14105. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14106. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14107. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14108. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14109. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14110. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14111. }
  14112. _this.setCubeMapTextureParams(gl, loadMipmap);
  14113. texture.width = info.width;
  14114. texture.height = info.height;
  14115. texture.isReady = true;
  14116. texture.type = info.textureType;
  14117. if (onLoad) {
  14118. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14119. }
  14120. }, undefined, undefined, true, onerror);
  14121. }
  14122. }
  14123. else {
  14124. if (!files) {
  14125. throw new Error("Cannot load cubemap because files were not defined");
  14126. }
  14127. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14128. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14129. var height = width;
  14130. _this._prepareWorkingCanvas();
  14131. if (!_this._workingCanvas || !_this._workingContext) {
  14132. return;
  14133. }
  14134. _this._workingCanvas.width = width;
  14135. _this._workingCanvas.height = height;
  14136. var faces = [
  14137. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14138. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14139. ];
  14140. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14141. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14142. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14143. for (var index = 0; index < faces.length; index++) {
  14144. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14145. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14146. }
  14147. if (!noMipmap) {
  14148. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14149. }
  14150. _this.setCubeMapTextureParams(gl, !noMipmap);
  14151. texture.width = width;
  14152. texture.height = height;
  14153. texture.isReady = true;
  14154. if (format) {
  14155. texture.format = format;
  14156. }
  14157. texture.onLoadedObservable.notifyObservers(texture);
  14158. texture.onLoadedObservable.clear();
  14159. if (onLoad) {
  14160. onLoad();
  14161. }
  14162. }, files, onError);
  14163. }
  14164. this._internalTexturesCache.push(texture);
  14165. return texture;
  14166. };
  14167. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14168. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14169. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14170. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14171. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14172. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14173. // this.resetTextureCache();
  14174. };
  14175. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14176. if (compression === void 0) { compression = null; }
  14177. if (level === void 0) { level = 0; }
  14178. texture._bufferViewArray = data;
  14179. texture.format = format;
  14180. texture.type = type;
  14181. texture.invertY = invertY;
  14182. texture._compression = compression;
  14183. var gl = this._gl;
  14184. var textureType = this._getWebGLTextureType(type);
  14185. var internalFormat = this._getInternalFormat(format);
  14186. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14187. var needConversion = false;
  14188. if (internalFormat === gl.RGB) {
  14189. internalFormat = gl.RGBA;
  14190. needConversion = true;
  14191. }
  14192. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14193. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14194. if (texture.width % 4 !== 0) {
  14195. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14196. }
  14197. // Data are known to be in +X +Y +Z -X -Y -Z
  14198. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14199. var faceData = data[faceIndex];
  14200. if (compression) {
  14201. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14202. }
  14203. else {
  14204. if (needConversion) {
  14205. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14206. }
  14207. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14208. }
  14209. }
  14210. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14211. if (isPot && texture.generateMipMaps && level === 0) {
  14212. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14213. }
  14214. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14215. // this.resetTextureCache();
  14216. texture.isReady = true;
  14217. };
  14218. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14219. if (compression === void 0) { compression = null; }
  14220. var gl = this._gl;
  14221. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14222. texture.isCube = true;
  14223. texture.generateMipMaps = generateMipMaps;
  14224. texture.format = format;
  14225. texture.type = type;
  14226. if (!this._doNotHandleContextLost) {
  14227. texture._bufferViewArray = data;
  14228. }
  14229. var textureType = this._getWebGLTextureType(type);
  14230. var internalFormat = this._getInternalFormat(format);
  14231. if (internalFormat === gl.RGB) {
  14232. internalFormat = gl.RGBA;
  14233. }
  14234. var width = size;
  14235. var height = width;
  14236. texture.width = width;
  14237. texture.height = height;
  14238. // Double check on POT to generate Mips.
  14239. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14240. if (!isPot) {
  14241. generateMipMaps = false;
  14242. }
  14243. // Upload data if needed. The texture won't be ready until then.
  14244. if (data) {
  14245. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14246. }
  14247. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14248. // Filters
  14249. if (data && generateMipMaps) {
  14250. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14251. }
  14252. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14253. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14254. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14255. }
  14256. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14257. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14258. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14259. }
  14260. else {
  14261. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14262. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14263. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14264. }
  14265. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14266. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14267. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14268. return texture;
  14269. };
  14270. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14271. var _this = this;
  14272. if (onLoad === void 0) { onLoad = null; }
  14273. if (onError === void 0) { onError = null; }
  14274. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14275. if (invertY === void 0) { invertY = false; }
  14276. var gl = this._gl;
  14277. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14278. scene._addPendingData(texture);
  14279. texture.url = url;
  14280. this._internalTexturesCache.push(texture);
  14281. var onerror = function (request, exception) {
  14282. scene._removePendingData(texture);
  14283. if (onError && request) {
  14284. onError(request.status + " " + request.statusText, exception);
  14285. }
  14286. };
  14287. var internalCallback = function (data) {
  14288. var width = texture.width;
  14289. var faceDataArrays = callback(data);
  14290. if (!faceDataArrays) {
  14291. return;
  14292. }
  14293. if (mipmmapGenerator) {
  14294. var textureType = _this._getWebGLTextureType(type);
  14295. var internalFormat = _this._getInternalFormat(format);
  14296. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14297. var needConversion = false;
  14298. if (internalFormat === gl.RGB) {
  14299. internalFormat = gl.RGBA;
  14300. needConversion = true;
  14301. }
  14302. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14303. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14304. var mipData = mipmmapGenerator(faceDataArrays);
  14305. for (var level = 0; level < mipData.length; level++) {
  14306. var mipSize = width >> level;
  14307. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14308. var mipFaceData = mipData[level][faceIndex];
  14309. if (needConversion) {
  14310. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14311. }
  14312. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14313. }
  14314. }
  14315. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14316. }
  14317. else {
  14318. texture.generateMipMaps = !noMipmap;
  14319. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14320. }
  14321. texture.isReady = true;
  14322. // this.resetTextureCache();
  14323. scene._removePendingData(texture);
  14324. if (onLoad) {
  14325. onLoad();
  14326. }
  14327. };
  14328. this._loadFile(url, function (data) {
  14329. internalCallback(data);
  14330. }, undefined, scene.database, true, onerror);
  14331. return texture;
  14332. };
  14333. ;
  14334. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14335. if (compression === void 0) { compression = null; }
  14336. var internalFormat = this._getInternalFormat(format);
  14337. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14338. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14339. if (!this._doNotHandleContextLost) {
  14340. texture._bufferView = data;
  14341. texture.format = format;
  14342. texture.invertY = invertY;
  14343. texture._compression = compression;
  14344. }
  14345. if (texture.width % 4 !== 0) {
  14346. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14347. }
  14348. if (compression && data) {
  14349. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14350. }
  14351. else {
  14352. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14353. }
  14354. if (texture.generateMipMaps) {
  14355. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14356. }
  14357. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14358. // this.resetTextureCache();
  14359. texture.isReady = true;
  14360. };
  14361. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14362. if (compression === void 0) { compression = null; }
  14363. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14364. texture.baseWidth = width;
  14365. texture.baseHeight = height;
  14366. texture.baseDepth = depth;
  14367. texture.width = width;
  14368. texture.height = height;
  14369. texture.depth = depth;
  14370. texture.format = format;
  14371. texture.generateMipMaps = generateMipMaps;
  14372. texture.samplingMode = samplingMode;
  14373. texture.is3D = true;
  14374. if (!this._doNotHandleContextLost) {
  14375. texture._bufferView = data;
  14376. }
  14377. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14378. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14379. // Filters
  14380. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14381. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14382. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14383. if (generateMipMaps) {
  14384. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14385. }
  14386. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14387. this._internalTexturesCache.push(texture);
  14388. return texture;
  14389. };
  14390. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14391. var gl = this._gl;
  14392. if (!gl) {
  14393. return;
  14394. }
  14395. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14396. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14397. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14398. if (!noMipmap && !isCompressed) {
  14399. gl.generateMipmap(gl.TEXTURE_2D);
  14400. }
  14401. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14402. // this.resetTextureCache();
  14403. if (scene) {
  14404. scene._removePendingData(texture);
  14405. }
  14406. texture.onLoadedObservable.notifyObservers(texture);
  14407. texture.onLoadedObservable.clear();
  14408. };
  14409. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14410. var _this = this;
  14411. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14412. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14413. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14414. var gl = this._gl;
  14415. if (!gl) {
  14416. return;
  14417. }
  14418. if (!texture._webGLTexture) {
  14419. // this.resetTextureCache();
  14420. if (scene) {
  14421. scene._removePendingData(texture);
  14422. }
  14423. return;
  14424. }
  14425. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14426. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14427. texture.baseWidth = width;
  14428. texture.baseHeight = height;
  14429. texture.width = potWidth;
  14430. texture.height = potHeight;
  14431. texture.isReady = true;
  14432. if (processFunction(potWidth, potHeight, function () {
  14433. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14434. })) {
  14435. // Returning as texture needs extra async steps
  14436. return;
  14437. }
  14438. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14439. };
  14440. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14441. // Create new RGBA data container.
  14442. var rgbaData;
  14443. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14444. rgbaData = new Float32Array(width * height * 4);
  14445. }
  14446. else {
  14447. rgbaData = new Uint32Array(width * height * 4);
  14448. }
  14449. // Convert each pixel.
  14450. for (var x = 0; x < width; x++) {
  14451. for (var y = 0; y < height; y++) {
  14452. var index = (y * width + x) * 3;
  14453. var newIndex = (y * width + x) * 4;
  14454. // Map Old Value to new value.
  14455. rgbaData[newIndex + 0] = rgbData[index + 0];
  14456. rgbaData[newIndex + 1] = rgbData[index + 1];
  14457. rgbaData[newIndex + 2] = rgbData[index + 2];
  14458. // Add fully opaque alpha channel.
  14459. rgbaData[newIndex + 3] = 1;
  14460. }
  14461. }
  14462. return rgbaData;
  14463. };
  14464. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14465. var gl = this._gl;
  14466. if (texture._framebuffer) {
  14467. gl.deleteFramebuffer(texture._framebuffer);
  14468. texture._framebuffer = null;
  14469. }
  14470. if (texture._depthStencilBuffer) {
  14471. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14472. texture._depthStencilBuffer = null;
  14473. }
  14474. if (texture._MSAAFramebuffer) {
  14475. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14476. texture._MSAAFramebuffer = null;
  14477. }
  14478. if (texture._MSAARenderBuffer) {
  14479. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14480. texture._MSAARenderBuffer = null;
  14481. }
  14482. };
  14483. Engine.prototype._releaseTexture = function (texture) {
  14484. var gl = this._gl;
  14485. this._releaseFramebufferObjects(texture);
  14486. gl.deleteTexture(texture._webGLTexture);
  14487. // Unbind channels
  14488. this.unbindAllTextures();
  14489. var index = this._internalTexturesCache.indexOf(texture);
  14490. if (index !== -1) {
  14491. this._internalTexturesCache.splice(index, 1);
  14492. }
  14493. // Integrated fixed lod samplers.
  14494. if (texture._lodTextureHigh) {
  14495. texture._lodTextureHigh.dispose();
  14496. }
  14497. if (texture._lodTextureMid) {
  14498. texture._lodTextureMid.dispose();
  14499. }
  14500. if (texture._lodTextureLow) {
  14501. texture._lodTextureLow.dispose();
  14502. }
  14503. // Set output texture of post process to null if the texture has been released/disposed
  14504. this.scenes.forEach(function (scene) {
  14505. scene.postProcesses.forEach(function (postProcess) {
  14506. if (postProcess._outputTexture == texture) {
  14507. postProcess._outputTexture = null;
  14508. }
  14509. });
  14510. scene.cameras.forEach(function (camera) {
  14511. camera._postProcesses.forEach(function (postProcess) {
  14512. if (postProcess) {
  14513. if (postProcess._outputTexture == texture) {
  14514. postProcess._outputTexture = null;
  14515. }
  14516. }
  14517. });
  14518. });
  14519. });
  14520. };
  14521. Engine.prototype.setProgram = function (program) {
  14522. if (this._currentProgram !== program) {
  14523. this._gl.useProgram(program);
  14524. this._currentProgram = program;
  14525. }
  14526. };
  14527. Engine.prototype.bindSamplers = function (effect) {
  14528. this.setProgram(effect.getProgram());
  14529. var samplers = effect.getSamplers();
  14530. for (var index = 0; index < samplers.length; index++) {
  14531. var uniform = effect.getUniform(samplers[index]);
  14532. if (uniform) {
  14533. this._boundUniforms[index] = uniform;
  14534. }
  14535. }
  14536. this._currentEffect = null;
  14537. };
  14538. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14539. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14540. return;
  14541. }
  14542. // Remove
  14543. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14544. // Bind last to it
  14545. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14546. // Bind to dummy
  14547. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14548. };
  14549. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14550. if (!internalTexture) {
  14551. return -1;
  14552. }
  14553. internalTexture._initialSlot = channel;
  14554. if (this.disableTextureBindingOptimization) {
  14555. if (channel !== internalTexture._designatedSlot) {
  14556. this._textureCollisions.addCount(1, false);
  14557. }
  14558. }
  14559. else {
  14560. if (channel !== internalTexture._designatedSlot) {
  14561. if (internalTexture._designatedSlot > -1) {
  14562. return internalTexture._designatedSlot;
  14563. }
  14564. else {
  14565. // No slot for this texture, let's pick a new one (if we find a free slot)
  14566. if (this._nextFreeTextureSlots.length) {
  14567. return this._nextFreeTextureSlots[0];
  14568. }
  14569. // We need to recycle the oldest bound texture, sorry.
  14570. this._textureCollisions.addCount(1, false);
  14571. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14572. }
  14573. }
  14574. }
  14575. return channel;
  14576. };
  14577. Engine.prototype._linkTrackers = function (previous, next) {
  14578. previous.next = next;
  14579. next.previous = previous;
  14580. };
  14581. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14582. var currentSlot = internalTexture._designatedSlot;
  14583. if (currentSlot === -1) {
  14584. return -1;
  14585. }
  14586. internalTexture._designatedSlot = -1;
  14587. if (this.disableTextureBindingOptimization) {
  14588. return -1;
  14589. }
  14590. // Remove from bound list
  14591. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14592. // Free the slot
  14593. this._boundTexturesCache[currentSlot] = null;
  14594. this._nextFreeTextureSlots.push(currentSlot);
  14595. return currentSlot;
  14596. };
  14597. Engine.prototype._activateCurrentTexture = function () {
  14598. if (this._currentTextureChannel !== this._activeChannel) {
  14599. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14600. this._currentTextureChannel = this._activeChannel;
  14601. }
  14602. };
  14603. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14604. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14605. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14606. this._activeChannel = texture._designatedSlot;
  14607. }
  14608. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14609. var isTextureForRendering = texture && texture._initialSlot > -1;
  14610. if (currentTextureBound !== texture) {
  14611. if (currentTextureBound) {
  14612. this._removeDesignatedSlot(currentTextureBound);
  14613. }
  14614. this._activateCurrentTexture();
  14615. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14616. this._boundTexturesCache[this._activeChannel] = texture;
  14617. if (texture) {
  14618. if (!this.disableTextureBindingOptimization) {
  14619. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14620. if (slotIndex > -1) {
  14621. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14622. }
  14623. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14624. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14625. }
  14626. texture._designatedSlot = this._activeChannel;
  14627. }
  14628. }
  14629. else if (forTextureDataUpdate) {
  14630. this._activateCurrentTexture();
  14631. }
  14632. if (isTextureForRendering && !forTextureDataUpdate) {
  14633. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14634. }
  14635. };
  14636. Engine.prototype._bindTexture = function (channel, texture) {
  14637. if (channel < 0) {
  14638. return;
  14639. }
  14640. if (texture) {
  14641. channel = this._getCorrectTextureChannel(channel, texture);
  14642. }
  14643. this._activeChannel = channel;
  14644. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14645. };
  14646. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14647. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14648. };
  14649. /**
  14650. * Binds the output of the passed in post process to the texture channel specified
  14651. * @param channel The channel the texture should be bound to
  14652. * @param postProcess The post process which's output should be bound
  14653. */
  14654. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  14655. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  14656. };
  14657. Engine.prototype.unbindAllTextures = function () {
  14658. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14659. this._activeChannel = channel;
  14660. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14661. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14662. if (this.webGLVersion > 1) {
  14663. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14664. }
  14665. }
  14666. };
  14667. /**
  14668. * Sets a texture to the according uniform.
  14669. * @param channel The texture channel
  14670. * @param uniform The uniform to set
  14671. * @param texture The texture to apply
  14672. */
  14673. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14674. if (channel < 0) {
  14675. return;
  14676. }
  14677. if (uniform) {
  14678. this._boundUniforms[channel] = uniform;
  14679. }
  14680. this._setTexture(channel, texture);
  14681. };
  14682. /**
  14683. * Sets a depth stencil texture from a render target to the according uniform.
  14684. * @param channel The texture channel
  14685. * @param uniform The uniform to set
  14686. * @param texture The render target texture containing the depth stencil texture to apply
  14687. */
  14688. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14689. if (channel < 0) {
  14690. return;
  14691. }
  14692. if (uniform) {
  14693. this._boundUniforms[channel] = uniform;
  14694. }
  14695. if (!texture || !texture.depthStencilTexture) {
  14696. this._setTexture(channel, null);
  14697. }
  14698. else {
  14699. this._setTexture(channel, texture, false, true);
  14700. }
  14701. };
  14702. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14703. var uniform = this._boundUniforms[sourceSlot];
  14704. if (uniform._currentState === destination) {
  14705. return;
  14706. }
  14707. this._gl.uniform1i(uniform, destination);
  14708. uniform._currentState = destination;
  14709. };
  14710. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14711. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14712. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14713. // Not ready?
  14714. if (!texture) {
  14715. if (this._boundTexturesCache[channel] != null) {
  14716. this._activeChannel = channel;
  14717. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14718. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14719. if (this.webGLVersion > 1) {
  14720. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14721. }
  14722. }
  14723. return false;
  14724. }
  14725. // Video
  14726. if (texture.video) {
  14727. this._activeChannel = channel;
  14728. texture.update();
  14729. }
  14730. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14731. texture.delayLoad();
  14732. return false;
  14733. }
  14734. var internalTexture;
  14735. if (depthStencilTexture) {
  14736. internalTexture = texture.depthStencilTexture;
  14737. }
  14738. else if (texture.isReady()) {
  14739. internalTexture = texture.getInternalTexture();
  14740. }
  14741. else if (texture.isCube) {
  14742. internalTexture = this.emptyCubeTexture;
  14743. }
  14744. else if (texture.is3D) {
  14745. internalTexture = this.emptyTexture3D;
  14746. }
  14747. else {
  14748. internalTexture = this.emptyTexture;
  14749. }
  14750. if (!isPartOfTextureArray) {
  14751. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14752. }
  14753. if (this._boundTexturesCache[channel] === internalTexture) {
  14754. this._moveBoundTextureOnTop(internalTexture);
  14755. if (!isPartOfTextureArray) {
  14756. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14757. }
  14758. return false;
  14759. }
  14760. this._activeChannel = channel;
  14761. if (internalTexture && internalTexture.is3D) {
  14762. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14763. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14764. internalTexture._cachedWrapU = texture.wrapU;
  14765. switch (texture.wrapU) {
  14766. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14767. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14768. break;
  14769. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14770. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14771. break;
  14772. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14773. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14774. break;
  14775. }
  14776. }
  14777. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14778. internalTexture._cachedWrapV = texture.wrapV;
  14779. switch (texture.wrapV) {
  14780. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14781. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14782. break;
  14783. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14784. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14785. break;
  14786. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14787. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14788. break;
  14789. }
  14790. }
  14791. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14792. internalTexture._cachedWrapR = texture.wrapR;
  14793. switch (texture.wrapR) {
  14794. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14795. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14796. break;
  14797. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14798. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14799. break;
  14800. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14801. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14802. break;
  14803. }
  14804. }
  14805. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14806. }
  14807. else if (internalTexture && internalTexture.isCube) {
  14808. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14809. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14810. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14811. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14812. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14813. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14814. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14815. }
  14816. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14817. }
  14818. else {
  14819. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14820. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14821. internalTexture._cachedWrapU = texture.wrapU;
  14822. switch (texture.wrapU) {
  14823. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14824. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14825. break;
  14826. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14827. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14828. break;
  14829. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14830. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14831. break;
  14832. }
  14833. }
  14834. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14835. internalTexture._cachedWrapV = texture.wrapV;
  14836. switch (texture.wrapV) {
  14837. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14838. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14839. break;
  14840. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14841. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14842. break;
  14843. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14844. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14845. break;
  14846. }
  14847. }
  14848. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14849. }
  14850. return true;
  14851. };
  14852. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14853. if (channel < 0 || !uniform) {
  14854. return;
  14855. }
  14856. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14857. this._textureUnits = new Int32Array(textures.length);
  14858. }
  14859. for (var i = 0; i < textures.length; i++) {
  14860. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14861. }
  14862. this._gl.uniform1iv(uniform, this._textureUnits);
  14863. for (var index = 0; index < textures.length; index++) {
  14864. this._setTexture(this._textureUnits[index], textures[index], true);
  14865. }
  14866. };
  14867. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14868. var internalTexture = texture.getInternalTexture();
  14869. if (!internalTexture) {
  14870. return;
  14871. }
  14872. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14873. var value = texture.anisotropicFilteringLevel;
  14874. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14875. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14876. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14877. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14878. }
  14879. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14880. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14881. internalTexture._cachedAnisotropicFilteringLevel = value;
  14882. }
  14883. };
  14884. Engine.prototype.readPixels = function (x, y, width, height) {
  14885. var data = new Uint8Array(height * width * 4);
  14886. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14887. return data;
  14888. };
  14889. /**
  14890. * Add an externaly attached data from its key.
  14891. * This method call will fail and return false, if such key already exists.
  14892. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14893. * @param key the unique key that identifies the data
  14894. * @param data the data object to associate to the key for this Engine instance
  14895. * @return true if no such key were already present and the data was added successfully, false otherwise
  14896. */
  14897. Engine.prototype.addExternalData = function (key, data) {
  14898. if (!this._externalData) {
  14899. this._externalData = new BABYLON.StringDictionary();
  14900. }
  14901. return this._externalData.add(key, data);
  14902. };
  14903. /**
  14904. * Get an externaly attached data from its key
  14905. * @param key the unique key that identifies the data
  14906. * @return the associated data, if present (can be null), or undefined if not present
  14907. */
  14908. Engine.prototype.getExternalData = function (key) {
  14909. if (!this._externalData) {
  14910. this._externalData = new BABYLON.StringDictionary();
  14911. }
  14912. return this._externalData.get(key);
  14913. };
  14914. /**
  14915. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14916. * @param key the unique key that identifies the data
  14917. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14918. * @return the associated data, can be null if the factory returned null.
  14919. */
  14920. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14921. if (!this._externalData) {
  14922. this._externalData = new BABYLON.StringDictionary();
  14923. }
  14924. return this._externalData.getOrAddWithFactory(key, factory);
  14925. };
  14926. /**
  14927. * Remove an externaly attached data from the Engine instance
  14928. * @param key the unique key that identifies the data
  14929. * @return true if the data was successfully removed, false if it doesn't exist
  14930. */
  14931. Engine.prototype.removeExternalData = function (key) {
  14932. if (!this._externalData) {
  14933. this._externalData = new BABYLON.StringDictionary();
  14934. }
  14935. return this._externalData.remove(key);
  14936. };
  14937. Engine.prototype.unbindAllAttributes = function () {
  14938. if (this._mustWipeVertexAttributes) {
  14939. this._mustWipeVertexAttributes = false;
  14940. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14941. this._gl.disableVertexAttribArray(i);
  14942. this._vertexAttribArraysEnabled[i] = false;
  14943. this._currentBufferPointers[i].active = false;
  14944. }
  14945. return;
  14946. }
  14947. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14948. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14949. continue;
  14950. }
  14951. this._gl.disableVertexAttribArray(i);
  14952. this._vertexAttribArraysEnabled[i] = false;
  14953. this._currentBufferPointers[i].active = false;
  14954. }
  14955. };
  14956. Engine.prototype.releaseEffects = function () {
  14957. for (var name in this._compiledEffects) {
  14958. this._deleteProgram(this._compiledEffects[name]._program);
  14959. }
  14960. this._compiledEffects = {};
  14961. };
  14962. // Dispose
  14963. Engine.prototype.dispose = function () {
  14964. this.hideLoadingUI();
  14965. this.stopRenderLoop();
  14966. // Release postProcesses
  14967. while (this.postProcesses.length) {
  14968. this.postProcesses[0].dispose();
  14969. }
  14970. // Empty texture
  14971. if (this._emptyTexture) {
  14972. this._releaseTexture(this._emptyTexture);
  14973. this._emptyTexture = null;
  14974. }
  14975. if (this._emptyCubeTexture) {
  14976. this._releaseTexture(this._emptyCubeTexture);
  14977. this._emptyCubeTexture = null;
  14978. }
  14979. // Rescale PP
  14980. if (this._rescalePostProcess) {
  14981. this._rescalePostProcess.dispose();
  14982. }
  14983. // Release scenes
  14984. while (this.scenes.length) {
  14985. this.scenes[0].dispose();
  14986. }
  14987. // Release audio engine
  14988. if (Engine.audioEngine) {
  14989. Engine.audioEngine.dispose();
  14990. }
  14991. // Release effects
  14992. this.releaseEffects();
  14993. // Unbind
  14994. this.unbindAllAttributes();
  14995. this._boundUniforms = [];
  14996. if (this._dummyFramebuffer) {
  14997. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14998. }
  14999. //WebVR
  15000. this.disableVR();
  15001. // Events
  15002. if (BABYLON.Tools.IsWindowObjectExist()) {
  15003. window.removeEventListener("blur", this._onBlur);
  15004. window.removeEventListener("focus", this._onFocus);
  15005. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15006. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15007. if (this._renderingCanvas) {
  15008. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15009. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15010. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15011. if (!this._doNotHandleContextLost) {
  15012. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15013. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15014. }
  15015. }
  15016. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15017. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15018. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15019. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15020. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15021. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15022. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15023. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15024. if (this._onVrDisplayConnect) {
  15025. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15026. if (this._onVrDisplayDisconnect) {
  15027. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15028. }
  15029. if (this._onVrDisplayPresentChange) {
  15030. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15031. }
  15032. this._onVrDisplayConnect = null;
  15033. this._onVrDisplayDisconnect = null;
  15034. }
  15035. }
  15036. // Remove from Instances
  15037. var index = Engine.Instances.indexOf(this);
  15038. if (index >= 0) {
  15039. Engine.Instances.splice(index, 1);
  15040. }
  15041. this._workingCanvas = null;
  15042. this._workingContext = null;
  15043. this._currentBufferPointers = [];
  15044. this._renderingCanvas = null;
  15045. this._currentProgram = null;
  15046. this._bindedRenderFunction = null;
  15047. this.onResizeObservable.clear();
  15048. this.onCanvasBlurObservable.clear();
  15049. this.onCanvasFocusObservable.clear();
  15050. this.onCanvasPointerOutObservable.clear();
  15051. this.onBeginFrameObservable.clear();
  15052. this.onEndFrameObservable.clear();
  15053. BABYLON.Effect.ResetCache();
  15054. // Abort active requests
  15055. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15056. var request = _a[_i];
  15057. request.abort();
  15058. }
  15059. };
  15060. // Loading screen
  15061. Engine.prototype.displayLoadingUI = function () {
  15062. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15063. return;
  15064. }
  15065. var loadingScreen = this.loadingScreen;
  15066. if (loadingScreen) {
  15067. loadingScreen.displayLoadingUI();
  15068. }
  15069. };
  15070. Engine.prototype.hideLoadingUI = function () {
  15071. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15072. return;
  15073. }
  15074. var loadingScreen = this.loadingScreen;
  15075. if (loadingScreen) {
  15076. loadingScreen.hideLoadingUI();
  15077. }
  15078. };
  15079. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15080. get: function () {
  15081. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15082. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15083. return this._loadingScreen;
  15084. },
  15085. set: function (loadingScreen) {
  15086. this._loadingScreen = loadingScreen;
  15087. },
  15088. enumerable: true,
  15089. configurable: true
  15090. });
  15091. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15092. set: function (text) {
  15093. this.loadingScreen.loadingUIText = text;
  15094. },
  15095. enumerable: true,
  15096. configurable: true
  15097. });
  15098. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15099. set: function (color) {
  15100. this.loadingScreen.loadingUIBackgroundColor = color;
  15101. },
  15102. enumerable: true,
  15103. configurable: true
  15104. });
  15105. Engine.prototype.attachContextLostEvent = function (callback) {
  15106. if (this._renderingCanvas) {
  15107. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15108. }
  15109. };
  15110. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15111. if (this._renderingCanvas) {
  15112. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15113. }
  15114. };
  15115. Engine.prototype.getVertexShaderSource = function (program) {
  15116. var shaders = this._gl.getAttachedShaders(program);
  15117. if (!shaders) {
  15118. return null;
  15119. }
  15120. return this._gl.getShaderSource(shaders[0]);
  15121. };
  15122. Engine.prototype.getFragmentShaderSource = function (program) {
  15123. var shaders = this._gl.getAttachedShaders(program);
  15124. if (!shaders) {
  15125. return null;
  15126. }
  15127. return this._gl.getShaderSource(shaders[1]);
  15128. };
  15129. Engine.prototype.getError = function () {
  15130. return this._gl.getError();
  15131. };
  15132. // FPS
  15133. Engine.prototype.getFps = function () {
  15134. return this._fps;
  15135. };
  15136. Engine.prototype.getDeltaTime = function () {
  15137. return this._deltaTime;
  15138. };
  15139. Engine.prototype._measureFps = function () {
  15140. this._performanceMonitor.sampleFrame();
  15141. this._fps = this._performanceMonitor.averageFPS;
  15142. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15143. };
  15144. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15145. if (faceIndex === void 0) { faceIndex = -1; }
  15146. var gl = this._gl;
  15147. if (!this._dummyFramebuffer) {
  15148. var dummy = gl.createFramebuffer();
  15149. if (!dummy) {
  15150. throw new Error("Unable to create dummy framebuffer");
  15151. }
  15152. this._dummyFramebuffer = dummy;
  15153. }
  15154. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15155. if (faceIndex > -1) {
  15156. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15157. }
  15158. else {
  15159. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15160. }
  15161. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15162. var buffer;
  15163. switch (readType) {
  15164. case gl.UNSIGNED_BYTE:
  15165. buffer = new Uint8Array(4 * width * height);
  15166. readType = gl.UNSIGNED_BYTE;
  15167. break;
  15168. default:
  15169. buffer = new Float32Array(4 * width * height);
  15170. readType = gl.FLOAT;
  15171. break;
  15172. }
  15173. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15174. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15175. return buffer;
  15176. };
  15177. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15178. if (this._webGLVersion > 1) {
  15179. return this._caps.colorBufferFloat;
  15180. }
  15181. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15182. };
  15183. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15184. if (this._webGLVersion > 1) {
  15185. return this._caps.colorBufferFloat;
  15186. }
  15187. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15188. };
  15189. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15190. Engine.prototype._canRenderToFramebuffer = function (type) {
  15191. var gl = this._gl;
  15192. //clear existing errors
  15193. while (gl.getError() !== gl.NO_ERROR) { }
  15194. var successful = true;
  15195. var texture = gl.createTexture();
  15196. gl.bindTexture(gl.TEXTURE_2D, texture);
  15197. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15198. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15199. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15200. var fb = gl.createFramebuffer();
  15201. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15202. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15203. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15204. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15205. successful = successful && (gl.getError() === gl.NO_ERROR);
  15206. //try render by clearing frame buffer's color buffer
  15207. if (successful) {
  15208. gl.clear(gl.COLOR_BUFFER_BIT);
  15209. successful = successful && (gl.getError() === gl.NO_ERROR);
  15210. }
  15211. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15212. if (successful) {
  15213. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15214. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15215. var readFormat = gl.RGBA;
  15216. var readType = gl.UNSIGNED_BYTE;
  15217. var buffer = new Uint8Array(4);
  15218. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15219. successful = successful && (gl.getError() === gl.NO_ERROR);
  15220. }
  15221. //clean up
  15222. gl.deleteTexture(texture);
  15223. gl.deleteFramebuffer(fb);
  15224. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15225. //clear accumulated errors
  15226. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15227. return successful;
  15228. };
  15229. Engine.prototype._getWebGLTextureType = function (type) {
  15230. if (type === Engine.TEXTURETYPE_FLOAT) {
  15231. return this._gl.FLOAT;
  15232. }
  15233. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15234. // Add Half Float Constant.
  15235. return this._gl.HALF_FLOAT_OES;
  15236. }
  15237. return this._gl.UNSIGNED_BYTE;
  15238. };
  15239. ;
  15240. Engine.prototype._getInternalFormat = function (format) {
  15241. var internalFormat = this._gl.RGBA;
  15242. switch (format) {
  15243. case Engine.TEXTUREFORMAT_ALPHA:
  15244. internalFormat = this._gl.ALPHA;
  15245. break;
  15246. case Engine.TEXTUREFORMAT_LUMINANCE:
  15247. internalFormat = this._gl.LUMINANCE;
  15248. break;
  15249. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15250. internalFormat = this._gl.LUMINANCE_ALPHA;
  15251. break;
  15252. case Engine.TEXTUREFORMAT_RGB:
  15253. case Engine.TEXTUREFORMAT_RGB32F:
  15254. internalFormat = this._gl.RGB;
  15255. break;
  15256. case Engine.TEXTUREFORMAT_RGBA:
  15257. case Engine.TEXTUREFORMAT_RGBA32F:
  15258. internalFormat = this._gl.RGBA;
  15259. break;
  15260. case Engine.TEXTUREFORMAT_R32F:
  15261. internalFormat = this._gl.RED;
  15262. break;
  15263. case Engine.TEXTUREFORMAT_RG32F:
  15264. internalFormat = this._gl.RG;
  15265. break;
  15266. }
  15267. return internalFormat;
  15268. };
  15269. /** @ignore */
  15270. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15271. if (this._webGLVersion === 1) {
  15272. if (format) {
  15273. switch (format) {
  15274. case Engine.TEXTUREFORMAT_LUMINANCE:
  15275. return this._gl.LUMINANCE;
  15276. }
  15277. }
  15278. return this._gl.RGBA;
  15279. }
  15280. if (type === Engine.TEXTURETYPE_FLOAT) {
  15281. if (format) {
  15282. switch (format) {
  15283. case Engine.TEXTUREFORMAT_R32F:
  15284. return this._gl.R32F;
  15285. case Engine.TEXTUREFORMAT_RG32F:
  15286. return this._gl.RG32F;
  15287. case Engine.TEXTUREFORMAT_RGB32F:
  15288. return this._gl.RGB32F;
  15289. }
  15290. }
  15291. return this._gl.RGBA32F;
  15292. }
  15293. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15294. return this._gl.RGBA16F;
  15295. }
  15296. if (format) {
  15297. switch (format) {
  15298. case Engine.TEXTUREFORMAT_LUMINANCE:
  15299. return this._gl.LUMINANCE;
  15300. }
  15301. }
  15302. return this._gl.RGBA;
  15303. };
  15304. ;
  15305. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15306. if (type === Engine.TEXTURETYPE_FLOAT) {
  15307. return this._gl.RGBA32F;
  15308. }
  15309. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15310. return this._gl.RGBA16F;
  15311. }
  15312. return this._gl.RGBA8;
  15313. };
  15314. ;
  15315. Engine.prototype.createQuery = function () {
  15316. return this._gl.createQuery();
  15317. };
  15318. Engine.prototype.deleteQuery = function (query) {
  15319. this._gl.deleteQuery(query);
  15320. return this;
  15321. };
  15322. Engine.prototype.isQueryResultAvailable = function (query) {
  15323. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15324. };
  15325. Engine.prototype.getQueryResult = function (query) {
  15326. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15327. };
  15328. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15329. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15330. this._gl.beginQuery(glAlgorithm, query);
  15331. return this;
  15332. };
  15333. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15334. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15335. this._gl.endQuery(glAlgorithm);
  15336. return this;
  15337. };
  15338. /* Time queries */
  15339. Engine.prototype._createTimeQuery = function () {
  15340. var timerQuery = this._caps.timerQuery;
  15341. if (timerQuery.createQueryEXT) {
  15342. return timerQuery.createQueryEXT();
  15343. }
  15344. return this.createQuery();
  15345. };
  15346. Engine.prototype._deleteTimeQuery = function (query) {
  15347. var timerQuery = this._caps.timerQuery;
  15348. if (timerQuery.deleteQueryEXT) {
  15349. timerQuery.deleteQueryEXT(query);
  15350. return;
  15351. }
  15352. this.deleteQuery(query);
  15353. };
  15354. Engine.prototype._getTimeQueryResult = function (query) {
  15355. var timerQuery = this._caps.timerQuery;
  15356. if (timerQuery.getQueryObjectEXT) {
  15357. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15358. }
  15359. return this.getQueryResult(query);
  15360. };
  15361. Engine.prototype._getTimeQueryAvailability = function (query) {
  15362. var timerQuery = this._caps.timerQuery;
  15363. if (timerQuery.getQueryObjectEXT) {
  15364. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15365. }
  15366. return this.isQueryResultAvailable(query);
  15367. };
  15368. Engine.prototype.startTimeQuery = function () {
  15369. var timerQuery = this._caps.timerQuery;
  15370. if (!timerQuery) {
  15371. return null;
  15372. }
  15373. var token = new BABYLON._TimeToken();
  15374. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15375. if (this._caps.canUseTimestampForTimerQuery) {
  15376. token._startTimeQuery = this._createTimeQuery();
  15377. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15378. }
  15379. else {
  15380. if (this._currentNonTimestampToken) {
  15381. return this._currentNonTimestampToken;
  15382. }
  15383. token._timeElapsedQuery = this._createTimeQuery();
  15384. if (timerQuery.beginQueryEXT) {
  15385. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15386. }
  15387. else {
  15388. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15389. }
  15390. this._currentNonTimestampToken = token;
  15391. }
  15392. return token;
  15393. };
  15394. Engine.prototype.endTimeQuery = function (token) {
  15395. var timerQuery = this._caps.timerQuery;
  15396. if (!timerQuery || !token) {
  15397. return -1;
  15398. }
  15399. if (this._caps.canUseTimestampForTimerQuery) {
  15400. if (!token._startTimeQuery) {
  15401. return -1;
  15402. }
  15403. if (!token._endTimeQuery) {
  15404. token._endTimeQuery = this._createTimeQuery();
  15405. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15406. }
  15407. }
  15408. else if (!token._timeElapsedQueryEnded) {
  15409. if (!token._timeElapsedQuery) {
  15410. return -1;
  15411. }
  15412. if (timerQuery.endQueryEXT) {
  15413. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15414. }
  15415. else {
  15416. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15417. }
  15418. token._timeElapsedQueryEnded = true;
  15419. }
  15420. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15421. var available = false;
  15422. if (token._endTimeQuery) {
  15423. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15424. }
  15425. else if (token._timeElapsedQuery) {
  15426. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15427. }
  15428. if (available && !disjoint) {
  15429. var result = 0;
  15430. if (this._caps.canUseTimestampForTimerQuery) {
  15431. if (!token._startTimeQuery || !token._endTimeQuery) {
  15432. return -1;
  15433. }
  15434. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15435. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15436. result = timeEnd - timeStart;
  15437. this._deleteTimeQuery(token._startTimeQuery);
  15438. this._deleteTimeQuery(token._endTimeQuery);
  15439. token._startTimeQuery = null;
  15440. token._endTimeQuery = null;
  15441. }
  15442. else {
  15443. if (!token._timeElapsedQuery) {
  15444. return -1;
  15445. }
  15446. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15447. this._deleteTimeQuery(token._timeElapsedQuery);
  15448. token._timeElapsedQuery = null;
  15449. token._timeElapsedQueryEnded = false;
  15450. this._currentNonTimestampToken = null;
  15451. }
  15452. return result;
  15453. }
  15454. return -1;
  15455. };
  15456. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15457. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15458. };
  15459. // Transform feedback
  15460. Engine.prototype.createTransformFeedback = function () {
  15461. return this._gl.createTransformFeedback();
  15462. };
  15463. Engine.prototype.deleteTransformFeedback = function (value) {
  15464. this._gl.deleteTransformFeedback(value);
  15465. };
  15466. Engine.prototype.bindTransformFeedback = function (value) {
  15467. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15468. };
  15469. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15470. if (usePoints === void 0) { usePoints = true; }
  15471. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15472. };
  15473. Engine.prototype.endTransformFeedback = function () {
  15474. this._gl.endTransformFeedback();
  15475. };
  15476. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15477. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15478. };
  15479. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15480. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15481. };
  15482. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15483. var _this = this;
  15484. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15485. this._activeRequests.push(request);
  15486. request.onCompleteObservable.add(function (request) {
  15487. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15488. });
  15489. return request;
  15490. };
  15491. /** @ignore */
  15492. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15493. var _this = this;
  15494. return new Promise(function (resolve, reject) {
  15495. _this._loadFile(url, function (data) {
  15496. resolve(data);
  15497. }, undefined, database, useArrayBuffer, function (request, exception) {
  15498. reject(exception);
  15499. });
  15500. });
  15501. };
  15502. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15503. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15504. var onload = function (data) {
  15505. loadedFiles[index] = data;
  15506. loadedFiles._internalCount++;
  15507. if (loadedFiles._internalCount === 6) {
  15508. onfinish(loadedFiles);
  15509. }
  15510. };
  15511. var onerror = function (request, exception) {
  15512. if (onErrorCallBack && request) {
  15513. onErrorCallBack(request.status + " " + request.statusText, exception);
  15514. }
  15515. };
  15516. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15517. };
  15518. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15519. if (onError === void 0) { onError = null; }
  15520. var loadedFiles = [];
  15521. loadedFiles._internalCount = 0;
  15522. for (var index = 0; index < 6; index++) {
  15523. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15524. }
  15525. };
  15526. // Statics
  15527. Engine.isSupported = function () {
  15528. try {
  15529. var tempcanvas = document.createElement("canvas");
  15530. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15531. return gl != null && !!window.WebGLRenderingContext;
  15532. }
  15533. catch (e) {
  15534. return false;
  15535. }
  15536. };
  15537. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15538. Engine.ExceptionList = [
  15539. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15540. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15541. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15542. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15543. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15544. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15545. ];
  15546. Engine.Instances = new Array();
  15547. // Const statics
  15548. Engine._ALPHA_DISABLE = 0;
  15549. Engine._ALPHA_ADD = 1;
  15550. Engine._ALPHA_COMBINE = 2;
  15551. Engine._ALPHA_SUBTRACT = 3;
  15552. Engine._ALPHA_MULTIPLY = 4;
  15553. Engine._ALPHA_MAXIMIZED = 5;
  15554. Engine._ALPHA_ONEONE = 6;
  15555. Engine._ALPHA_PREMULTIPLIED = 7;
  15556. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15557. Engine._ALPHA_INTERPOLATE = 9;
  15558. Engine._ALPHA_SCREENMODE = 10;
  15559. Engine._DELAYLOADSTATE_NONE = 0;
  15560. Engine._DELAYLOADSTATE_LOADED = 1;
  15561. Engine._DELAYLOADSTATE_LOADING = 2;
  15562. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15563. Engine._TEXTUREFORMAT_ALPHA = 0;
  15564. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15565. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15566. Engine._TEXTUREFORMAT_RGB = 4;
  15567. Engine._TEXTUREFORMAT_RGBA = 5;
  15568. Engine._TEXTUREFORMAT_R32F = 6;
  15569. Engine._TEXTUREFORMAT_RG32F = 7;
  15570. Engine._TEXTUREFORMAT_RGB32F = 8;
  15571. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15572. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15573. Engine._TEXTURETYPE_FLOAT = 1;
  15574. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15575. // Depht or Stencil test Constants.
  15576. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15577. 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.
  15578. 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.
  15579. 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.
  15580. 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.
  15581. 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.
  15582. 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.
  15583. 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.
  15584. // Stencil Actions Constants.
  15585. Engine._KEEP = 0x1E00;
  15586. Engine._REPLACE = 0x1E01;
  15587. Engine._INCR = 0x1E02;
  15588. Engine._DECR = 0x1E03;
  15589. Engine._INVERT = 0x150A;
  15590. Engine._INCR_WRAP = 0x8507;
  15591. Engine._DECR_WRAP = 0x8508;
  15592. // Texture rescaling mode
  15593. Engine._SCALEMODE_FLOOR = 1;
  15594. Engine._SCALEMODE_NEAREST = 2;
  15595. Engine._SCALEMODE_CEILING = 3;
  15596. // Updatable statics so stick with vars here
  15597. Engine.CollisionsEpsilon = 0.001;
  15598. Engine.CodeRepository = "src/";
  15599. Engine.ShadersRepository = "src/Shaders/";
  15600. return Engine;
  15601. }());
  15602. BABYLON.Engine = Engine;
  15603. })(BABYLON || (BABYLON = {}));
  15604. //# sourceMappingURL=babylon.engine.js.map
  15605. "use strict";
  15606. var BABYLON;
  15607. (function (BABYLON) {
  15608. /**
  15609. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15610. */
  15611. var Node = /** @class */ (function () {
  15612. /**
  15613. * Creates a new Node
  15614. * @param {string} name - the name and id to be given to this node
  15615. * @param {BABYLON.Scene} the scene this node will be added to
  15616. */
  15617. function Node(name, scene) {
  15618. if (scene === void 0) { scene = null; }
  15619. /**
  15620. * Gets or sets a string used to store user defined state for the node
  15621. */
  15622. this.state = "";
  15623. /**
  15624. * Gets or sets an object used to store user defined information for the node
  15625. */
  15626. this.metadata = null;
  15627. /**
  15628. * Gets or sets a boolean used to define if the node must be serialized
  15629. */
  15630. this.doNotSerialize = false;
  15631. /** @ignore */
  15632. this._isDisposed = false;
  15633. /**
  15634. * Gets a list of {BABYLON.Animation} associated with the node
  15635. */
  15636. this.animations = new Array();
  15637. this._ranges = {};
  15638. this._isEnabled = true;
  15639. this._isReady = true;
  15640. /** @ignore */
  15641. this._currentRenderId = -1;
  15642. this._parentRenderId = -1;
  15643. this._childRenderId = -1;
  15644. this._animationPropertiesOverride = null;
  15645. /**
  15646. * An event triggered when the mesh is disposed
  15647. * @type {BABYLON.Observable}
  15648. */
  15649. this.onDisposeObservable = new BABYLON.Observable();
  15650. // Behaviors
  15651. this._behaviors = new Array();
  15652. this.name = name;
  15653. this.id = name;
  15654. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15655. this.uniqueId = this._scene.getUniqueId();
  15656. this._initCache();
  15657. }
  15658. /**
  15659. * Gets a boolean indicating if the node has been disposed
  15660. * @returns true if the node was disposed
  15661. */
  15662. Node.prototype.isDisposed = function () {
  15663. return this._isDisposed;
  15664. };
  15665. Object.defineProperty(Node.prototype, "parent", {
  15666. get: function () {
  15667. return this._parentNode;
  15668. },
  15669. /**
  15670. * Gets or sets the parent of the node
  15671. */
  15672. set: function (parent) {
  15673. if (this._parentNode === parent) {
  15674. return;
  15675. }
  15676. // Remove self from list of children of parent
  15677. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15678. var index = this._parentNode._children.indexOf(this);
  15679. if (index !== -1) {
  15680. this._parentNode._children.splice(index, 1);
  15681. }
  15682. }
  15683. // Store new parent
  15684. this._parentNode = parent;
  15685. // Add as child to new parent
  15686. if (this._parentNode) {
  15687. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15688. this._parentNode._children = new Array();
  15689. }
  15690. this._parentNode._children.push(this);
  15691. }
  15692. },
  15693. enumerable: true,
  15694. configurable: true
  15695. });
  15696. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15697. /**
  15698. * Gets or sets the animation properties override
  15699. */
  15700. get: function () {
  15701. return this._animationPropertiesOverride;
  15702. },
  15703. set: function (value) {
  15704. this._animationPropertiesOverride = value;
  15705. },
  15706. enumerable: true,
  15707. configurable: true
  15708. });
  15709. /**
  15710. * Gets a string idenfifying the name of the class
  15711. * @returns "Node" string
  15712. */
  15713. Node.prototype.getClassName = function () {
  15714. return "Node";
  15715. };
  15716. Object.defineProperty(Node.prototype, "onDispose", {
  15717. /**
  15718. * Sets a callback that will be raised when the node will be disposed
  15719. */
  15720. set: function (callback) {
  15721. if (this._onDisposeObserver) {
  15722. this.onDisposeObservable.remove(this._onDisposeObserver);
  15723. }
  15724. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15725. },
  15726. enumerable: true,
  15727. configurable: true
  15728. });
  15729. /**
  15730. * Gets the scene of the node
  15731. * @returns a {BABYLON.Scene}
  15732. */
  15733. Node.prototype.getScene = function () {
  15734. return this._scene;
  15735. };
  15736. /**
  15737. * Gets the engine of the node
  15738. * @returns a {BABYLON.Engine}
  15739. */
  15740. Node.prototype.getEngine = function () {
  15741. return this._scene.getEngine();
  15742. };
  15743. /**
  15744. * Attach a behavior to the node
  15745. * @see http://doc.babylonjs.com/features/behaviour
  15746. * @param behavior defines the behavior to attach
  15747. * @returns the current Node
  15748. */
  15749. Node.prototype.addBehavior = function (behavior) {
  15750. var _this = this;
  15751. var index = this._behaviors.indexOf(behavior);
  15752. if (index !== -1) {
  15753. return this;
  15754. }
  15755. behavior.init();
  15756. if (this._scene.isLoading) {
  15757. // We defer the attach when the scene will be loaded
  15758. var observer = this._scene.onDataLoadedObservable.add(function () {
  15759. behavior.attach(_this);
  15760. setTimeout(function () {
  15761. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15762. _this._scene.onDataLoadedObservable.remove(observer);
  15763. }, 0);
  15764. });
  15765. }
  15766. else {
  15767. behavior.attach(this);
  15768. }
  15769. this._behaviors.push(behavior);
  15770. return this;
  15771. };
  15772. /**
  15773. * Remove an attached behavior
  15774. * @see http://doc.babylonjs.com/features/behaviour
  15775. * @param behavior defines the behavior to attach
  15776. * @returns the current Node
  15777. */
  15778. Node.prototype.removeBehavior = function (behavior) {
  15779. var index = this._behaviors.indexOf(behavior);
  15780. if (index === -1) {
  15781. return this;
  15782. }
  15783. this._behaviors[index].detach();
  15784. this._behaviors.splice(index, 1);
  15785. return this;
  15786. };
  15787. Object.defineProperty(Node.prototype, "behaviors", {
  15788. /**
  15789. * Gets the list of attached behaviors
  15790. * @see http://doc.babylonjs.com/features/behaviour
  15791. */
  15792. get: function () {
  15793. return this._behaviors;
  15794. },
  15795. enumerable: true,
  15796. configurable: true
  15797. });
  15798. /**
  15799. * Gets an attached behavior by name
  15800. * @param name defines the name of the behavior to look for
  15801. * @see http://doc.babylonjs.com/features/behaviour
  15802. * @returns null if behavior was not found else the requested behavior
  15803. */
  15804. Node.prototype.getBehaviorByName = function (name) {
  15805. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15806. var behavior = _a[_i];
  15807. if (behavior.name === name) {
  15808. return behavior;
  15809. }
  15810. }
  15811. return null;
  15812. };
  15813. /**
  15814. * Returns the world matrix of the node
  15815. * @returns a matrix containing the node's world matrix
  15816. */
  15817. Node.prototype.getWorldMatrix = function () {
  15818. return BABYLON.Matrix.Identity();
  15819. };
  15820. // override it in derived class if you add new variables to the cache
  15821. // and call the parent class method
  15822. /** @ignore */
  15823. Node.prototype._initCache = function () {
  15824. this._cache = {};
  15825. this._cache.parent = undefined;
  15826. };
  15827. /** @ignore */
  15828. Node.prototype.updateCache = function (force) {
  15829. if (!force && this.isSynchronized())
  15830. return;
  15831. this._cache.parent = this.parent;
  15832. this._updateCache();
  15833. };
  15834. // override it in derived class if you add new variables to the cache
  15835. // and call the parent class method if !ignoreParentClass
  15836. /** @ignore */
  15837. Node.prototype._updateCache = function (ignoreParentClass) {
  15838. };
  15839. // override it in derived class if you add new variables to the cache
  15840. /** @ignore */
  15841. Node.prototype._isSynchronized = function () {
  15842. return true;
  15843. };
  15844. /** @ignore */
  15845. Node.prototype._markSyncedWithParent = function () {
  15846. if (this.parent) {
  15847. this._parentRenderId = this.parent._childRenderId;
  15848. }
  15849. };
  15850. /** @ignore */
  15851. Node.prototype.isSynchronizedWithParent = function () {
  15852. if (!this.parent) {
  15853. return true;
  15854. }
  15855. if (this._parentRenderId !== this.parent._childRenderId) {
  15856. return false;
  15857. }
  15858. return this.parent.isSynchronized();
  15859. };
  15860. /** @ignore */
  15861. Node.prototype.isSynchronized = function (updateCache) {
  15862. var check = this.hasNewParent();
  15863. check = check || !this.isSynchronizedWithParent();
  15864. check = check || !this._isSynchronized();
  15865. if (updateCache)
  15866. this.updateCache(true);
  15867. return !check;
  15868. };
  15869. /** @ignore */
  15870. Node.prototype.hasNewParent = function (update) {
  15871. if (this._cache.parent === this.parent)
  15872. return false;
  15873. if (update)
  15874. this._cache.parent = this.parent;
  15875. return true;
  15876. };
  15877. /**
  15878. * Is this node ready to be used/rendered
  15879. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15880. * @return true if the node is ready
  15881. */
  15882. Node.prototype.isReady = function (completeCheck) {
  15883. if (completeCheck === void 0) { completeCheck = false; }
  15884. return this._isReady;
  15885. };
  15886. /**
  15887. * Is this node enabled?
  15888. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true
  15889. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  15890. * @return whether this node (and its parent) is enabled
  15891. * @see setEnabled
  15892. */
  15893. Node.prototype.isEnabled = function (checkAncestors) {
  15894. if (checkAncestors === void 0) { checkAncestors = true; }
  15895. if (checkAncestors === false) {
  15896. return this._isEnabled;
  15897. }
  15898. if (this._isEnabled === false) {
  15899. return false;
  15900. }
  15901. if (this.parent !== undefined && this.parent !== null) {
  15902. return this.parent.isEnabled(checkAncestors);
  15903. }
  15904. return true;
  15905. };
  15906. /**
  15907. * Set the enabled state of this node
  15908. * @param value defines the new enabled state
  15909. * @see isEnabled
  15910. */
  15911. Node.prototype.setEnabled = function (value) {
  15912. this._isEnabled = value;
  15913. };
  15914. /**
  15915. * Is this node a descendant of the given node?
  15916. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15917. * @param ancestor defines the parent node to inspect
  15918. * @see parent
  15919. * @returns a boolean indicating if this node is a descendant of the given node
  15920. */
  15921. Node.prototype.isDescendantOf = function (ancestor) {
  15922. if (this.parent) {
  15923. if (this.parent === ancestor) {
  15924. return true;
  15925. }
  15926. return this.parent.isDescendantOf(ancestor);
  15927. }
  15928. return false;
  15929. };
  15930. /** @ignore */
  15931. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15932. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15933. if (!this._children) {
  15934. return;
  15935. }
  15936. for (var index = 0; index < this._children.length; index++) {
  15937. var item = this._children[index];
  15938. if (!predicate || predicate(item)) {
  15939. results.push(item);
  15940. }
  15941. if (!directDescendantsOnly) {
  15942. item._getDescendants(results, false, predicate);
  15943. }
  15944. }
  15945. };
  15946. /**
  15947. * Will return all nodes that have this node as ascendant
  15948. * @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
  15949. * @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
  15950. * @return all children nodes of all types
  15951. */
  15952. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15953. var results = new Array();
  15954. this._getDescendants(results, directDescendantsOnly, predicate);
  15955. return results;
  15956. };
  15957. /**
  15958. * Get all child-meshes of this node
  15959. * @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
  15960. * @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
  15961. * @returns an array of {BABYLON.AbstractMesh}
  15962. */
  15963. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15964. var results = [];
  15965. this._getDescendants(results, directDescendantsOnly, function (node) {
  15966. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15967. });
  15968. return results;
  15969. };
  15970. /**
  15971. * Get all child-transformNodes of this node
  15972. * @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
  15973. * @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
  15974. * @returns an array of {BABYLON.TransformNode}
  15975. */
  15976. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15977. var results = [];
  15978. this._getDescendants(results, directDescendantsOnly, function (node) {
  15979. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15980. });
  15981. return results;
  15982. };
  15983. /**
  15984. * Get all direct children of this node
  15985. * @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
  15986. * @returns an array of {BABYLON.Node}
  15987. */
  15988. Node.prototype.getChildren = function (predicate) {
  15989. return this.getDescendants(true, predicate);
  15990. };
  15991. /** @ignore */
  15992. Node.prototype._setReady = function (state) {
  15993. if (state === this._isReady) {
  15994. return;
  15995. }
  15996. if (!state) {
  15997. this._isReady = false;
  15998. return;
  15999. }
  16000. if (this.onReady) {
  16001. this.onReady(this);
  16002. }
  16003. this._isReady = true;
  16004. };
  16005. /**
  16006. * Get an animation by name
  16007. * @param name defines the name of the animation to look for
  16008. * @returns null if not found else the requested animation
  16009. */
  16010. Node.prototype.getAnimationByName = function (name) {
  16011. for (var i = 0; i < this.animations.length; i++) {
  16012. var animation = this.animations[i];
  16013. if (animation.name === name) {
  16014. return animation;
  16015. }
  16016. }
  16017. return null;
  16018. };
  16019. /**
  16020. * Creates an animation range for this node
  16021. * @param name defines the name of the range
  16022. * @param from defines the starting key
  16023. * @param to defines the end key
  16024. */
  16025. Node.prototype.createAnimationRange = function (name, from, to) {
  16026. // check name not already in use
  16027. if (!this._ranges[name]) {
  16028. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16029. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16030. if (this.animations[i]) {
  16031. this.animations[i].createRange(name, from, to);
  16032. }
  16033. }
  16034. }
  16035. };
  16036. /**
  16037. * Delete a specific animation range
  16038. * @param name defines the name of the range to delete
  16039. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16040. */
  16041. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16042. if (deleteFrames === void 0) { deleteFrames = true; }
  16043. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16044. if (this.animations[i]) {
  16045. this.animations[i].deleteRange(name, deleteFrames);
  16046. }
  16047. }
  16048. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16049. };
  16050. /**
  16051. * Get an animation range by name
  16052. * @param name defines the name of the animation range to look for
  16053. * @returns null if not found else the requested animation range
  16054. */
  16055. Node.prototype.getAnimationRange = function (name) {
  16056. return this._ranges[name];
  16057. };
  16058. /**
  16059. * Will start the animation sequence
  16060. * @param name defines the range frames for animation sequence
  16061. * @param loop defines if the animation should loop (false by default)
  16062. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16063. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16064. * @returns the object created for this animation. If range does not exist, it will return null
  16065. */
  16066. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16067. var range = this.getAnimationRange(name);
  16068. if (!range) {
  16069. return null;
  16070. }
  16071. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16072. };
  16073. /**
  16074. * Serialize animation ranges into a JSON compatible object
  16075. * @returns serialization object
  16076. */
  16077. Node.prototype.serializeAnimationRanges = function () {
  16078. var serializationRanges = [];
  16079. for (var name in this._ranges) {
  16080. var localRange = this._ranges[name];
  16081. if (!localRange) {
  16082. continue;
  16083. }
  16084. var range = {};
  16085. range.name = name;
  16086. range.from = localRange.from;
  16087. range.to = localRange.to;
  16088. serializationRanges.push(range);
  16089. }
  16090. return serializationRanges;
  16091. };
  16092. /**
  16093. * Computes the world matrix of the node
  16094. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16095. * @returns the world matrix
  16096. */
  16097. Node.prototype.computeWorldMatrix = function (force) {
  16098. return BABYLON.Matrix.Identity();
  16099. };
  16100. /**
  16101. * Releases resources associated with this node.
  16102. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16103. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16104. */
  16105. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16106. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16107. if (!doNotRecurse) {
  16108. var nodes = this.getDescendants(true);
  16109. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16110. var node = nodes_1[_i];
  16111. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16112. }
  16113. }
  16114. else {
  16115. var transformNodes = this.getChildTransformNodes(true);
  16116. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16117. var transformNode = transformNodes_1[_a];
  16118. transformNode.parent = null;
  16119. transformNode.computeWorldMatrix(true);
  16120. }
  16121. }
  16122. this.parent = null;
  16123. // Callback
  16124. this.onDisposeObservable.notifyObservers(this);
  16125. this.onDisposeObservable.clear();
  16126. // Behaviors
  16127. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16128. var behavior = _c[_b];
  16129. behavior.detach();
  16130. }
  16131. this._behaviors = [];
  16132. this._isDisposed = true;
  16133. };
  16134. /**
  16135. * Parse animation range data from a serialization object and store them into a given node
  16136. * @param node defines where to store the animation ranges
  16137. * @param parsedNode defines the serialization object to read data from
  16138. * @param scene defines the hosting scene
  16139. */
  16140. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16141. if (parsedNode.ranges) {
  16142. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16143. var data = parsedNode.ranges[index];
  16144. node.createAnimationRange(data.name, data.from, data.to);
  16145. }
  16146. }
  16147. };
  16148. __decorate([
  16149. BABYLON.serialize()
  16150. ], Node.prototype, "name", void 0);
  16151. __decorate([
  16152. BABYLON.serialize()
  16153. ], Node.prototype, "id", void 0);
  16154. __decorate([
  16155. BABYLON.serialize()
  16156. ], Node.prototype, "uniqueId", void 0);
  16157. __decorate([
  16158. BABYLON.serialize()
  16159. ], Node.prototype, "state", void 0);
  16160. __decorate([
  16161. BABYLON.serialize()
  16162. ], Node.prototype, "metadata", void 0);
  16163. return Node;
  16164. }());
  16165. BABYLON.Node = Node;
  16166. })(BABYLON || (BABYLON = {}));
  16167. //# sourceMappingURL=babylon.node.js.map
  16168. "use strict";
  16169. var BABYLON;
  16170. (function (BABYLON) {
  16171. var BoundingSphere = /** @class */ (function () {
  16172. function BoundingSphere(minimum, maximum) {
  16173. this.minimum = minimum;
  16174. this.maximum = maximum;
  16175. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16176. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16177. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16178. this.radius = distance * 0.5;
  16179. this.centerWorld = BABYLON.Vector3.Zero();
  16180. this._update(BABYLON.Matrix.Identity());
  16181. }
  16182. // Methods
  16183. BoundingSphere.prototype._update = function (world) {
  16184. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16185. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16186. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16187. };
  16188. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16189. for (var i = 0; i < 6; i++) {
  16190. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16191. return false;
  16192. }
  16193. return true;
  16194. };
  16195. BoundingSphere.prototype.intersectsPoint = function (point) {
  16196. var x = this.centerWorld.x - point.x;
  16197. var y = this.centerWorld.y - point.y;
  16198. var z = this.centerWorld.z - point.z;
  16199. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16200. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16201. return false;
  16202. return true;
  16203. };
  16204. // Statics
  16205. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16206. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16207. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16208. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16209. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16210. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16211. return false;
  16212. return true;
  16213. };
  16214. return BoundingSphere;
  16215. }());
  16216. BABYLON.BoundingSphere = BoundingSphere;
  16217. })(BABYLON || (BABYLON = {}));
  16218. //# sourceMappingURL=babylon.boundingSphere.js.map
  16219. "use strict";
  16220. var BABYLON;
  16221. (function (BABYLON) {
  16222. var BoundingBox = /** @class */ (function () {
  16223. function BoundingBox(minimum, maximum) {
  16224. this.minimum = minimum;
  16225. this.maximum = maximum;
  16226. this.vectors = new Array();
  16227. this.vectorsWorld = new Array();
  16228. // Bounding vectors
  16229. this.vectors.push(this.minimum.clone());
  16230. this.vectors.push(this.maximum.clone());
  16231. this.vectors.push(this.minimum.clone());
  16232. this.vectors[2].x = this.maximum.x;
  16233. this.vectors.push(this.minimum.clone());
  16234. this.vectors[3].y = this.maximum.y;
  16235. this.vectors.push(this.minimum.clone());
  16236. this.vectors[4].z = this.maximum.z;
  16237. this.vectors.push(this.maximum.clone());
  16238. this.vectors[5].z = this.minimum.z;
  16239. this.vectors.push(this.maximum.clone());
  16240. this.vectors[6].x = this.minimum.x;
  16241. this.vectors.push(this.maximum.clone());
  16242. this.vectors[7].y = this.minimum.y;
  16243. // OBB
  16244. this.center = this.maximum.add(this.minimum).scale(0.5);
  16245. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16246. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16247. // World
  16248. for (var index = 0; index < this.vectors.length; index++) {
  16249. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16250. }
  16251. this.minimumWorld = BABYLON.Vector3.Zero();
  16252. this.maximumWorld = BABYLON.Vector3.Zero();
  16253. this.centerWorld = BABYLON.Vector3.Zero();
  16254. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16255. this._update(BABYLON.Matrix.Identity());
  16256. }
  16257. // Methods
  16258. BoundingBox.prototype.getWorldMatrix = function () {
  16259. return this._worldMatrix;
  16260. };
  16261. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16262. this._worldMatrix.copyFrom(matrix);
  16263. return this;
  16264. };
  16265. BoundingBox.prototype._update = function (world) {
  16266. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16267. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16268. for (var index = 0; index < this.vectors.length; index++) {
  16269. var v = this.vectorsWorld[index];
  16270. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16271. if (v.x < this.minimumWorld.x)
  16272. this.minimumWorld.x = v.x;
  16273. if (v.y < this.minimumWorld.y)
  16274. this.minimumWorld.y = v.y;
  16275. if (v.z < this.minimumWorld.z)
  16276. this.minimumWorld.z = v.z;
  16277. if (v.x > this.maximumWorld.x)
  16278. this.maximumWorld.x = v.x;
  16279. if (v.y > this.maximumWorld.y)
  16280. this.maximumWorld.y = v.y;
  16281. if (v.z > this.maximumWorld.z)
  16282. this.maximumWorld.z = v.z;
  16283. }
  16284. // Extend
  16285. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16286. this.extendSizeWorld.scaleInPlace(0.5);
  16287. // OBB
  16288. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16289. this.centerWorld.scaleInPlace(0.5);
  16290. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16291. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16292. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16293. this._worldMatrix = world;
  16294. };
  16295. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16296. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16297. };
  16298. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16299. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16300. };
  16301. BoundingBox.prototype.intersectsPoint = function (point) {
  16302. var delta = -BABYLON.Epsilon;
  16303. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16304. return false;
  16305. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16306. return false;
  16307. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16308. return false;
  16309. return true;
  16310. };
  16311. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16312. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16313. };
  16314. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16315. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16316. return false;
  16317. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16318. return false;
  16319. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16320. return false;
  16321. return true;
  16322. };
  16323. // Statics
  16324. BoundingBox.Intersects = function (box0, box1) {
  16325. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16326. return false;
  16327. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16328. return false;
  16329. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16330. return false;
  16331. return true;
  16332. };
  16333. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16334. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16335. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16336. return (num <= (sphereRadius * sphereRadius));
  16337. };
  16338. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16339. for (var p = 0; p < 6; p++) {
  16340. for (var i = 0; i < 8; i++) {
  16341. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16342. return false;
  16343. }
  16344. }
  16345. }
  16346. return true;
  16347. };
  16348. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16349. for (var p = 0; p < 6; p++) {
  16350. var inCount = 8;
  16351. for (var i = 0; i < 8; i++) {
  16352. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16353. --inCount;
  16354. }
  16355. else {
  16356. break;
  16357. }
  16358. }
  16359. if (inCount === 0)
  16360. return false;
  16361. }
  16362. return true;
  16363. };
  16364. return BoundingBox;
  16365. }());
  16366. BABYLON.BoundingBox = BoundingBox;
  16367. })(BABYLON || (BABYLON = {}));
  16368. //# sourceMappingURL=babylon.boundingBox.js.map
  16369. "use strict";
  16370. var BABYLON;
  16371. (function (BABYLON) {
  16372. var computeBoxExtents = function (axis, box) {
  16373. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16374. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16375. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16376. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16377. var r = r0 + r1 + r2;
  16378. return {
  16379. min: p - r,
  16380. max: p + r
  16381. };
  16382. };
  16383. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16384. var axisOverlap = function (axis, box0, box1) {
  16385. var result0 = computeBoxExtents(axis, box0);
  16386. var result1 = computeBoxExtents(axis, box1);
  16387. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16388. };
  16389. var BoundingInfo = /** @class */ (function () {
  16390. function BoundingInfo(minimum, maximum) {
  16391. this.minimum = minimum;
  16392. this.maximum = maximum;
  16393. this._isLocked = false;
  16394. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16395. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16396. }
  16397. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16398. get: function () {
  16399. return this._isLocked;
  16400. },
  16401. set: function (value) {
  16402. this._isLocked = value;
  16403. },
  16404. enumerable: true,
  16405. configurable: true
  16406. });
  16407. // Methods
  16408. BoundingInfo.prototype.update = function (world) {
  16409. if (this._isLocked) {
  16410. return;
  16411. }
  16412. this.boundingBox._update(world);
  16413. this.boundingSphere._update(world);
  16414. };
  16415. /**
  16416. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16417. * @param center New center of the bounding info
  16418. * @param extend New extend of the bounding info
  16419. */
  16420. BoundingInfo.prototype.centerOn = function (center, extend) {
  16421. this.minimum = center.subtract(extend);
  16422. this.maximum = center.add(extend);
  16423. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16424. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16425. return this;
  16426. };
  16427. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16428. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16429. return false;
  16430. return this.boundingBox.isInFrustum(frustumPlanes);
  16431. };
  16432. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16433. /**
  16434. * Gets the world distance between the min and max points of the bounding box
  16435. */
  16436. get: function () {
  16437. var boundingBox = this.boundingBox;
  16438. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16439. return size.length();
  16440. },
  16441. enumerable: true,
  16442. configurable: true
  16443. });
  16444. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16445. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16446. };
  16447. BoundingInfo.prototype._checkCollision = function (collider) {
  16448. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16449. };
  16450. BoundingInfo.prototype.intersectsPoint = function (point) {
  16451. if (!this.boundingSphere.centerWorld) {
  16452. return false;
  16453. }
  16454. if (!this.boundingSphere.intersectsPoint(point)) {
  16455. return false;
  16456. }
  16457. if (!this.boundingBox.intersectsPoint(point)) {
  16458. return false;
  16459. }
  16460. return true;
  16461. };
  16462. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16463. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16464. return false;
  16465. }
  16466. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16467. return false;
  16468. }
  16469. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16470. return false;
  16471. }
  16472. if (!precise) {
  16473. return true;
  16474. }
  16475. var box0 = this.boundingBox;
  16476. var box1 = boundingInfo.boundingBox;
  16477. if (!axisOverlap(box0.directions[0], box0, box1))
  16478. return false;
  16479. if (!axisOverlap(box0.directions[1], box0, box1))
  16480. return false;
  16481. if (!axisOverlap(box0.directions[2], box0, box1))
  16482. return false;
  16483. if (!axisOverlap(box1.directions[0], box0, box1))
  16484. return false;
  16485. if (!axisOverlap(box1.directions[1], box0, box1))
  16486. return false;
  16487. if (!axisOverlap(box1.directions[2], box0, box1))
  16488. return false;
  16489. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16490. return false;
  16491. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16492. return false;
  16493. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16494. return false;
  16495. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16496. return false;
  16497. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16498. return false;
  16499. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16500. return false;
  16501. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16502. return false;
  16503. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16504. return false;
  16505. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16506. return false;
  16507. return true;
  16508. };
  16509. return BoundingInfo;
  16510. }());
  16511. BABYLON.BoundingInfo = BoundingInfo;
  16512. })(BABYLON || (BABYLON = {}));
  16513. //# sourceMappingURL=babylon.boundingInfo.js.map
  16514. "use strict";
  16515. var BABYLON;
  16516. (function (BABYLON) {
  16517. var TransformNode = /** @class */ (function (_super) {
  16518. __extends(TransformNode, _super);
  16519. function TransformNode(name, scene, isPure) {
  16520. if (scene === void 0) { scene = null; }
  16521. if (isPure === void 0) { isPure = true; }
  16522. var _this = _super.call(this, name, scene) || this;
  16523. _this._forward = new BABYLON.Vector3(0, 0, 1);
  16524. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  16525. _this._up = new BABYLON.Vector3(0, 1, 0);
  16526. _this._right = new BABYLON.Vector3(1, 0, 0);
  16527. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  16528. // Properties
  16529. _this._rotation = BABYLON.Vector3.Zero();
  16530. _this._scaling = BABYLON.Vector3.One();
  16531. _this._isDirty = false;
  16532. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  16533. _this.scalingDeterminant = 1;
  16534. _this.infiniteDistance = false;
  16535. _this.position = BABYLON.Vector3.Zero();
  16536. _this._localWorld = BABYLON.Matrix.Zero();
  16537. _this._worldMatrix = BABYLON.Matrix.Zero();
  16538. _this._worldMatrixDeterminant = 0;
  16539. _this._absolutePosition = BABYLON.Vector3.Zero();
  16540. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16541. _this._postMultiplyPivotMatrix = false;
  16542. _this._isWorldMatrixFrozen = false;
  16543. /**
  16544. * An event triggered after the world matrix is updated
  16545. * @type {BABYLON.Observable}
  16546. */
  16547. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16548. _this._nonUniformScaling = false;
  16549. if (isPure) {
  16550. _this.getScene().addTransformNode(_this);
  16551. }
  16552. return _this;
  16553. }
  16554. /**
  16555. * Gets a string idenfifying the name of the class
  16556. * @returns "TransformNode" string
  16557. */
  16558. TransformNode.prototype.getClassName = function () {
  16559. return "TransformNode";
  16560. };
  16561. Object.defineProperty(TransformNode.prototype, "rotation", {
  16562. /**
  16563. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16564. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16565. * Default : (0.0, 0.0, 0.0)
  16566. */
  16567. get: function () {
  16568. return this._rotation;
  16569. },
  16570. set: function (newRotation) {
  16571. this._rotation = newRotation;
  16572. },
  16573. enumerable: true,
  16574. configurable: true
  16575. });
  16576. Object.defineProperty(TransformNode.prototype, "scaling", {
  16577. /**
  16578. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16579. * Default : (1.0, 1.0, 1.0)
  16580. */
  16581. get: function () {
  16582. return this._scaling;
  16583. },
  16584. /**
  16585. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16586. * Default : (1.0, 1.0, 1.0)
  16587. */
  16588. set: function (newScaling) {
  16589. this._scaling = newScaling;
  16590. },
  16591. enumerable: true,
  16592. configurable: true
  16593. });
  16594. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16595. /**
  16596. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16597. * It's null by default.
  16598. * 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)
  16599. */
  16600. get: function () {
  16601. return this._rotationQuaternion;
  16602. },
  16603. set: function (quaternion) {
  16604. this._rotationQuaternion = quaternion;
  16605. //reset the rotation vector.
  16606. if (quaternion && this.rotation.length()) {
  16607. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16608. }
  16609. },
  16610. enumerable: true,
  16611. configurable: true
  16612. });
  16613. Object.defineProperty(TransformNode.prototype, "forward", {
  16614. /**
  16615. * The forward direction of that transform in world space.
  16616. */
  16617. get: function () {
  16618. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  16619. },
  16620. enumerable: true,
  16621. configurable: true
  16622. });
  16623. Object.defineProperty(TransformNode.prototype, "up", {
  16624. /**
  16625. * The up direction of that transform in world space.
  16626. */
  16627. get: function () {
  16628. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  16629. },
  16630. enumerable: true,
  16631. configurable: true
  16632. });
  16633. Object.defineProperty(TransformNode.prototype, "right", {
  16634. /**
  16635. * The right direction of that transform in world space.
  16636. */
  16637. get: function () {
  16638. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  16639. },
  16640. enumerable: true,
  16641. configurable: true
  16642. });
  16643. /**
  16644. * Returns the latest update of the World matrix
  16645. * Returns a Matrix.
  16646. */
  16647. TransformNode.prototype.getWorldMatrix = function () {
  16648. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16649. this.computeWorldMatrix();
  16650. }
  16651. return this._worldMatrix;
  16652. };
  16653. /**
  16654. * Returns the latest update of the World matrix determinant.
  16655. */
  16656. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16657. return this._worldMatrixDeterminant;
  16658. };
  16659. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16660. /**
  16661. * Returns directly the latest state of the mesh World matrix.
  16662. * A Matrix is returned.
  16663. */
  16664. get: function () {
  16665. return this._worldMatrix;
  16666. },
  16667. enumerable: true,
  16668. configurable: true
  16669. });
  16670. /**
  16671. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16672. * Returns the TransformNode.
  16673. */
  16674. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16675. this._poseMatrix.copyFrom(matrix);
  16676. return this;
  16677. };
  16678. /**
  16679. * Returns the mesh Pose matrix.
  16680. * Returned object : Matrix
  16681. */
  16682. TransformNode.prototype.getPoseMatrix = function () {
  16683. return this._poseMatrix;
  16684. };
  16685. TransformNode.prototype._isSynchronized = function () {
  16686. if (this._isDirty) {
  16687. return false;
  16688. }
  16689. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  16690. return false;
  16691. if (this._cache.pivotMatrixUpdated) {
  16692. return false;
  16693. }
  16694. if (this.infiniteDistance) {
  16695. return false;
  16696. }
  16697. if (!this._cache.position.equals(this.position))
  16698. return false;
  16699. if (this.rotationQuaternion) {
  16700. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16701. return false;
  16702. }
  16703. if (!this._cache.rotation.equals(this.rotation))
  16704. return false;
  16705. if (!this._cache.scaling.equals(this.scaling))
  16706. return false;
  16707. return true;
  16708. };
  16709. TransformNode.prototype._initCache = function () {
  16710. _super.prototype._initCache.call(this);
  16711. this._cache.localMatrixUpdated = false;
  16712. this._cache.position = BABYLON.Vector3.Zero();
  16713. this._cache.scaling = BABYLON.Vector3.Zero();
  16714. this._cache.rotation = BABYLON.Vector3.Zero();
  16715. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16716. this._cache.billboardMode = -1;
  16717. };
  16718. TransformNode.prototype.markAsDirty = function (property) {
  16719. if (property === "rotation") {
  16720. this.rotationQuaternion = null;
  16721. }
  16722. this._currentRenderId = Number.MAX_VALUE;
  16723. this._isDirty = true;
  16724. return this;
  16725. };
  16726. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16727. /**
  16728. * Returns the current mesh absolute position.
  16729. * Retuns a Vector3.
  16730. */
  16731. get: function () {
  16732. return this._absolutePosition;
  16733. },
  16734. enumerable: true,
  16735. configurable: true
  16736. });
  16737. /**
  16738. * Sets a new matrix to apply before all other transformation
  16739. * @param matrix defines the transform matrix
  16740. * @returns the current TransformNode
  16741. */
  16742. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16743. return this.setPivotMatrix(matrix, false);
  16744. };
  16745. /**
  16746. * Sets a new pivot matrix to the current node
  16747. * @param matrix defines the new pivot matrix to use
  16748. * @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
  16749. * @returns the current TransformNode
  16750. */
  16751. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16752. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16753. this._pivotMatrix = matrix.clone();
  16754. this._cache.pivotMatrixUpdated = true;
  16755. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16756. if (this._postMultiplyPivotMatrix) {
  16757. if (!this._pivotMatrixInverse) {
  16758. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16759. }
  16760. else {
  16761. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16762. }
  16763. }
  16764. return this;
  16765. };
  16766. /**
  16767. * Returns the mesh pivot matrix.
  16768. * Default : Identity.
  16769. * A Matrix is returned.
  16770. */
  16771. TransformNode.prototype.getPivotMatrix = function () {
  16772. return this._pivotMatrix;
  16773. };
  16774. /**
  16775. * Prevents the World matrix to be computed any longer.
  16776. * Returns the TransformNode.
  16777. */
  16778. TransformNode.prototype.freezeWorldMatrix = function () {
  16779. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16780. this.computeWorldMatrix(true);
  16781. this._isWorldMatrixFrozen = true;
  16782. return this;
  16783. };
  16784. /**
  16785. * Allows back the World matrix computation.
  16786. * Returns the TransformNode.
  16787. */
  16788. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16789. this._isWorldMatrixFrozen = false;
  16790. this.computeWorldMatrix(true);
  16791. return this;
  16792. };
  16793. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16794. /**
  16795. * True if the World matrix has been frozen.
  16796. * Returns a boolean.
  16797. */
  16798. get: function () {
  16799. return this._isWorldMatrixFrozen;
  16800. },
  16801. enumerable: true,
  16802. configurable: true
  16803. });
  16804. /**
  16805. * Retuns the mesh absolute position in the World.
  16806. * Returns a Vector3.
  16807. */
  16808. TransformNode.prototype.getAbsolutePosition = function () {
  16809. this.computeWorldMatrix();
  16810. return this._absolutePosition;
  16811. };
  16812. /**
  16813. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16814. * Returns the TransformNode.
  16815. */
  16816. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16817. if (!absolutePosition) {
  16818. return this;
  16819. }
  16820. var absolutePositionX;
  16821. var absolutePositionY;
  16822. var absolutePositionZ;
  16823. if (absolutePosition.x === undefined) {
  16824. if (arguments.length < 3) {
  16825. return this;
  16826. }
  16827. absolutePositionX = arguments[0];
  16828. absolutePositionY = arguments[1];
  16829. absolutePositionZ = arguments[2];
  16830. }
  16831. else {
  16832. absolutePositionX = absolutePosition.x;
  16833. absolutePositionY = absolutePosition.y;
  16834. absolutePositionZ = absolutePosition.z;
  16835. }
  16836. if (this.parent) {
  16837. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16838. invertParentWorldMatrix.invert();
  16839. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16840. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16841. }
  16842. else {
  16843. this.position.x = absolutePositionX;
  16844. this.position.y = absolutePositionY;
  16845. this.position.z = absolutePositionZ;
  16846. }
  16847. return this;
  16848. };
  16849. /**
  16850. * Sets the mesh position in its local space.
  16851. * Returns the TransformNode.
  16852. */
  16853. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16854. this.computeWorldMatrix();
  16855. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16856. return this;
  16857. };
  16858. /**
  16859. * Returns the mesh position in the local space from the current World matrix values.
  16860. * Returns a new Vector3.
  16861. */
  16862. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16863. this.computeWorldMatrix();
  16864. var invLocalWorldMatrix = this._localWorld.clone();
  16865. invLocalWorldMatrix.invert();
  16866. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16867. };
  16868. /**
  16869. * Translates the mesh along the passed Vector3 in its local space.
  16870. * Returns the TransformNode.
  16871. */
  16872. TransformNode.prototype.locallyTranslate = function (vector3) {
  16873. this.computeWorldMatrix(true);
  16874. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16875. return this;
  16876. };
  16877. /**
  16878. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16879. * @param targetPoint the position (must be in same space as current mesh) to look at
  16880. * @param yawCor optional yaw (y-axis) correction in radians
  16881. * @param pitchCor optional pitch (x-axis) correction in radians
  16882. * @param rollCor optional roll (z-axis) correction in radians
  16883. * @param space the choosen space of the target
  16884. * @returns the TransformNode.
  16885. */
  16886. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16887. if (yawCor === void 0) { yawCor = 0; }
  16888. if (pitchCor === void 0) { pitchCor = 0; }
  16889. if (rollCor === void 0) { rollCor = 0; }
  16890. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16891. var dv = TransformNode._lookAtVectorCache;
  16892. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16893. targetPoint.subtractToRef(pos, dv);
  16894. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16895. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16896. var pitch = Math.atan2(dv.y, len);
  16897. if (this.rotationQuaternion) {
  16898. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16899. }
  16900. else {
  16901. this.rotation.x = pitch + pitchCor;
  16902. this.rotation.y = yaw + yawCor;
  16903. this.rotation.z = rollCor;
  16904. }
  16905. return this;
  16906. };
  16907. /**
  16908. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16909. * This Vector3 is expressed in the World space.
  16910. */
  16911. TransformNode.prototype.getDirection = function (localAxis) {
  16912. var result = BABYLON.Vector3.Zero();
  16913. this.getDirectionToRef(localAxis, result);
  16914. return result;
  16915. };
  16916. /**
  16917. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16918. * localAxis is expressed in the mesh local space.
  16919. * result is computed in the Wordl space from the mesh World matrix.
  16920. * Returns the TransformNode.
  16921. */
  16922. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16923. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16924. return this;
  16925. };
  16926. /**
  16927. * Sets a new pivot point to the current node
  16928. * @param point defines the new pivot point to use
  16929. * @param space defines if the point is in world or local space (local by default)
  16930. * @returns the current TransformNode
  16931. */
  16932. TransformNode.prototype.setPivotPoint = function (point, space) {
  16933. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16934. if (this.getScene().getRenderId() == 0) {
  16935. this.computeWorldMatrix(true);
  16936. }
  16937. var wm = this.getWorldMatrix();
  16938. if (space == BABYLON.Space.WORLD) {
  16939. var tmat = BABYLON.Tmp.Matrix[0];
  16940. wm.invertToRef(tmat);
  16941. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16942. }
  16943. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16944. };
  16945. /**
  16946. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16947. */
  16948. TransformNode.prototype.getPivotPoint = function () {
  16949. var point = BABYLON.Vector3.Zero();
  16950. this.getPivotPointToRef(point);
  16951. return point;
  16952. };
  16953. /**
  16954. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16955. * Returns the TransformNode.
  16956. */
  16957. TransformNode.prototype.getPivotPointToRef = function (result) {
  16958. result.x = -this._pivotMatrix.m[12];
  16959. result.y = -this._pivotMatrix.m[13];
  16960. result.z = -this._pivotMatrix.m[14];
  16961. return this;
  16962. };
  16963. /**
  16964. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16965. */
  16966. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16967. var point = BABYLON.Vector3.Zero();
  16968. this.getAbsolutePivotPointToRef(point);
  16969. return point;
  16970. };
  16971. /**
  16972. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16973. * Returns the TransformNode.
  16974. */
  16975. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16976. result.x = this._pivotMatrix.m[12];
  16977. result.y = this._pivotMatrix.m[13];
  16978. result.z = this._pivotMatrix.m[14];
  16979. this.getPivotPointToRef(result);
  16980. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16981. return this;
  16982. };
  16983. /**
  16984. * Defines the passed node as the parent of the current node.
  16985. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16986. * Returns the TransformNode.
  16987. */
  16988. TransformNode.prototype.setParent = function (node) {
  16989. if (node === null) {
  16990. var rotation = BABYLON.Tmp.Quaternion[0];
  16991. var position = BABYLON.Tmp.Vector3[0];
  16992. var scale = BABYLON.Tmp.Vector3[1];
  16993. if (this.parent && this.parent.computeWorldMatrix) {
  16994. this.parent.computeWorldMatrix(true);
  16995. }
  16996. this.computeWorldMatrix(true);
  16997. this.getWorldMatrix().decompose(scale, rotation, position);
  16998. if (this.rotationQuaternion) {
  16999. this.rotationQuaternion.copyFrom(rotation);
  17000. }
  17001. else {
  17002. rotation.toEulerAnglesToRef(this.rotation);
  17003. }
  17004. this.scaling.x = scale.x;
  17005. this.scaling.y = scale.y;
  17006. this.scaling.z = scale.z;
  17007. this.position.x = position.x;
  17008. this.position.y = position.y;
  17009. this.position.z = position.z;
  17010. }
  17011. else {
  17012. var rotation = BABYLON.Tmp.Quaternion[0];
  17013. var position = BABYLON.Tmp.Vector3[0];
  17014. var scale = BABYLON.Tmp.Vector3[1];
  17015. var diffMatrix = BABYLON.Tmp.Matrix[0];
  17016. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  17017. this.computeWorldMatrix(true);
  17018. node.computeWorldMatrix(true);
  17019. node.getWorldMatrix().invertToRef(invParentMatrix);
  17020. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  17021. diffMatrix.decompose(scale, rotation, position);
  17022. if (this.rotationQuaternion) {
  17023. this.rotationQuaternion.copyFrom(rotation);
  17024. }
  17025. else {
  17026. rotation.toEulerAnglesToRef(this.rotation);
  17027. }
  17028. this.position.x = position.x;
  17029. this.position.y = position.y;
  17030. this.position.z = position.z;
  17031. this.scaling.x = scale.x;
  17032. this.scaling.y = scale.y;
  17033. this.scaling.z = scale.z;
  17034. }
  17035. this.parent = node;
  17036. return this;
  17037. };
  17038. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17039. get: function () {
  17040. return this._nonUniformScaling;
  17041. },
  17042. enumerable: true,
  17043. configurable: true
  17044. });
  17045. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17046. if (this._nonUniformScaling === value) {
  17047. return false;
  17048. }
  17049. this._nonUniformScaling = true;
  17050. return true;
  17051. };
  17052. /**
  17053. * Attach the current TransformNode to another TransformNode associated with a bone
  17054. * @param bone Bone affecting the TransformNode
  17055. * @param affectedTransformNode TransformNode associated with the bone
  17056. */
  17057. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17058. this._transformToBoneReferal = affectedTransformNode;
  17059. this.parent = bone;
  17060. if (bone.getWorldMatrix().determinant() < 0) {
  17061. this.scalingDeterminant *= -1;
  17062. }
  17063. return this;
  17064. };
  17065. TransformNode.prototype.detachFromBone = function () {
  17066. if (!this.parent) {
  17067. return this;
  17068. }
  17069. if (this.parent.getWorldMatrix().determinant() < 0) {
  17070. this.scalingDeterminant *= -1;
  17071. }
  17072. this._transformToBoneReferal = null;
  17073. this.parent = null;
  17074. return this;
  17075. };
  17076. /**
  17077. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17078. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17079. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17080. * The passed axis is also normalized.
  17081. * Returns the TransformNode.
  17082. */
  17083. TransformNode.prototype.rotate = function (axis, amount, space) {
  17084. axis.normalize();
  17085. if (!this.rotationQuaternion) {
  17086. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17087. this.rotation = BABYLON.Vector3.Zero();
  17088. }
  17089. var rotationQuaternion;
  17090. if (!space || space === BABYLON.Space.LOCAL) {
  17091. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  17092. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17093. }
  17094. else {
  17095. if (this.parent) {
  17096. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17097. invertParentWorldMatrix.invert();
  17098. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17099. }
  17100. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  17101. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17102. }
  17103. return this;
  17104. };
  17105. /**
  17106. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17107. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17108. * The passed axis is also normalized.
  17109. * Returns the TransformNode.
  17110. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17111. */
  17112. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17113. axis.normalize();
  17114. if (!this.rotationQuaternion) {
  17115. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17116. this.rotation.copyFromFloats(0, 0, 0);
  17117. }
  17118. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17119. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17120. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17121. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17122. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17123. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17124. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17125. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17126. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17127. return this;
  17128. };
  17129. /**
  17130. * Translates the mesh along the axis vector for the passed distance in the given space.
  17131. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17132. * Returns the TransformNode.
  17133. */
  17134. TransformNode.prototype.translate = function (axis, distance, space) {
  17135. var displacementVector = axis.scale(distance);
  17136. if (!space || space === BABYLON.Space.LOCAL) {
  17137. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17138. this.setPositionWithLocalVector(tempV3);
  17139. }
  17140. else {
  17141. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17142. }
  17143. return this;
  17144. };
  17145. /**
  17146. * Adds a rotation step to the mesh current rotation.
  17147. * x, y, z are Euler angles expressed in radians.
  17148. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17149. * This means this rotation is made in the mesh local space only.
  17150. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17151. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17152. * ```javascript
  17153. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17154. * ```
  17155. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17156. * 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.
  17157. * Returns the TransformNode.
  17158. */
  17159. TransformNode.prototype.addRotation = function (x, y, z) {
  17160. var rotationQuaternion;
  17161. if (this.rotationQuaternion) {
  17162. rotationQuaternion = this.rotationQuaternion;
  17163. }
  17164. else {
  17165. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17166. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17167. }
  17168. var accumulation = BABYLON.Tmp.Quaternion[0];
  17169. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17170. rotationQuaternion.multiplyInPlace(accumulation);
  17171. if (!this.rotationQuaternion) {
  17172. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17173. }
  17174. return this;
  17175. };
  17176. /**
  17177. * Computes the mesh World matrix and returns it.
  17178. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17179. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17180. * If the parameter `force`is set to `true`, the actual computation is done.
  17181. * Returns the mesh World Matrix.
  17182. */
  17183. TransformNode.prototype.computeWorldMatrix = function (force) {
  17184. if (this._isWorldMatrixFrozen) {
  17185. return this._worldMatrix;
  17186. }
  17187. if (!force && this.isSynchronized(true)) {
  17188. this._currentRenderId = this.getScene().getRenderId();
  17189. return this._worldMatrix;
  17190. }
  17191. this._cache.position.copyFrom(this.position);
  17192. this._cache.scaling.copyFrom(this.scaling);
  17193. this._cache.pivotMatrixUpdated = false;
  17194. this._cache.billboardMode = this.billboardMode;
  17195. this._currentRenderId = this.getScene().getRenderId();
  17196. this._childRenderId = this.getScene().getRenderId();
  17197. this._isDirty = false;
  17198. // Scaling
  17199. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17200. // Rotation
  17201. //rotate, if quaternion is set and rotation was used
  17202. if (this.rotationQuaternion) {
  17203. var len = this.rotation.length();
  17204. if (len) {
  17205. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17206. this.rotation.copyFromFloats(0, 0, 0);
  17207. }
  17208. }
  17209. if (this.rotationQuaternion) {
  17210. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17211. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17212. }
  17213. else {
  17214. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17215. this._cache.rotation.copyFrom(this.rotation);
  17216. }
  17217. // Translation
  17218. var camera = this.getScene().activeCamera;
  17219. if (this.infiniteDistance && !this.parent && camera) {
  17220. var cameraWorldMatrix = camera.getWorldMatrix();
  17221. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17222. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17223. }
  17224. else {
  17225. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17226. }
  17227. // Composing transformations
  17228. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17229. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17230. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17231. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  17232. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  17233. // Need to decompose each rotation here
  17234. var currentPosition = BABYLON.Tmp.Vector3[3];
  17235. if (this.parent && this.parent.getWorldMatrix) {
  17236. if (this._transformToBoneReferal) {
  17237. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17238. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17239. }
  17240. else {
  17241. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17242. }
  17243. }
  17244. else {
  17245. currentPosition.copyFrom(this.position);
  17246. }
  17247. currentPosition.subtractInPlace(camera.globalPosition);
  17248. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17249. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  17250. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17251. }
  17252. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  17253. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17254. }
  17255. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  17256. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17257. }
  17258. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17259. }
  17260. else {
  17261. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17262. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17263. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17264. }
  17265. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17266. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17267. }
  17268. // Local world
  17269. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17270. // Parent
  17271. if (this.parent && this.parent.getWorldMatrix) {
  17272. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  17273. if (this._transformToBoneReferal) {
  17274. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17275. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17276. }
  17277. else {
  17278. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17279. }
  17280. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17281. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17282. this._worldMatrix.copyFrom(this._localWorld);
  17283. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17284. }
  17285. else {
  17286. if (this._transformToBoneReferal) {
  17287. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17288. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17289. }
  17290. else {
  17291. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17292. }
  17293. }
  17294. this._markSyncedWithParent();
  17295. }
  17296. else {
  17297. this._worldMatrix.copyFrom(this._localWorld);
  17298. }
  17299. // Post multiply inverse of pivotMatrix
  17300. if (this._postMultiplyPivotMatrix) {
  17301. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17302. }
  17303. // Normal matrix
  17304. if (this.scaling.isNonUniform) {
  17305. this._updateNonUniformScalingState(true);
  17306. }
  17307. else if (this.parent && this.parent._nonUniformScaling) {
  17308. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17309. }
  17310. else {
  17311. this._updateNonUniformScalingState(false);
  17312. }
  17313. this._afterComputeWorldMatrix();
  17314. // Absolute position
  17315. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17316. // Callbacks
  17317. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17318. if (!this._poseMatrix) {
  17319. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17320. }
  17321. // Cache the determinant
  17322. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17323. return this._worldMatrix;
  17324. };
  17325. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17326. };
  17327. /**
  17328. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17329. * @param func: callback function to add
  17330. *
  17331. * Returns the TransformNode.
  17332. */
  17333. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17334. this.onAfterWorldMatrixUpdateObservable.add(func);
  17335. return this;
  17336. };
  17337. /**
  17338. * Removes a registered callback function.
  17339. * Returns the TransformNode.
  17340. */
  17341. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17342. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17343. return this;
  17344. };
  17345. /**
  17346. * Clone the current transform node
  17347. * Returns the new transform node
  17348. * @param name Name of the new clone
  17349. * @param newParent New parent for the clone
  17350. * @param doNotCloneChildren Do not clone children hierarchy
  17351. */
  17352. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17353. var _this = this;
  17354. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17355. result.name = name;
  17356. result.id = name;
  17357. if (newParent) {
  17358. result.parent = newParent;
  17359. }
  17360. if (!doNotCloneChildren) {
  17361. // Children
  17362. var directDescendants = this.getDescendants(true);
  17363. for (var index = 0; index < directDescendants.length; index++) {
  17364. var child = directDescendants[index];
  17365. if (child.clone) {
  17366. child.clone(name + "." + child.name, result);
  17367. }
  17368. }
  17369. }
  17370. return result;
  17371. };
  17372. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17373. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17374. serializationObject.type = this.getClassName();
  17375. // Parent
  17376. if (this.parent) {
  17377. serializationObject.parentId = this.parent.id;
  17378. }
  17379. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17380. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17381. }
  17382. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17383. serializationObject.isEnabled = this.isEnabled();
  17384. // Parent
  17385. if (this.parent) {
  17386. serializationObject.parentId = this.parent.id;
  17387. }
  17388. return serializationObject;
  17389. };
  17390. // Statics
  17391. /**
  17392. * Returns a new TransformNode object parsed from the source provided.
  17393. * The parameter `parsedMesh` is the source.
  17394. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17395. */
  17396. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17397. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17398. if (BABYLON.Tags) {
  17399. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17400. }
  17401. if (parsedTransformNode.localMatrix) {
  17402. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17403. }
  17404. else if (parsedTransformNode.pivotMatrix) {
  17405. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17406. }
  17407. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17408. // Parent
  17409. if (parsedTransformNode.parentId) {
  17410. transformNode._waitingParentId = parsedTransformNode.parentId;
  17411. }
  17412. return transformNode;
  17413. };
  17414. /**
  17415. * Releases resources associated with this transform node.
  17416. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17417. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17418. */
  17419. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17420. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17421. // Animations
  17422. this.getScene().stopAnimation(this);
  17423. // Remove from scene
  17424. this.getScene().removeTransformNode(this);
  17425. this.onAfterWorldMatrixUpdateObservable.clear();
  17426. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17427. };
  17428. // Statics
  17429. TransformNode.BILLBOARDMODE_NONE = 0;
  17430. TransformNode.BILLBOARDMODE_X = 1;
  17431. TransformNode.BILLBOARDMODE_Y = 2;
  17432. TransformNode.BILLBOARDMODE_Z = 4;
  17433. TransformNode.BILLBOARDMODE_ALL = 7;
  17434. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17435. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17436. __decorate([
  17437. BABYLON.serializeAsVector3()
  17438. ], TransformNode.prototype, "_rotation", void 0);
  17439. __decorate([
  17440. BABYLON.serializeAsQuaternion()
  17441. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17442. __decorate([
  17443. BABYLON.serializeAsVector3()
  17444. ], TransformNode.prototype, "_scaling", void 0);
  17445. __decorate([
  17446. BABYLON.serialize()
  17447. ], TransformNode.prototype, "billboardMode", void 0);
  17448. __decorate([
  17449. BABYLON.serialize()
  17450. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17451. __decorate([
  17452. BABYLON.serialize()
  17453. ], TransformNode.prototype, "infiniteDistance", void 0);
  17454. __decorate([
  17455. BABYLON.serializeAsVector3()
  17456. ], TransformNode.prototype, "position", void 0);
  17457. return TransformNode;
  17458. }(BABYLON.Node));
  17459. BABYLON.TransformNode = TransformNode;
  17460. })(BABYLON || (BABYLON = {}));
  17461. //# sourceMappingURL=babylon.transformNode.js.map
  17462. "use strict";
  17463. var BABYLON;
  17464. (function (BABYLON) {
  17465. var AbstractMesh = /** @class */ (function (_super) {
  17466. __extends(AbstractMesh, _super);
  17467. // Constructor
  17468. function AbstractMesh(name, scene) {
  17469. if (scene === void 0) { scene = null; }
  17470. var _this = _super.call(this, name, scene, false) || this;
  17471. _this._facetNb = 0; // facet number
  17472. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17473. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17474. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17475. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17476. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17477. _this._subDiv = {
  17478. max: 1,
  17479. X: 1,
  17480. Y: 1,
  17481. Z: 1
  17482. };
  17483. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17484. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17485. // Events
  17486. /**
  17487. * An event triggered when this mesh collides with another one
  17488. * @type {BABYLON.Observable}
  17489. */
  17490. _this.onCollideObservable = new BABYLON.Observable();
  17491. /**
  17492. * An event triggered when the collision's position changes
  17493. * @type {BABYLON.Observable}
  17494. */
  17495. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17496. /**
  17497. * An event triggered when material is changed
  17498. * @type {BABYLON.Observable}
  17499. */
  17500. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17501. // Properties
  17502. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17503. /**
  17504. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17505. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17506. * or
  17507. * 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.
  17508. * for more info check WebGl documentations
  17509. */
  17510. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17511. /**
  17512. * 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:
  17513. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17514. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17515. * 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.
  17516. */
  17517. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17518. /**
  17519. * 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.
  17520. * The default value is -1 which means don't break the query and wait till the result.
  17521. */
  17522. _this.occlusionRetryCount = -1;
  17523. _this._occlusionInternalRetryCounter = 0;
  17524. _this._isOccluded = false;
  17525. _this._isOcclusionQueryInProgress = false;
  17526. _this._visibility = 1.0;
  17527. _this.alphaIndex = Number.MAX_VALUE;
  17528. _this.isVisible = true;
  17529. _this.isPickable = true;
  17530. _this.showBoundingBox = false;
  17531. _this.showSubMeshesBoundingBox = false;
  17532. _this.isBlocker = false;
  17533. _this.enablePointerMoveEvents = false;
  17534. _this.renderingGroupId = 0;
  17535. _this._receiveShadows = false;
  17536. _this.renderOutline = false;
  17537. _this.outlineColor = BABYLON.Color3.Red();
  17538. _this.outlineWidth = 0.02;
  17539. _this.renderOverlay = false;
  17540. _this.overlayColor = BABYLON.Color3.Red();
  17541. _this.overlayAlpha = 0.5;
  17542. _this._hasVertexAlpha = false;
  17543. _this._useVertexColors = true;
  17544. _this._computeBonesUsingShaders = true;
  17545. _this._numBoneInfluencers = 4;
  17546. _this._applyFog = true;
  17547. _this.useOctreeForRenderingSelection = true;
  17548. _this.useOctreeForPicking = true;
  17549. _this.useOctreeForCollisions = true;
  17550. _this._layerMask = 0x0FFFFFFF;
  17551. /**
  17552. * True if the mesh must be rendered in any case.
  17553. */
  17554. _this.alwaysSelectAsActiveMesh = false;
  17555. /**
  17556. * This scene's action manager
  17557. * @type {BABYLON.ActionManager}
  17558. */
  17559. _this.actionManager = null;
  17560. // Physics
  17561. _this.physicsImpostor = null;
  17562. // Collisions
  17563. _this._checkCollisions = false;
  17564. _this._collisionMask = -1;
  17565. _this._collisionGroup = -1;
  17566. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17567. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17568. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17569. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17570. // Edges
  17571. _this.edgesWidth = 1;
  17572. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17573. // Cache
  17574. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17575. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17576. _this._renderId = 0;
  17577. _this._intersectionsInProgress = new Array();
  17578. _this._unIndexed = false;
  17579. _this._lightSources = new Array();
  17580. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17581. if (collidedMesh === void 0) { collidedMesh = null; }
  17582. //TODO move this to the collision coordinator!
  17583. if (_this.getScene().workerCollisions)
  17584. newPosition.multiplyInPlace(_this._collider._radius);
  17585. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17586. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17587. _this.position.addInPlace(_this._diffPositionForCollisions);
  17588. }
  17589. if (collidedMesh) {
  17590. _this.onCollideObservable.notifyObservers(collidedMesh);
  17591. }
  17592. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17593. };
  17594. _this.getScene().addMesh(_this);
  17595. _this._resyncLightSources();
  17596. return _this;
  17597. }
  17598. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17599. get: function () {
  17600. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17601. },
  17602. enumerable: true,
  17603. configurable: true
  17604. });
  17605. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17606. get: function () {
  17607. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17608. },
  17609. enumerable: true,
  17610. configurable: true
  17611. });
  17612. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17613. get: function () {
  17614. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17615. },
  17616. enumerable: true,
  17617. configurable: true
  17618. });
  17619. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17620. get: function () {
  17621. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17622. },
  17623. enumerable: true,
  17624. configurable: true
  17625. });
  17626. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17627. get: function () {
  17628. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17629. },
  17630. enumerable: true,
  17631. configurable: true
  17632. });
  17633. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17634. /**
  17635. * Read-only : the number of facets in the mesh
  17636. */
  17637. get: function () {
  17638. return this._facetNb;
  17639. },
  17640. enumerable: true,
  17641. configurable: true
  17642. });
  17643. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17644. /**
  17645. * The number (integer) of subdivisions per axis in the partioning space
  17646. */
  17647. get: function () {
  17648. return this._partitioningSubdivisions;
  17649. },
  17650. set: function (nb) {
  17651. this._partitioningSubdivisions = nb;
  17652. },
  17653. enumerable: true,
  17654. configurable: true
  17655. });
  17656. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17657. /**
  17658. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17659. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17660. */
  17661. get: function () {
  17662. return this._partitioningBBoxRatio;
  17663. },
  17664. set: function (ratio) {
  17665. this._partitioningBBoxRatio = ratio;
  17666. },
  17667. enumerable: true,
  17668. configurable: true
  17669. });
  17670. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17671. /**
  17672. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17673. * Works only for updatable meshes.
  17674. * Doesn't work with multi-materials.
  17675. */
  17676. get: function () {
  17677. return this._facetDepthSort;
  17678. },
  17679. set: function (sort) {
  17680. this._facetDepthSort = sort;
  17681. },
  17682. enumerable: true,
  17683. configurable: true
  17684. });
  17685. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17686. /**
  17687. * The location (Vector3) where the facet depth sort must be computed from.
  17688. * By default, the active camera position.
  17689. * Used only when facet depth sort is enabled.
  17690. */
  17691. get: function () {
  17692. return this._facetDepthSortFrom;
  17693. },
  17694. set: function (location) {
  17695. this._facetDepthSortFrom = location;
  17696. },
  17697. enumerable: true,
  17698. configurable: true
  17699. });
  17700. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17701. /**
  17702. * Read-only boolean : is the feature facetData enabled ?
  17703. */
  17704. get: function () {
  17705. return this._facetDataEnabled;
  17706. },
  17707. enumerable: true,
  17708. configurable: true
  17709. });
  17710. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17711. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17712. return false;
  17713. }
  17714. this._markSubMeshesAsMiscDirty();
  17715. return true;
  17716. };
  17717. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17718. set: function (callback) {
  17719. if (this._onCollideObserver) {
  17720. this.onCollideObservable.remove(this._onCollideObserver);
  17721. }
  17722. this._onCollideObserver = this.onCollideObservable.add(callback);
  17723. },
  17724. enumerable: true,
  17725. configurable: true
  17726. });
  17727. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17728. set: function (callback) {
  17729. if (this._onCollisionPositionChangeObserver) {
  17730. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17731. }
  17732. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17733. },
  17734. enumerable: true,
  17735. configurable: true
  17736. });
  17737. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17738. /**
  17739. * 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.
  17740. */
  17741. get: function () {
  17742. return this._isOccluded;
  17743. },
  17744. set: function (value) {
  17745. this._isOccluded = value;
  17746. },
  17747. enumerable: true,
  17748. configurable: true
  17749. });
  17750. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17751. /**
  17752. * Flag to check the progress status of the query
  17753. */
  17754. get: function () {
  17755. return this._isOcclusionQueryInProgress;
  17756. },
  17757. enumerable: true,
  17758. configurable: true
  17759. });
  17760. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17761. /**
  17762. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17763. */
  17764. get: function () {
  17765. return this._visibility;
  17766. },
  17767. /**
  17768. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17769. */
  17770. set: function (value) {
  17771. if (this._visibility === value) {
  17772. return;
  17773. }
  17774. this._visibility = value;
  17775. this._markSubMeshesAsMiscDirty();
  17776. },
  17777. enumerable: true,
  17778. configurable: true
  17779. });
  17780. Object.defineProperty(AbstractMesh.prototype, "material", {
  17781. get: function () {
  17782. return this._material;
  17783. },
  17784. set: function (value) {
  17785. if (this._material === value) {
  17786. return;
  17787. }
  17788. this._material = value;
  17789. if (this.onMaterialChangedObservable.hasObservers) {
  17790. this.onMaterialChangedObservable.notifyObservers(this);
  17791. }
  17792. if (!this.subMeshes) {
  17793. return;
  17794. }
  17795. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17796. var subMesh = _a[_i];
  17797. subMesh.setEffect(null);
  17798. }
  17799. },
  17800. enumerable: true,
  17801. configurable: true
  17802. });
  17803. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17804. get: function () {
  17805. return this._receiveShadows;
  17806. },
  17807. set: function (value) {
  17808. if (this._receiveShadows === value) {
  17809. return;
  17810. }
  17811. this._receiveShadows = value;
  17812. this._markSubMeshesAsLightDirty();
  17813. },
  17814. enumerable: true,
  17815. configurable: true
  17816. });
  17817. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17818. get: function () {
  17819. return this._hasVertexAlpha;
  17820. },
  17821. set: function (value) {
  17822. if (this._hasVertexAlpha === value) {
  17823. return;
  17824. }
  17825. this._hasVertexAlpha = value;
  17826. this._markSubMeshesAsAttributesDirty();
  17827. this._markSubMeshesAsMiscDirty();
  17828. },
  17829. enumerable: true,
  17830. configurable: true
  17831. });
  17832. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17833. get: function () {
  17834. return this._useVertexColors;
  17835. },
  17836. set: function (value) {
  17837. if (this._useVertexColors === value) {
  17838. return;
  17839. }
  17840. this._useVertexColors = value;
  17841. this._markSubMeshesAsAttributesDirty();
  17842. },
  17843. enumerable: true,
  17844. configurable: true
  17845. });
  17846. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17847. get: function () {
  17848. return this._computeBonesUsingShaders;
  17849. },
  17850. set: function (value) {
  17851. if (this._computeBonesUsingShaders === value) {
  17852. return;
  17853. }
  17854. this._computeBonesUsingShaders = value;
  17855. this._markSubMeshesAsAttributesDirty();
  17856. },
  17857. enumerable: true,
  17858. configurable: true
  17859. });
  17860. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17861. get: function () {
  17862. return this._numBoneInfluencers;
  17863. },
  17864. set: function (value) {
  17865. if (this._numBoneInfluencers === value) {
  17866. return;
  17867. }
  17868. this._numBoneInfluencers = value;
  17869. this._markSubMeshesAsAttributesDirty();
  17870. },
  17871. enumerable: true,
  17872. configurable: true
  17873. });
  17874. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17875. get: function () {
  17876. return this._applyFog;
  17877. },
  17878. set: function (value) {
  17879. if (this._applyFog === value) {
  17880. return;
  17881. }
  17882. this._applyFog = value;
  17883. this._markSubMeshesAsMiscDirty();
  17884. },
  17885. enumerable: true,
  17886. configurable: true
  17887. });
  17888. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17889. get: function () {
  17890. return this._layerMask;
  17891. },
  17892. set: function (value) {
  17893. if (value === this._layerMask) {
  17894. return;
  17895. }
  17896. this._layerMask = value;
  17897. this._resyncLightSources();
  17898. },
  17899. enumerable: true,
  17900. configurable: true
  17901. });
  17902. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17903. get: function () {
  17904. return this._collisionMask;
  17905. },
  17906. set: function (mask) {
  17907. this._collisionMask = !isNaN(mask) ? mask : -1;
  17908. },
  17909. enumerable: true,
  17910. configurable: true
  17911. });
  17912. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17913. get: function () {
  17914. return this._collisionGroup;
  17915. },
  17916. set: function (mask) {
  17917. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17918. },
  17919. enumerable: true,
  17920. configurable: true
  17921. });
  17922. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17923. get: function () {
  17924. return null;
  17925. },
  17926. enumerable: true,
  17927. configurable: true
  17928. });
  17929. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17930. get: function () {
  17931. return this._skeleton;
  17932. },
  17933. set: function (value) {
  17934. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17935. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17936. }
  17937. if (value && value.needInitialSkinMatrix) {
  17938. value._registerMeshWithPoseMatrix(this);
  17939. }
  17940. this._skeleton = value;
  17941. if (!this._skeleton) {
  17942. this._bonesTransformMatrices = null;
  17943. }
  17944. this._markSubMeshesAsAttributesDirty();
  17945. },
  17946. enumerable: true,
  17947. configurable: true
  17948. });
  17949. /**
  17950. * Returns the string "AbstractMesh"
  17951. */
  17952. AbstractMesh.prototype.getClassName = function () {
  17953. return "AbstractMesh";
  17954. };
  17955. /**
  17956. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17957. */
  17958. AbstractMesh.prototype.toString = function (fullDetails) {
  17959. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17960. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17961. if (this._skeleton) {
  17962. ret += ", skeleton: " + this._skeleton.name;
  17963. }
  17964. if (fullDetails) {
  17965. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17966. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17967. }
  17968. return ret;
  17969. };
  17970. AbstractMesh.prototype._rebuild = function () {
  17971. if (this._occlusionQuery) {
  17972. this._occlusionQuery = null;
  17973. }
  17974. if (this._edgesRenderer) {
  17975. this._edgesRenderer._rebuild();
  17976. }
  17977. if (!this.subMeshes) {
  17978. return;
  17979. }
  17980. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17981. var subMesh = _a[_i];
  17982. subMesh._rebuild();
  17983. }
  17984. };
  17985. AbstractMesh.prototype._resyncLightSources = function () {
  17986. this._lightSources.length = 0;
  17987. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17988. var light = _a[_i];
  17989. if (!light.isEnabled()) {
  17990. continue;
  17991. }
  17992. if (light.canAffectMesh(this)) {
  17993. this._lightSources.push(light);
  17994. }
  17995. }
  17996. this._markSubMeshesAsLightDirty();
  17997. };
  17998. AbstractMesh.prototype._resyncLighSource = function (light) {
  17999. var isIn = light.isEnabled() && light.canAffectMesh(this);
  18000. var index = this._lightSources.indexOf(light);
  18001. if (index === -1) {
  18002. if (!isIn) {
  18003. return;
  18004. }
  18005. this._lightSources.push(light);
  18006. }
  18007. else {
  18008. if (isIn) {
  18009. return;
  18010. }
  18011. this._lightSources.splice(index, 1);
  18012. }
  18013. this._markSubMeshesAsLightDirty();
  18014. };
  18015. AbstractMesh.prototype._removeLightSource = function (light) {
  18016. var index = this._lightSources.indexOf(light);
  18017. if (index === -1) {
  18018. return;
  18019. }
  18020. this._lightSources.splice(index, 1);
  18021. this._markSubMeshesAsLightDirty();
  18022. };
  18023. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  18024. if (!this.subMeshes) {
  18025. return;
  18026. }
  18027. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18028. var subMesh = _a[_i];
  18029. if (subMesh._materialDefines) {
  18030. func(subMesh._materialDefines);
  18031. }
  18032. }
  18033. };
  18034. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18035. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18036. };
  18037. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18038. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18039. };
  18040. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18041. if (!this.subMeshes) {
  18042. return;
  18043. }
  18044. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18045. var subMesh = _a[_i];
  18046. var material = subMesh.getMaterial();
  18047. if (material) {
  18048. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18049. }
  18050. }
  18051. };
  18052. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18053. /**
  18054. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18055. * Default : (1.0, 1.0, 1.0)
  18056. */
  18057. get: function () {
  18058. return this._scaling;
  18059. },
  18060. /**
  18061. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18062. * Default : (1.0, 1.0, 1.0)
  18063. */
  18064. set: function (newScaling) {
  18065. this._scaling = newScaling;
  18066. if (this.physicsImpostor) {
  18067. this.physicsImpostor.forceUpdate();
  18068. }
  18069. },
  18070. enumerable: true,
  18071. configurable: true
  18072. });
  18073. // Methods
  18074. /**
  18075. * Disables the mesh edger rendering mode.
  18076. * Returns the AbstractMesh.
  18077. */
  18078. AbstractMesh.prototype.disableEdgesRendering = function () {
  18079. if (this._edgesRenderer) {
  18080. this._edgesRenderer.dispose();
  18081. this._edgesRenderer = null;
  18082. }
  18083. return this;
  18084. };
  18085. /**
  18086. * Enables the edge rendering mode on the mesh.
  18087. * This mode makes the mesh edges visible.
  18088. * Returns the AbstractMesh.
  18089. */
  18090. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18091. if (epsilon === void 0) { epsilon = 0.95; }
  18092. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18093. this.disableEdgesRendering();
  18094. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18095. return this;
  18096. };
  18097. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18098. /**
  18099. * Returns true if the mesh is blocked. Used by the class Mesh.
  18100. * Returns the boolean `false` by default.
  18101. */
  18102. get: function () {
  18103. return false;
  18104. },
  18105. enumerable: true,
  18106. configurable: true
  18107. });
  18108. /**
  18109. * Returns the mesh itself by default, used by the class Mesh.
  18110. * Returned type : AbstractMesh
  18111. */
  18112. AbstractMesh.prototype.getLOD = function (camera) {
  18113. return this;
  18114. };
  18115. /**
  18116. * Returns 0 by default, used by the class Mesh.
  18117. * Returns an integer.
  18118. */
  18119. AbstractMesh.prototype.getTotalVertices = function () {
  18120. return 0;
  18121. };
  18122. /**
  18123. * Returns null by default, used by the class Mesh.
  18124. * Returned type : integer array
  18125. */
  18126. AbstractMesh.prototype.getIndices = function () {
  18127. return null;
  18128. };
  18129. /**
  18130. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18131. * Returned type : float array or Float32Array
  18132. */
  18133. AbstractMesh.prototype.getVerticesData = function (kind) {
  18134. return null;
  18135. };
  18136. /**
  18137. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18138. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18139. * The `data` are either a numeric array either a Float32Array.
  18140. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18141. * 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).
  18142. * Note that a new underlying VertexBuffer object is created each call.
  18143. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18144. *
  18145. * Possible `kind` values :
  18146. * - BABYLON.VertexBuffer.PositionKind
  18147. * - BABYLON.VertexBuffer.UVKind
  18148. * - BABYLON.VertexBuffer.UV2Kind
  18149. * - BABYLON.VertexBuffer.UV3Kind
  18150. * - BABYLON.VertexBuffer.UV4Kind
  18151. * - BABYLON.VertexBuffer.UV5Kind
  18152. * - BABYLON.VertexBuffer.UV6Kind
  18153. * - BABYLON.VertexBuffer.ColorKind
  18154. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18155. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18156. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18157. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18158. *
  18159. * Returns the Mesh.
  18160. */
  18161. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18162. return this;
  18163. };
  18164. /**
  18165. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18166. * If the mesh has no geometry, it is simply returned as it is.
  18167. * The `data` are either a numeric array either a Float32Array.
  18168. * No new underlying VertexBuffer object is created.
  18169. * 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.
  18170. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18171. *
  18172. * Possible `kind` values :
  18173. * - BABYLON.VertexBuffer.PositionKind
  18174. * - BABYLON.VertexBuffer.UVKind
  18175. * - BABYLON.VertexBuffer.UV2Kind
  18176. * - BABYLON.VertexBuffer.UV3Kind
  18177. * - BABYLON.VertexBuffer.UV4Kind
  18178. * - BABYLON.VertexBuffer.UV5Kind
  18179. * - BABYLON.VertexBuffer.UV6Kind
  18180. * - BABYLON.VertexBuffer.ColorKind
  18181. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18182. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18183. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18184. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18185. *
  18186. * Returns the Mesh.
  18187. */
  18188. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18189. return this;
  18190. };
  18191. /**
  18192. * Sets the mesh indices.
  18193. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18194. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18195. * This method creates a new index buffer each call.
  18196. * Returns the Mesh.
  18197. */
  18198. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18199. return this;
  18200. };
  18201. /** Returns false by default, used by the class Mesh.
  18202. * Returns a boolean
  18203. */
  18204. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18205. return false;
  18206. };
  18207. /**
  18208. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18209. * Returns a BoundingInfo
  18210. */
  18211. AbstractMesh.prototype.getBoundingInfo = function () {
  18212. if (this._masterMesh) {
  18213. return this._masterMesh.getBoundingInfo();
  18214. }
  18215. if (!this._boundingInfo) {
  18216. // this._boundingInfo is being created here
  18217. this._updateBoundingInfo();
  18218. }
  18219. // cannot be null.
  18220. return this._boundingInfo;
  18221. };
  18222. /**
  18223. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18224. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18225. */
  18226. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18227. if (includeDescendants === void 0) { includeDescendants = true; }
  18228. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18229. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18230. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18231. if (maxDimension === 0) {
  18232. return this;
  18233. }
  18234. var scale = 1 / maxDimension;
  18235. this.scaling.scaleInPlace(scale);
  18236. return this;
  18237. };
  18238. /**
  18239. * Sets a mesh new object BoundingInfo.
  18240. * Returns the AbstractMesh.
  18241. */
  18242. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18243. this._boundingInfo = boundingInfo;
  18244. return this;
  18245. };
  18246. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18247. get: function () {
  18248. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18249. },
  18250. enumerable: true,
  18251. configurable: true
  18252. });
  18253. AbstractMesh.prototype._preActivate = function () {
  18254. };
  18255. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18256. };
  18257. AbstractMesh.prototype._activate = function (renderId) {
  18258. this._renderId = renderId;
  18259. };
  18260. /**
  18261. * Returns the latest update of the World matrix
  18262. * Returns a Matrix.
  18263. */
  18264. AbstractMesh.prototype.getWorldMatrix = function () {
  18265. if (this._masterMesh) {
  18266. return this._masterMesh.getWorldMatrix();
  18267. }
  18268. return _super.prototype.getWorldMatrix.call(this);
  18269. };
  18270. /**
  18271. * Returns the latest update of the World matrix determinant.
  18272. */
  18273. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18274. if (this._masterMesh) {
  18275. return this._masterMesh._getWorldMatrixDeterminant();
  18276. }
  18277. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18278. };
  18279. // ================================== Point of View Movement =================================
  18280. /**
  18281. * Perform relative position change from the point of view of behind the front of the mesh.
  18282. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18283. * Supports definition of mesh facing forward or backward.
  18284. * @param {number} amountRight
  18285. * @param {number} amountUp
  18286. * @param {number} amountForward
  18287. *
  18288. * Returns the AbstractMesh.
  18289. */
  18290. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18291. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18292. return this;
  18293. };
  18294. /**
  18295. * Calculate relative position change from the point of view of behind the front of the mesh.
  18296. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18297. * Supports definition of mesh facing forward or backward.
  18298. * @param {number} amountRight
  18299. * @param {number} amountUp
  18300. * @param {number} amountForward
  18301. *
  18302. * Returns a new Vector3.
  18303. */
  18304. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18305. var rotMatrix = new BABYLON.Matrix();
  18306. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18307. rotQuaternion.toRotationMatrix(rotMatrix);
  18308. var translationDelta = BABYLON.Vector3.Zero();
  18309. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18310. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18311. return translationDelta;
  18312. };
  18313. // ================================== Point of View Rotation =================================
  18314. /**
  18315. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18316. * Supports definition of mesh facing forward or backward.
  18317. * @param {number} flipBack
  18318. * @param {number} twirlClockwise
  18319. * @param {number} tiltRight
  18320. *
  18321. * Returns the AbstractMesh.
  18322. */
  18323. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18324. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18325. return this;
  18326. };
  18327. /**
  18328. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18329. * Supports definition of mesh facing forward or backward.
  18330. * @param {number} flipBack
  18331. * @param {number} twirlClockwise
  18332. * @param {number} tiltRight
  18333. *
  18334. * Returns a new Vector3.
  18335. */
  18336. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18337. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18338. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18339. };
  18340. /**
  18341. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18342. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18343. */
  18344. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18345. if (includeDescendants === void 0) { includeDescendants = true; }
  18346. this.computeWorldMatrix(true);
  18347. var min;
  18348. var max;
  18349. var boundingInfo = this.getBoundingInfo();
  18350. if (!this.subMeshes) {
  18351. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18352. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18353. }
  18354. else {
  18355. min = boundingInfo.boundingBox.minimumWorld;
  18356. max = boundingInfo.boundingBox.maximumWorld;
  18357. }
  18358. if (includeDescendants) {
  18359. var descendants = this.getDescendants(false);
  18360. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18361. var descendant = descendants_1[_i];
  18362. var childMesh = descendant;
  18363. childMesh.computeWorldMatrix(true);
  18364. //make sure we have the needed params to get mix and max
  18365. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18366. continue;
  18367. }
  18368. var childBoundingInfo = childMesh.getBoundingInfo();
  18369. var boundingBox = childBoundingInfo.boundingBox;
  18370. var minBox = boundingBox.minimumWorld;
  18371. var maxBox = boundingBox.maximumWorld;
  18372. BABYLON.Tools.CheckExtends(minBox, min, max);
  18373. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18374. }
  18375. }
  18376. return {
  18377. min: min,
  18378. max: max
  18379. };
  18380. };
  18381. /**
  18382. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18383. * Returns the AbstractMesh.
  18384. */
  18385. AbstractMesh.prototype._updateBoundingInfo = function () {
  18386. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18387. this._boundingInfo.update(this.worldMatrixFromCache);
  18388. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18389. return this;
  18390. };
  18391. /**
  18392. * Update a mesh's children BoundingInfo objects only.
  18393. * Returns the AbstractMesh.
  18394. */
  18395. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18396. if (!this.subMeshes) {
  18397. return this;
  18398. }
  18399. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18400. var subMesh = this.subMeshes[subIndex];
  18401. if (!subMesh.IsGlobal) {
  18402. subMesh.updateBoundingInfo(matrix);
  18403. }
  18404. }
  18405. return this;
  18406. };
  18407. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18408. // Bounding info
  18409. this._updateBoundingInfo();
  18410. };
  18411. /**
  18412. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18413. * A mesh is in the frustum if its bounding box intersects the frustum.
  18414. * Boolean returned.
  18415. */
  18416. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18417. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18418. };
  18419. /**
  18420. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18421. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18422. * Boolean returned.
  18423. */
  18424. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18425. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18426. ;
  18427. };
  18428. /**
  18429. * True if the mesh intersects another mesh or a SolidParticle object.
  18430. * 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)
  18431. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18432. * Returns a boolean.
  18433. */
  18434. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18435. if (precise === void 0) { precise = false; }
  18436. if (!this._boundingInfo || !mesh._boundingInfo) {
  18437. return false;
  18438. }
  18439. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18440. return true;
  18441. }
  18442. if (includeDescendants) {
  18443. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18444. var child = _a[_i];
  18445. if (child.intersectsMesh(mesh, precise, true)) {
  18446. return true;
  18447. }
  18448. }
  18449. }
  18450. return false;
  18451. };
  18452. /**
  18453. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18454. * Returns a boolean.
  18455. */
  18456. AbstractMesh.prototype.intersectsPoint = function (point) {
  18457. if (!this._boundingInfo) {
  18458. return false;
  18459. }
  18460. return this._boundingInfo.intersectsPoint(point);
  18461. };
  18462. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18463. return this.physicsImpostor;
  18464. };
  18465. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18466. if (camera === void 0) { camera = null; }
  18467. if (!camera) {
  18468. camera = this.getScene().activeCamera;
  18469. }
  18470. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18471. };
  18472. /**
  18473. * Returns the distance from the mesh to the active camera.
  18474. * Returns a float.
  18475. */
  18476. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18477. if (camera === void 0) { camera = null; }
  18478. if (!camera) {
  18479. camera = this.getScene().activeCamera;
  18480. }
  18481. return this.absolutePosition.subtract(camera.position).length();
  18482. };
  18483. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18484. if (!this.physicsImpostor) {
  18485. return this;
  18486. }
  18487. this.physicsImpostor.applyImpulse(force, contactPoint);
  18488. return this;
  18489. };
  18490. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18491. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18492. return this;
  18493. }
  18494. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18495. mainPivot: pivot1,
  18496. connectedPivot: pivot2,
  18497. nativeParams: options
  18498. });
  18499. return this;
  18500. };
  18501. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18502. // Collisions
  18503. /**
  18504. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18505. * Default `false`.
  18506. */
  18507. get: function () {
  18508. return this._checkCollisions;
  18509. },
  18510. set: function (collisionEnabled) {
  18511. this._checkCollisions = collisionEnabled;
  18512. if (this.getScene().workerCollisions) {
  18513. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18514. }
  18515. },
  18516. enumerable: true,
  18517. configurable: true
  18518. });
  18519. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18520. /**
  18521. * Gets Collider object used to compute collisions (not physics)
  18522. */
  18523. get: function () {
  18524. return this._collider;
  18525. },
  18526. enumerable: true,
  18527. configurable: true
  18528. });
  18529. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18530. var globalPosition = this.getAbsolutePosition();
  18531. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18532. if (!this._collider) {
  18533. this._collider = new BABYLON.Collider();
  18534. }
  18535. this._collider._radius = this.ellipsoid;
  18536. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18537. return this;
  18538. };
  18539. // Submeshes octree
  18540. /**
  18541. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18542. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18543. * Returns an Octree of submeshes.
  18544. */
  18545. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18546. if (maxCapacity === void 0) { maxCapacity = 64; }
  18547. if (maxDepth === void 0) { maxDepth = 2; }
  18548. if (!this._submeshesOctree) {
  18549. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18550. }
  18551. this.computeWorldMatrix(true);
  18552. var boundingInfo = this.getBoundingInfo();
  18553. // Update octree
  18554. var bbox = boundingInfo.boundingBox;
  18555. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18556. return this._submeshesOctree;
  18557. };
  18558. // Collisions
  18559. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18560. this._generatePointsArray();
  18561. if (!this._positions) {
  18562. return this;
  18563. }
  18564. // Transformation
  18565. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18566. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18567. subMesh._lastColliderWorldVertices = [];
  18568. subMesh._trianglePlanes = [];
  18569. var start = subMesh.verticesStart;
  18570. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18571. for (var i = start; i < end; i++) {
  18572. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18573. }
  18574. }
  18575. // Collide
  18576. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18577. if (collider.collisionFound) {
  18578. collider.collidedMesh = this;
  18579. }
  18580. return this;
  18581. };
  18582. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18583. var subMeshes;
  18584. var len;
  18585. // Octrees
  18586. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18587. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18588. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18589. len = intersections.length;
  18590. subMeshes = intersections.data;
  18591. }
  18592. else {
  18593. subMeshes = this.subMeshes;
  18594. len = subMeshes.length;
  18595. }
  18596. for (var index = 0; index < len; index++) {
  18597. var subMesh = subMeshes[index];
  18598. // Bounding test
  18599. if (len > 1 && !subMesh._checkCollision(collider))
  18600. continue;
  18601. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18602. }
  18603. return this;
  18604. };
  18605. AbstractMesh.prototype._checkCollision = function (collider) {
  18606. // Bounding box test
  18607. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18608. return this;
  18609. // Transformation matrix
  18610. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18611. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18612. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18613. return this;
  18614. };
  18615. // Picking
  18616. AbstractMesh.prototype._generatePointsArray = function () {
  18617. return false;
  18618. };
  18619. /**
  18620. * Checks if the passed Ray intersects with the mesh.
  18621. * Returns an object PickingInfo.
  18622. */
  18623. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18624. var pickingInfo = new BABYLON.PickingInfo();
  18625. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18626. return pickingInfo;
  18627. }
  18628. if (!this._generatePointsArray()) {
  18629. return pickingInfo;
  18630. }
  18631. var intersectInfo = null;
  18632. // Octrees
  18633. var subMeshes;
  18634. var len;
  18635. if (this._submeshesOctree && this.useOctreeForPicking) {
  18636. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18637. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18638. len = intersections.length;
  18639. subMeshes = intersections.data;
  18640. }
  18641. else {
  18642. subMeshes = this.subMeshes;
  18643. len = subMeshes.length;
  18644. }
  18645. for (var index = 0; index < len; index++) {
  18646. var subMesh = subMeshes[index];
  18647. // Bounding test
  18648. if (len > 1 && !subMesh.canIntersects(ray))
  18649. continue;
  18650. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18651. if (currentIntersectInfo) {
  18652. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18653. intersectInfo = currentIntersectInfo;
  18654. intersectInfo.subMeshId = index;
  18655. if (fastCheck) {
  18656. break;
  18657. }
  18658. }
  18659. }
  18660. }
  18661. if (intersectInfo) {
  18662. // Get picked point
  18663. var world = this.getWorldMatrix();
  18664. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18665. var direction = ray.direction.clone();
  18666. direction = direction.scale(intersectInfo.distance);
  18667. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18668. var pickedPoint = worldOrigin.add(worldDirection);
  18669. // Return result
  18670. pickingInfo.hit = true;
  18671. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18672. pickingInfo.pickedPoint = pickedPoint;
  18673. pickingInfo.pickedMesh = this;
  18674. pickingInfo.bu = intersectInfo.bu || 0;
  18675. pickingInfo.bv = intersectInfo.bv || 0;
  18676. pickingInfo.faceId = intersectInfo.faceId;
  18677. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18678. return pickingInfo;
  18679. }
  18680. return pickingInfo;
  18681. };
  18682. /**
  18683. * Clones the mesh, used by the class Mesh.
  18684. * Just returns `null` for an AbstractMesh.
  18685. */
  18686. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18687. return null;
  18688. };
  18689. /**
  18690. * Disposes all the mesh submeshes.
  18691. * Returns the AbstractMesh.
  18692. */
  18693. AbstractMesh.prototype.releaseSubMeshes = function () {
  18694. if (this.subMeshes) {
  18695. while (this.subMeshes.length) {
  18696. this.subMeshes[0].dispose();
  18697. }
  18698. }
  18699. else {
  18700. this.subMeshes = new Array();
  18701. }
  18702. return this;
  18703. };
  18704. /**
  18705. * Releases resources associated with this abstract mesh.
  18706. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18707. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18708. */
  18709. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18710. var _this = this;
  18711. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18712. var index;
  18713. // Smart Array Retainers.
  18714. this.getScene().freeActiveMeshes();
  18715. this.getScene().freeRenderingGroups();
  18716. // Action manager
  18717. if (this.actionManager !== undefined && this.actionManager !== null) {
  18718. this.actionManager.dispose();
  18719. this.actionManager = null;
  18720. }
  18721. // Skeleton
  18722. this._skeleton = null;
  18723. // Physics
  18724. if (this.physicsImpostor) {
  18725. this.physicsImpostor.dispose();
  18726. }
  18727. // Intersections in progress
  18728. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18729. var other = this._intersectionsInProgress[index];
  18730. var pos = other._intersectionsInProgress.indexOf(this);
  18731. other._intersectionsInProgress.splice(pos, 1);
  18732. }
  18733. this._intersectionsInProgress = [];
  18734. // Lights
  18735. var lights = this.getScene().lights;
  18736. lights.forEach(function (light) {
  18737. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18738. if (meshIndex !== -1) {
  18739. light.includedOnlyMeshes.splice(meshIndex, 1);
  18740. }
  18741. meshIndex = light.excludedMeshes.indexOf(_this);
  18742. if (meshIndex !== -1) {
  18743. light.excludedMeshes.splice(meshIndex, 1);
  18744. }
  18745. // Shadow generators
  18746. var generator = light.getShadowGenerator();
  18747. if (generator) {
  18748. var shadowMap = generator.getShadowMap();
  18749. if (shadowMap && shadowMap.renderList) {
  18750. meshIndex = shadowMap.renderList.indexOf(_this);
  18751. if (meshIndex !== -1) {
  18752. shadowMap.renderList.splice(meshIndex, 1);
  18753. }
  18754. }
  18755. }
  18756. });
  18757. // Edges
  18758. if (this._edgesRenderer) {
  18759. this._edgesRenderer.dispose();
  18760. this._edgesRenderer = null;
  18761. }
  18762. // SubMeshes
  18763. if (this.getClassName() !== "InstancedMesh") {
  18764. this.releaseSubMeshes();
  18765. }
  18766. // Octree
  18767. var sceneOctree = this.getScene().selectionOctree;
  18768. if (sceneOctree !== undefined && sceneOctree !== null) {
  18769. var index = sceneOctree.dynamicContent.indexOf(this);
  18770. if (index !== -1) {
  18771. sceneOctree.dynamicContent.splice(index, 1);
  18772. }
  18773. }
  18774. // Query
  18775. var engine = this.getScene().getEngine();
  18776. if (this._occlusionQuery) {
  18777. this._isOcclusionQueryInProgress = false;
  18778. engine.deleteQuery(this._occlusionQuery);
  18779. this._occlusionQuery = null;
  18780. }
  18781. // Engine
  18782. engine.wipeCaches();
  18783. // Remove from scene
  18784. this.getScene().removeMesh(this);
  18785. if (disposeMaterialAndTextures) {
  18786. if (this.material) {
  18787. this.material.dispose(false, true);
  18788. }
  18789. }
  18790. if (!doNotRecurse) {
  18791. // Particles
  18792. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18793. if (this.getScene().particleSystems[index].emitter === this) {
  18794. this.getScene().particleSystems[index].dispose();
  18795. index--;
  18796. }
  18797. }
  18798. }
  18799. // facet data
  18800. if (this._facetDataEnabled) {
  18801. this.disableFacetData();
  18802. }
  18803. this.onAfterWorldMatrixUpdateObservable.clear();
  18804. this.onCollideObservable.clear();
  18805. this.onCollisionPositionChangeObservable.clear();
  18806. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18807. };
  18808. /**
  18809. * Adds the passed mesh as a child to the current mesh.
  18810. * Returns the AbstractMesh.
  18811. */
  18812. AbstractMesh.prototype.addChild = function (mesh) {
  18813. mesh.setParent(this);
  18814. return this;
  18815. };
  18816. /**
  18817. * Removes the passed mesh from the current mesh children list.
  18818. * Returns the AbstractMesh.
  18819. */
  18820. AbstractMesh.prototype.removeChild = function (mesh) {
  18821. mesh.setParent(null);
  18822. return this;
  18823. };
  18824. // Facet data
  18825. /**
  18826. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18827. * Returns the AbstractMesh.
  18828. */
  18829. AbstractMesh.prototype._initFacetData = function () {
  18830. if (!this._facetNormals) {
  18831. this._facetNormals = new Array();
  18832. }
  18833. if (!this._facetPositions) {
  18834. this._facetPositions = new Array();
  18835. }
  18836. if (!this._facetPartitioning) {
  18837. this._facetPartitioning = new Array();
  18838. }
  18839. this._facetNb = (this.getIndices().length / 3) | 0;
  18840. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18841. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18842. for (var f = 0; f < this._facetNb; f++) {
  18843. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18844. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18845. }
  18846. this._facetDataEnabled = true;
  18847. return this;
  18848. };
  18849. /**
  18850. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18851. * This method can be called within the render loop.
  18852. * 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.
  18853. * Returns the AbstractMesh.
  18854. */
  18855. AbstractMesh.prototype.updateFacetData = function () {
  18856. if (!this._facetDataEnabled) {
  18857. this._initFacetData();
  18858. }
  18859. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18860. var indices = this.getIndices();
  18861. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18862. var bInfo = this.getBoundingInfo();
  18863. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18864. // init arrays, matrix and sort function on first call
  18865. this._facetDepthSortEnabled = true;
  18866. if (indices instanceof Uint16Array) {
  18867. this._depthSortedIndices = new Uint16Array(indices);
  18868. }
  18869. else if (indices instanceof Uint32Array) {
  18870. this._depthSortedIndices = new Uint32Array(indices);
  18871. }
  18872. else {
  18873. var needs32bits = false;
  18874. for (var i = 0; i < indices.length; i++) {
  18875. if (indices[i] > 65535) {
  18876. needs32bits = true;
  18877. break;
  18878. }
  18879. }
  18880. if (needs32bits) {
  18881. this._depthSortedIndices = new Uint32Array(indices);
  18882. }
  18883. else {
  18884. this._depthSortedIndices = new Uint16Array(indices);
  18885. }
  18886. }
  18887. this._facetDepthSortFunction = function (f1, f2) {
  18888. return (f2.sqDistance - f1.sqDistance);
  18889. };
  18890. if (!this._facetDepthSortFrom) {
  18891. var camera = this.getScene().activeCamera;
  18892. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18893. }
  18894. this._depthSortedFacets = [];
  18895. for (var f = 0; f < this._facetNb; f++) {
  18896. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18897. this._depthSortedFacets.push(depthSortedFacet);
  18898. }
  18899. this._invertedMatrix = BABYLON.Matrix.Identity();
  18900. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18901. }
  18902. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18903. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18904. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18905. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18906. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18907. this._subDiv.max = this._partitioningSubdivisions;
  18908. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18909. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18910. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18911. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18912. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18913. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18914. // set the parameters for ComputeNormals()
  18915. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18916. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18917. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18918. this._facetParameters.bInfo = bInfo;
  18919. this._facetParameters.bbSize = this._bbSize;
  18920. this._facetParameters.subDiv = this._subDiv;
  18921. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18922. this._facetParameters.depthSort = this._facetDepthSort;
  18923. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18924. this.computeWorldMatrix(true);
  18925. this._worldMatrix.invertToRef(this._invertedMatrix);
  18926. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18927. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18928. }
  18929. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18930. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18931. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18932. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18933. var l = (this._depthSortedIndices.length / 3) | 0;
  18934. for (var f = 0; f < l; f++) {
  18935. var sind = this._depthSortedFacets[f].ind;
  18936. this._depthSortedIndices[f * 3] = indices[sind];
  18937. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18938. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18939. }
  18940. this.updateIndices(this._depthSortedIndices);
  18941. }
  18942. return this;
  18943. };
  18944. /**
  18945. * Returns the facetLocalNormals array.
  18946. * The normals are expressed in the mesh local space.
  18947. */
  18948. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18949. if (!this._facetNormals) {
  18950. this.updateFacetData();
  18951. }
  18952. return this._facetNormals;
  18953. };
  18954. /**
  18955. * Returns the facetLocalPositions array.
  18956. * The facet positions are expressed in the mesh local space.
  18957. */
  18958. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18959. if (!this._facetPositions) {
  18960. this.updateFacetData();
  18961. }
  18962. return this._facetPositions;
  18963. };
  18964. /**
  18965. * Returns the facetLocalPartioning array.
  18966. */
  18967. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18968. if (!this._facetPartitioning) {
  18969. this.updateFacetData();
  18970. }
  18971. return this._facetPartitioning;
  18972. };
  18973. /**
  18974. * Returns the i-th facet position in the world system.
  18975. * This method allocates a new Vector3 per call.
  18976. */
  18977. AbstractMesh.prototype.getFacetPosition = function (i) {
  18978. var pos = BABYLON.Vector3.Zero();
  18979. this.getFacetPositionToRef(i, pos);
  18980. return pos;
  18981. };
  18982. /**
  18983. * Sets the reference Vector3 with the i-th facet position in the world system.
  18984. * Returns the AbstractMesh.
  18985. */
  18986. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18987. var localPos = (this.getFacetLocalPositions())[i];
  18988. var world = this.getWorldMatrix();
  18989. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18990. return this;
  18991. };
  18992. /**
  18993. * Returns the i-th facet normal in the world system.
  18994. * This method allocates a new Vector3 per call.
  18995. */
  18996. AbstractMesh.prototype.getFacetNormal = function (i) {
  18997. var norm = BABYLON.Vector3.Zero();
  18998. this.getFacetNormalToRef(i, norm);
  18999. return norm;
  19000. };
  19001. /**
  19002. * Sets the reference Vector3 with the i-th facet normal in the world system.
  19003. * Returns the AbstractMesh.
  19004. */
  19005. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  19006. var localNorm = (this.getFacetLocalNormals())[i];
  19007. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  19008. return this;
  19009. };
  19010. /**
  19011. * 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).
  19012. */
  19013. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  19014. var bInfo = this.getBoundingInfo();
  19015. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  19016. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  19017. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  19018. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  19019. return null;
  19020. }
  19021. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  19022. };
  19023. /**
  19024. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  19025. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  19026. * 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.
  19027. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19028. * 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.
  19029. */
  19030. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  19031. if (checkFace === void 0) { checkFace = false; }
  19032. if (facing === void 0) { facing = true; }
  19033. var world = this.getWorldMatrix();
  19034. var invMat = BABYLON.Tmp.Matrix[5];
  19035. world.invertToRef(invMat);
  19036. var invVect = BABYLON.Tmp.Vector3[8];
  19037. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19038. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19039. if (projected) {
  19040. // tranform the local computed projected vector to world coordinates
  19041. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19042. }
  19043. return closest;
  19044. };
  19045. /**
  19046. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19047. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19048. * 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.
  19049. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19050. * 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.
  19051. */
  19052. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19053. if (checkFace === void 0) { checkFace = false; }
  19054. if (facing === void 0) { facing = true; }
  19055. var closest = null;
  19056. var tmpx = 0.0;
  19057. var tmpy = 0.0;
  19058. var tmpz = 0.0;
  19059. var d = 0.0; // tmp dot facet normal * facet position
  19060. var t0 = 0.0;
  19061. var projx = 0.0;
  19062. var projy = 0.0;
  19063. var projz = 0.0;
  19064. // Get all the facets in the same partitioning block than (x, y, z)
  19065. var facetPositions = this.getFacetLocalPositions();
  19066. var facetNormals = this.getFacetLocalNormals();
  19067. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19068. if (!facetsInBlock) {
  19069. return null;
  19070. }
  19071. // Get the closest facet to (x, y, z)
  19072. var shortest = Number.MAX_VALUE; // init distance vars
  19073. var tmpDistance = shortest;
  19074. var fib; // current facet in the block
  19075. var norm; // current facet normal
  19076. var p0; // current facet barycenter position
  19077. // loop on all the facets in the current partitioning block
  19078. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19079. fib = facetsInBlock[idx];
  19080. norm = facetNormals[fib];
  19081. p0 = facetPositions[fib];
  19082. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19083. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19084. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19085. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19086. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19087. projx = x + norm.x * t0;
  19088. projy = y + norm.y * t0;
  19089. projz = z + norm.z * t0;
  19090. tmpx = projx - x;
  19091. tmpy = projy - y;
  19092. tmpz = projz - z;
  19093. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19094. if (tmpDistance < shortest) {
  19095. shortest = tmpDistance;
  19096. closest = fib;
  19097. if (projected) {
  19098. projected.x = projx;
  19099. projected.y = projy;
  19100. projected.z = projz;
  19101. }
  19102. }
  19103. }
  19104. }
  19105. return closest;
  19106. };
  19107. /**
  19108. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19109. */
  19110. AbstractMesh.prototype.getFacetDataParameters = function () {
  19111. return this._facetParameters;
  19112. };
  19113. /**
  19114. * Disables the feature FacetData and frees the related memory.
  19115. * Returns the AbstractMesh.
  19116. */
  19117. AbstractMesh.prototype.disableFacetData = function () {
  19118. if (this._facetDataEnabled) {
  19119. this._facetDataEnabled = false;
  19120. this._facetPositions = new Array();
  19121. this._facetNormals = new Array();
  19122. this._facetPartitioning = new Array();
  19123. this._facetParameters = null;
  19124. this._depthSortedIndices = new Uint32Array(0);
  19125. }
  19126. return this;
  19127. };
  19128. /**
  19129. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19130. * Returns the mesh.
  19131. */
  19132. AbstractMesh.prototype.updateIndices = function (indices) {
  19133. return this;
  19134. };
  19135. /**
  19136. * The mesh Geometry. Actually used by the Mesh object.
  19137. * Returns a blank geometry object.
  19138. */
  19139. /**
  19140. * Creates new normals data for the mesh.
  19141. * @param updatable.
  19142. */
  19143. AbstractMesh.prototype.createNormals = function (updatable) {
  19144. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19145. var indices = this.getIndices();
  19146. var normals;
  19147. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19148. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19149. }
  19150. else {
  19151. normals = [];
  19152. }
  19153. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19154. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19155. };
  19156. /**
  19157. * Align the mesh with a normal.
  19158. * Returns the mesh.
  19159. */
  19160. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19161. if (!upDirection) {
  19162. upDirection = BABYLON.Axis.Y;
  19163. }
  19164. var axisX = BABYLON.Tmp.Vector3[0];
  19165. var axisZ = BABYLON.Tmp.Vector3[1];
  19166. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19167. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19168. if (this.rotationQuaternion) {
  19169. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19170. }
  19171. else {
  19172. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19173. }
  19174. return this;
  19175. };
  19176. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19177. var engine = this.getEngine();
  19178. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19179. this._isOccluded = false;
  19180. return;
  19181. }
  19182. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19183. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19184. if (isOcclusionQueryAvailable) {
  19185. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19186. this._isOcclusionQueryInProgress = false;
  19187. this._occlusionInternalRetryCounter = 0;
  19188. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19189. }
  19190. else {
  19191. this._occlusionInternalRetryCounter++;
  19192. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19193. this._isOcclusionQueryInProgress = false;
  19194. this._occlusionInternalRetryCounter = 0;
  19195. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19196. // if strict continue the last state of the object.
  19197. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19198. }
  19199. else {
  19200. return;
  19201. }
  19202. }
  19203. }
  19204. var scene = this.getScene();
  19205. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19206. if (!this._occlusionQuery) {
  19207. this._occlusionQuery = engine.createQuery();
  19208. }
  19209. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19210. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19211. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19212. this._isOcclusionQueryInProgress = true;
  19213. };
  19214. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19215. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19216. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19217. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19218. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19219. return AbstractMesh;
  19220. }(BABYLON.TransformNode));
  19221. BABYLON.AbstractMesh = AbstractMesh;
  19222. })(BABYLON || (BABYLON = {}));
  19223. //# sourceMappingURL=babylon.abstractMesh.js.map
  19224. "use strict";
  19225. var BABYLON;
  19226. (function (BABYLON) {
  19227. /**
  19228. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19229. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19230. * 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.
  19231. */
  19232. var Light = /** @class */ (function (_super) {
  19233. __extends(Light, _super);
  19234. /**
  19235. * Creates a Light object in the scene.
  19236. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19237. * @param name The firendly name of the light
  19238. * @param scene The scene the light belongs too
  19239. */
  19240. function Light(name, scene) {
  19241. var _this = _super.call(this, name, scene) || this;
  19242. /**
  19243. * Diffuse gives the basic color to an object.
  19244. */
  19245. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19246. /**
  19247. * Specular produces a highlight color on an object.
  19248. * Note: This is note affecting PBR materials.
  19249. */
  19250. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19251. /**
  19252. * Strength of the light.
  19253. * Note: By default it is define in the framework own unit.
  19254. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19255. */
  19256. _this.intensity = 1.0;
  19257. /**
  19258. * Defines how far from the source the light is impacting in scene units.
  19259. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19260. */
  19261. _this.range = Number.MAX_VALUE;
  19262. /**
  19263. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19264. * of light.
  19265. */
  19266. _this._photometricScale = 1.0;
  19267. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19268. _this._radius = 0.00001;
  19269. /**
  19270. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19271. * exceeding the number allowed of the materials.
  19272. */
  19273. _this.renderPriority = 0;
  19274. /**
  19275. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19276. * the current shadow generator.
  19277. */
  19278. _this.shadowEnabled = true;
  19279. _this._excludeWithLayerMask = 0;
  19280. _this._includeOnlyWithLayerMask = 0;
  19281. _this._lightmapMode = 0;
  19282. /**
  19283. * @ignore Internal use only.
  19284. */
  19285. _this._excludedMeshesIds = new Array();
  19286. /**
  19287. * @ignore Internal use only.
  19288. */
  19289. _this._includedOnlyMeshesIds = new Array();
  19290. _this.getScene().addLight(_this);
  19291. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19292. _this._buildUniformLayout();
  19293. _this.includedOnlyMeshes = new Array();
  19294. _this.excludedMeshes = new Array();
  19295. _this._resyncMeshes();
  19296. return _this;
  19297. }
  19298. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19299. /**
  19300. * If every light affecting the material is in this lightmapMode,
  19301. * material.lightmapTexture adds or multiplies
  19302. * (depends on material.useLightmapAsShadowmap)
  19303. * after every other light calculations.
  19304. */
  19305. get: function () {
  19306. return Light._LIGHTMAP_DEFAULT;
  19307. },
  19308. enumerable: true,
  19309. configurable: true
  19310. });
  19311. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19312. /**
  19313. * material.lightmapTexture as only diffuse lighting from this light
  19314. * adds only specular lighting from this light
  19315. * adds dynamic shadows
  19316. */
  19317. get: function () {
  19318. return Light._LIGHTMAP_SPECULAR;
  19319. },
  19320. enumerable: true,
  19321. configurable: true
  19322. });
  19323. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19324. /**
  19325. * material.lightmapTexture as only lighting
  19326. * no light calculation from this light
  19327. * only adds dynamic shadows from this light
  19328. */
  19329. get: function () {
  19330. return Light._LIGHTMAP_SHADOWSONLY;
  19331. },
  19332. enumerable: true,
  19333. configurable: true
  19334. });
  19335. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19336. /**
  19337. * Each light type uses the default quantity according to its type:
  19338. * point/spot lights use luminous intensity
  19339. * directional lights use illuminance
  19340. */
  19341. get: function () {
  19342. return Light._INTENSITYMODE_AUTOMATIC;
  19343. },
  19344. enumerable: true,
  19345. configurable: true
  19346. });
  19347. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19348. /**
  19349. * lumen (lm)
  19350. */
  19351. get: function () {
  19352. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19353. },
  19354. enumerable: true,
  19355. configurable: true
  19356. });
  19357. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19358. /**
  19359. * candela (lm/sr)
  19360. */
  19361. get: function () {
  19362. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19363. },
  19364. enumerable: true,
  19365. configurable: true
  19366. });
  19367. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19368. /**
  19369. * lux (lm/m^2)
  19370. */
  19371. get: function () {
  19372. return Light._INTENSITYMODE_ILLUMINANCE;
  19373. },
  19374. enumerable: true,
  19375. configurable: true
  19376. });
  19377. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19378. /**
  19379. * nit (cd/m^2)
  19380. */
  19381. get: function () {
  19382. return Light._INTENSITYMODE_LUMINANCE;
  19383. },
  19384. enumerable: true,
  19385. configurable: true
  19386. });
  19387. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19388. /**
  19389. * Light type const id of the point light.
  19390. */
  19391. get: function () {
  19392. return Light._LIGHTTYPEID_POINTLIGHT;
  19393. },
  19394. enumerable: true,
  19395. configurable: true
  19396. });
  19397. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19398. /**
  19399. * Light type const id of the directional light.
  19400. */
  19401. get: function () {
  19402. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19403. },
  19404. enumerable: true,
  19405. configurable: true
  19406. });
  19407. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19408. /**
  19409. * Light type const id of the spot light.
  19410. */
  19411. get: function () {
  19412. return Light._LIGHTTYPEID_SPOTLIGHT;
  19413. },
  19414. enumerable: true,
  19415. configurable: true
  19416. });
  19417. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19418. /**
  19419. * Light type const id of the hemispheric light.
  19420. */
  19421. get: function () {
  19422. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19423. },
  19424. enumerable: true,
  19425. configurable: true
  19426. });
  19427. Object.defineProperty(Light.prototype, "intensityMode", {
  19428. /**
  19429. * Gets the photometric scale used to interpret the intensity.
  19430. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19431. */
  19432. get: function () {
  19433. return this._intensityMode;
  19434. },
  19435. /**
  19436. * Sets the photometric scale used to interpret the intensity.
  19437. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19438. */
  19439. set: function (value) {
  19440. this._intensityMode = value;
  19441. this._computePhotometricScale();
  19442. },
  19443. enumerable: true,
  19444. configurable: true
  19445. });
  19446. ;
  19447. ;
  19448. Object.defineProperty(Light.prototype, "radius", {
  19449. /**
  19450. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19451. */
  19452. get: function () {
  19453. return this._radius;
  19454. },
  19455. /**
  19456. * sets the light radius used by PBR Materials to simulate soft area lights.
  19457. */
  19458. set: function (value) {
  19459. this._radius = value;
  19460. this._computePhotometricScale();
  19461. },
  19462. enumerable: true,
  19463. configurable: true
  19464. });
  19465. ;
  19466. ;
  19467. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19468. /**
  19469. * Gets the only meshes impacted by this light.
  19470. */
  19471. get: function () {
  19472. return this._includedOnlyMeshes;
  19473. },
  19474. /**
  19475. * Sets the only meshes impacted by this light.
  19476. */
  19477. set: function (value) {
  19478. this._includedOnlyMeshes = value;
  19479. this._hookArrayForIncludedOnly(value);
  19480. },
  19481. enumerable: true,
  19482. configurable: true
  19483. });
  19484. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19485. /**
  19486. * Gets the meshes not impacted by this light.
  19487. */
  19488. get: function () {
  19489. return this._excludedMeshes;
  19490. },
  19491. /**
  19492. * Sets the meshes not impacted by this light.
  19493. */
  19494. set: function (value) {
  19495. this._excludedMeshes = value;
  19496. this._hookArrayForExcluded(value);
  19497. },
  19498. enumerable: true,
  19499. configurable: true
  19500. });
  19501. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19502. /**
  19503. * Gets the layer id use to find what meshes are not impacted by the light.
  19504. * Inactive if 0
  19505. */
  19506. get: function () {
  19507. return this._excludeWithLayerMask;
  19508. },
  19509. /**
  19510. * Sets the layer id use to find what meshes are not impacted by the light.
  19511. * Inactive if 0
  19512. */
  19513. set: function (value) {
  19514. this._excludeWithLayerMask = value;
  19515. this._resyncMeshes();
  19516. },
  19517. enumerable: true,
  19518. configurable: true
  19519. });
  19520. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19521. /**
  19522. * Gets the layer id use to find what meshes are impacted by the light.
  19523. * Inactive if 0
  19524. */
  19525. get: function () {
  19526. return this._includeOnlyWithLayerMask;
  19527. },
  19528. /**
  19529. * Sets the layer id use to find what meshes are impacted by the light.
  19530. * Inactive if 0
  19531. */
  19532. set: function (value) {
  19533. this._includeOnlyWithLayerMask = value;
  19534. this._resyncMeshes();
  19535. },
  19536. enumerable: true,
  19537. configurable: true
  19538. });
  19539. Object.defineProperty(Light.prototype, "lightmapMode", {
  19540. /**
  19541. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19542. */
  19543. get: function () {
  19544. return this._lightmapMode;
  19545. },
  19546. /**
  19547. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19548. */
  19549. set: function (value) {
  19550. if (this._lightmapMode === value) {
  19551. return;
  19552. }
  19553. this._lightmapMode = value;
  19554. this._markMeshesAsLightDirty();
  19555. },
  19556. enumerable: true,
  19557. configurable: true
  19558. });
  19559. /**
  19560. * Returns the string "Light".
  19561. * @returns the class name
  19562. */
  19563. Light.prototype.getClassName = function () {
  19564. return "Light";
  19565. };
  19566. /**
  19567. * Converts the light information to a readable string for debug purpose.
  19568. * @param fullDetails Supports for multiple levels of logging within scene loading
  19569. * @returns the human readable light info
  19570. */
  19571. Light.prototype.toString = function (fullDetails) {
  19572. var ret = "Name: " + this.name;
  19573. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19574. if (this.animations) {
  19575. for (var i = 0; i < this.animations.length; i++) {
  19576. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19577. }
  19578. }
  19579. if (fullDetails) {
  19580. }
  19581. return ret;
  19582. };
  19583. /**
  19584. * Set the enabled state of this node.
  19585. * @param value - the new enabled state
  19586. * @see isEnabled
  19587. */
  19588. Light.prototype.setEnabled = function (value) {
  19589. _super.prototype.setEnabled.call(this, value);
  19590. this._resyncMeshes();
  19591. };
  19592. /**
  19593. * Returns the Light associated shadow generator if any.
  19594. * @return the associated shadow generator.
  19595. */
  19596. Light.prototype.getShadowGenerator = function () {
  19597. return this._shadowGenerator;
  19598. };
  19599. /**
  19600. * Returns a Vector3, the absolute light position in the World.
  19601. * @returns the world space position of the light
  19602. */
  19603. Light.prototype.getAbsolutePosition = function () {
  19604. return BABYLON.Vector3.Zero();
  19605. };
  19606. /**
  19607. * Specifies if the light will affect the passed mesh.
  19608. * @param mesh The mesh to test against the light
  19609. * @return true the mesh is affected otherwise, false.
  19610. */
  19611. Light.prototype.canAffectMesh = function (mesh) {
  19612. if (!mesh) {
  19613. return true;
  19614. }
  19615. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19616. return false;
  19617. }
  19618. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19619. return false;
  19620. }
  19621. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19622. return false;
  19623. }
  19624. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19625. return false;
  19626. }
  19627. return true;
  19628. };
  19629. /**
  19630. * Computes and Returns the light World matrix.
  19631. * @returns the world matrix
  19632. */
  19633. Light.prototype.getWorldMatrix = function () {
  19634. this._currentRenderId = this.getScene().getRenderId();
  19635. var worldMatrix = this._getWorldMatrix();
  19636. if (this.parent && this.parent.getWorldMatrix) {
  19637. if (!this._parentedWorldMatrix) {
  19638. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19639. }
  19640. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19641. this._markSyncedWithParent();
  19642. return this._parentedWorldMatrix;
  19643. }
  19644. return worldMatrix;
  19645. };
  19646. /**
  19647. * Sort function to order lights for rendering.
  19648. * @param a First Light object to compare to second.
  19649. * @param b Second Light object to compare first.
  19650. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19651. */
  19652. Light.CompareLightsPriority = function (a, b) {
  19653. //shadow-casting lights have priority over non-shadow-casting lights
  19654. //the renderPrioirty is a secondary sort criterion
  19655. if (a.shadowEnabled !== b.shadowEnabled) {
  19656. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19657. }
  19658. return b.renderPriority - a.renderPriority;
  19659. };
  19660. /**
  19661. * Releases resources associated with this node.
  19662. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19663. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19664. */
  19665. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19666. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19667. if (this._shadowGenerator) {
  19668. this._shadowGenerator.dispose();
  19669. this._shadowGenerator = null;
  19670. }
  19671. // Animations
  19672. this.getScene().stopAnimation(this);
  19673. // Remove from meshes
  19674. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19675. var mesh = _a[_i];
  19676. mesh._removeLightSource(this);
  19677. }
  19678. this._uniformBuffer.dispose();
  19679. // Remove from scene
  19680. this.getScene().removeLight(this);
  19681. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19682. };
  19683. /**
  19684. * Returns the light type ID (integer).
  19685. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19686. */
  19687. Light.prototype.getTypeID = function () {
  19688. return 0;
  19689. };
  19690. /**
  19691. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19692. * @returns the scaled intensity in intensity mode unit
  19693. */
  19694. Light.prototype.getScaledIntensity = function () {
  19695. return this._photometricScale * this.intensity;
  19696. };
  19697. /**
  19698. * Returns a new Light object, named "name", from the current one.
  19699. * @param name The name of the cloned light
  19700. * @returns the new created light
  19701. */
  19702. Light.prototype.clone = function (name) {
  19703. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19704. if (!constructor) {
  19705. return null;
  19706. }
  19707. return BABYLON.SerializationHelper.Clone(constructor, this);
  19708. };
  19709. /**
  19710. * Serializes the current light into a Serialization object.
  19711. * @returns the serialized object.
  19712. */
  19713. Light.prototype.serialize = function () {
  19714. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19715. // Type
  19716. serializationObject.type = this.getTypeID();
  19717. // Parent
  19718. if (this.parent) {
  19719. serializationObject.parentId = this.parent.id;
  19720. }
  19721. // Inclusion / exclusions
  19722. if (this.excludedMeshes.length > 0) {
  19723. serializationObject.excludedMeshesIds = [];
  19724. this.excludedMeshes.forEach(function (mesh) {
  19725. serializationObject.excludedMeshesIds.push(mesh.id);
  19726. });
  19727. }
  19728. if (this.includedOnlyMeshes.length > 0) {
  19729. serializationObject.includedOnlyMeshesIds = [];
  19730. this.includedOnlyMeshes.forEach(function (mesh) {
  19731. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19732. });
  19733. }
  19734. // Animations
  19735. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19736. serializationObject.ranges = this.serializeAnimationRanges();
  19737. return serializationObject;
  19738. };
  19739. /**
  19740. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19741. * This new light is named "name" and added to the passed scene.
  19742. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19743. * @param name The friendly name of the light
  19744. * @param scene The scene the new light will belong to
  19745. * @returns the constructor function
  19746. */
  19747. Light.GetConstructorFromName = function (type, name, scene) {
  19748. switch (type) {
  19749. case 0:
  19750. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19751. case 1:
  19752. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19753. case 2:
  19754. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19755. case 3:
  19756. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19757. }
  19758. return null;
  19759. };
  19760. /**
  19761. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19762. * @param parsedLight The JSON representation of the light
  19763. * @param scene The scene to create the parsed light in
  19764. * @returns the created light after parsing
  19765. */
  19766. Light.Parse = function (parsedLight, scene) {
  19767. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19768. if (!constructor) {
  19769. return null;
  19770. }
  19771. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19772. // Inclusion / exclusions
  19773. if (parsedLight.excludedMeshesIds) {
  19774. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19775. }
  19776. if (parsedLight.includedOnlyMeshesIds) {
  19777. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19778. }
  19779. // Parent
  19780. if (parsedLight.parentId) {
  19781. light._waitingParentId = parsedLight.parentId;
  19782. }
  19783. // Animations
  19784. if (parsedLight.animations) {
  19785. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19786. var parsedAnimation = parsedLight.animations[animationIndex];
  19787. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19788. }
  19789. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19790. }
  19791. if (parsedLight.autoAnimate) {
  19792. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19793. }
  19794. return light;
  19795. };
  19796. Light.prototype._hookArrayForExcluded = function (array) {
  19797. var _this = this;
  19798. var oldPush = array.push;
  19799. array.push = function () {
  19800. var items = [];
  19801. for (var _i = 0; _i < arguments.length; _i++) {
  19802. items[_i] = arguments[_i];
  19803. }
  19804. var result = oldPush.apply(array, items);
  19805. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19806. var item = items_1[_a];
  19807. item._resyncLighSource(_this);
  19808. }
  19809. return result;
  19810. };
  19811. var oldSplice = array.splice;
  19812. array.splice = function (index, deleteCount) {
  19813. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19814. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19815. var item = deleted_1[_i];
  19816. item._resyncLighSource(_this);
  19817. }
  19818. return deleted;
  19819. };
  19820. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19821. var item = array_1[_i];
  19822. item._resyncLighSource(this);
  19823. }
  19824. };
  19825. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19826. var _this = this;
  19827. var oldPush = array.push;
  19828. array.push = function () {
  19829. var items = [];
  19830. for (var _i = 0; _i < arguments.length; _i++) {
  19831. items[_i] = arguments[_i];
  19832. }
  19833. var result = oldPush.apply(array, items);
  19834. _this._resyncMeshes();
  19835. return result;
  19836. };
  19837. var oldSplice = array.splice;
  19838. array.splice = function (index, deleteCount) {
  19839. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19840. _this._resyncMeshes();
  19841. return deleted;
  19842. };
  19843. this._resyncMeshes();
  19844. };
  19845. Light.prototype._resyncMeshes = function () {
  19846. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19847. var mesh = _a[_i];
  19848. mesh._resyncLighSource(this);
  19849. }
  19850. };
  19851. /**
  19852. * Forces the meshes to update their light related information in their rendering used effects
  19853. * @ignore Internal Use Only
  19854. */
  19855. Light.prototype._markMeshesAsLightDirty = function () {
  19856. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19857. var mesh = _a[_i];
  19858. if (mesh._lightSources.indexOf(this) !== -1) {
  19859. mesh._markSubMeshesAsLightDirty();
  19860. }
  19861. }
  19862. };
  19863. /**
  19864. * Recomputes the cached photometric scale if needed.
  19865. */
  19866. Light.prototype._computePhotometricScale = function () {
  19867. this._photometricScale = this._getPhotometricScale();
  19868. this.getScene().resetCachedMaterial();
  19869. };
  19870. /**
  19871. * Returns the Photometric Scale according to the light type and intensity mode.
  19872. */
  19873. Light.prototype._getPhotometricScale = function () {
  19874. var photometricScale = 0.0;
  19875. var lightTypeID = this.getTypeID();
  19876. //get photometric mode
  19877. var photometricMode = this.intensityMode;
  19878. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19879. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19880. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19881. }
  19882. else {
  19883. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19884. }
  19885. }
  19886. //compute photometric scale
  19887. switch (lightTypeID) {
  19888. case Light.LIGHTTYPEID_POINTLIGHT:
  19889. case Light.LIGHTTYPEID_SPOTLIGHT:
  19890. switch (photometricMode) {
  19891. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19892. photometricScale = 1.0 / (4.0 * Math.PI);
  19893. break;
  19894. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19895. photometricScale = 1.0;
  19896. break;
  19897. case Light.INTENSITYMODE_LUMINANCE:
  19898. photometricScale = this.radius * this.radius;
  19899. break;
  19900. }
  19901. break;
  19902. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19903. switch (photometricMode) {
  19904. case Light.INTENSITYMODE_ILLUMINANCE:
  19905. photometricScale = 1.0;
  19906. break;
  19907. case Light.INTENSITYMODE_LUMINANCE:
  19908. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19909. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19910. var apexAngleRadians = this.radius;
  19911. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19912. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19913. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19914. photometricScale = solidAngle;
  19915. break;
  19916. }
  19917. break;
  19918. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19919. // No fall off in hemisperic light.
  19920. photometricScale = 1.0;
  19921. break;
  19922. }
  19923. return photometricScale;
  19924. };
  19925. /**
  19926. * Reorder the light in the scene according to their defined priority.
  19927. * @ignore Internal Use Only
  19928. */
  19929. Light.prototype._reorderLightsInScene = function () {
  19930. var scene = this.getScene();
  19931. if (this._renderPriority != 0) {
  19932. scene.requireLightSorting = true;
  19933. }
  19934. this.getScene().sortLightsByPriority();
  19935. };
  19936. //lightmapMode Consts
  19937. Light._LIGHTMAP_DEFAULT = 0;
  19938. Light._LIGHTMAP_SPECULAR = 1;
  19939. Light._LIGHTMAP_SHADOWSONLY = 2;
  19940. // Intensity Mode Consts
  19941. Light._INTENSITYMODE_AUTOMATIC = 0;
  19942. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19943. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19944. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19945. Light._INTENSITYMODE_LUMINANCE = 4;
  19946. // Light types ids const.
  19947. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19948. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19949. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19950. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19951. __decorate([
  19952. BABYLON.serializeAsColor3()
  19953. ], Light.prototype, "diffuse", void 0);
  19954. __decorate([
  19955. BABYLON.serializeAsColor3()
  19956. ], Light.prototype, "specular", void 0);
  19957. __decorate([
  19958. BABYLON.serialize()
  19959. ], Light.prototype, "intensity", void 0);
  19960. __decorate([
  19961. BABYLON.serialize()
  19962. ], Light.prototype, "range", void 0);
  19963. __decorate([
  19964. BABYLON.serialize()
  19965. ], Light.prototype, "intensityMode", null);
  19966. __decorate([
  19967. BABYLON.serialize()
  19968. ], Light.prototype, "radius", null);
  19969. __decorate([
  19970. BABYLON.serialize()
  19971. ], Light.prototype, "_renderPriority", void 0);
  19972. __decorate([
  19973. BABYLON.expandToProperty("_reorderLightsInScene")
  19974. ], Light.prototype, "renderPriority", void 0);
  19975. __decorate([
  19976. BABYLON.serialize()
  19977. ], Light.prototype, "shadowEnabled", void 0);
  19978. __decorate([
  19979. BABYLON.serialize("excludeWithLayerMask")
  19980. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19981. __decorate([
  19982. BABYLON.serialize("includeOnlyWithLayerMask")
  19983. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19984. __decorate([
  19985. BABYLON.serialize("lightmapMode")
  19986. ], Light.prototype, "_lightmapMode", void 0);
  19987. return Light;
  19988. }(BABYLON.Node));
  19989. BABYLON.Light = Light;
  19990. })(BABYLON || (BABYLON = {}));
  19991. //# sourceMappingURL=babylon.light.js.map
  19992. "use strict";
  19993. var BABYLON;
  19994. (function (BABYLON) {
  19995. var Camera = /** @class */ (function (_super) {
  19996. __extends(Camera, _super);
  19997. function Camera(name, position, scene) {
  19998. var _this = _super.call(this, name, scene) || this;
  19999. /**
  20000. * The vector the camera should consider as up.
  20001. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  20002. */
  20003. _this.upVector = BABYLON.Vector3.Up();
  20004. _this.orthoLeft = null;
  20005. _this.orthoRight = null;
  20006. _this.orthoBottom = null;
  20007. _this.orthoTop = null;
  20008. /**
  20009. * FOV is set in Radians. (default is 0.8)
  20010. */
  20011. _this.fov = 0.8;
  20012. _this.minZ = 1;
  20013. _this.maxZ = 10000.0;
  20014. _this.inertia = 0.9;
  20015. _this.mode = Camera.PERSPECTIVE_CAMERA;
  20016. _this.isIntermediate = false;
  20017. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  20018. /**
  20019. * Restricts the camera to viewing objects with the same layerMask.
  20020. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  20021. */
  20022. _this.layerMask = 0x0FFFFFFF;
  20023. /**
  20024. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  20025. */
  20026. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  20027. // Camera rig members
  20028. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  20029. _this._rigCameras = new Array();
  20030. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  20031. _this._skipRendering = false;
  20032. _this.customRenderTargets = new Array();
  20033. // Observables
  20034. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  20035. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  20036. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20037. _this.onRestoreStateObservable = new BABYLON.Observable();
  20038. // Cache
  20039. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20040. _this._projectionMatrix = new BABYLON.Matrix();
  20041. _this._doNotComputeProjectionMatrix = false;
  20042. _this._postProcesses = new Array();
  20043. _this._transformMatrix = BABYLON.Matrix.Zero();
  20044. _this._activeMeshes = new BABYLON.SmartArray(256);
  20045. _this._globalPosition = BABYLON.Vector3.Zero();
  20046. _this._refreshFrustumPlanes = true;
  20047. _this.getScene().addCamera(_this);
  20048. if (!_this.getScene().activeCamera) {
  20049. _this.getScene().activeCamera = _this;
  20050. }
  20051. _this.position = position;
  20052. return _this;
  20053. }
  20054. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20055. get: function () {
  20056. return Camera._PERSPECTIVE_CAMERA;
  20057. },
  20058. enumerable: true,
  20059. configurable: true
  20060. });
  20061. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20062. get: function () {
  20063. return Camera._ORTHOGRAPHIC_CAMERA;
  20064. },
  20065. enumerable: true,
  20066. configurable: true
  20067. });
  20068. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20069. /**
  20070. * This is the default FOV mode for perspective cameras.
  20071. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20072. *
  20073. */
  20074. get: function () {
  20075. return Camera._FOVMODE_VERTICAL_FIXED;
  20076. },
  20077. enumerable: true,
  20078. configurable: true
  20079. });
  20080. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20081. /**
  20082. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20083. *
  20084. */
  20085. get: function () {
  20086. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20087. },
  20088. enumerable: true,
  20089. configurable: true
  20090. });
  20091. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20092. get: function () {
  20093. return Camera._RIG_MODE_NONE;
  20094. },
  20095. enumerable: true,
  20096. configurable: true
  20097. });
  20098. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20099. get: function () {
  20100. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20101. },
  20102. enumerable: true,
  20103. configurable: true
  20104. });
  20105. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20106. get: function () {
  20107. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20108. },
  20109. enumerable: true,
  20110. configurable: true
  20111. });
  20112. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20113. get: function () {
  20114. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20115. },
  20116. enumerable: true,
  20117. configurable: true
  20118. });
  20119. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20120. get: function () {
  20121. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20122. },
  20123. enumerable: true,
  20124. configurable: true
  20125. });
  20126. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20127. get: function () {
  20128. return Camera._RIG_MODE_VR;
  20129. },
  20130. enumerable: true,
  20131. configurable: true
  20132. });
  20133. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20134. get: function () {
  20135. return Camera._RIG_MODE_WEBVR;
  20136. },
  20137. enumerable: true,
  20138. configurable: true
  20139. });
  20140. /**
  20141. * Store current camera state (fov, position, etc..)
  20142. */
  20143. Camera.prototype.storeState = function () {
  20144. this._stateStored = true;
  20145. this._storedFov = this.fov;
  20146. return this;
  20147. };
  20148. /**
  20149. * Restores the camera state values if it has been stored. You must call storeState() first
  20150. */
  20151. Camera.prototype._restoreStateValues = function () {
  20152. if (!this._stateStored) {
  20153. return false;
  20154. }
  20155. this.fov = this._storedFov;
  20156. return true;
  20157. };
  20158. /**
  20159. * Restored camera state. You must call storeState() first
  20160. */
  20161. Camera.prototype.restoreState = function () {
  20162. if (this._restoreStateValues()) {
  20163. this.onRestoreStateObservable.notifyObservers(this);
  20164. return true;
  20165. }
  20166. return false;
  20167. };
  20168. Camera.prototype.getClassName = function () {
  20169. return "Camera";
  20170. };
  20171. /**
  20172. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20173. */
  20174. Camera.prototype.toString = function (fullDetails) {
  20175. var ret = "Name: " + this.name;
  20176. ret += ", type: " + this.getClassName();
  20177. if (this.animations) {
  20178. for (var i = 0; i < this.animations.length; i++) {
  20179. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20180. }
  20181. }
  20182. if (fullDetails) {
  20183. }
  20184. return ret;
  20185. };
  20186. Object.defineProperty(Camera.prototype, "globalPosition", {
  20187. get: function () {
  20188. return this._globalPosition;
  20189. },
  20190. enumerable: true,
  20191. configurable: true
  20192. });
  20193. Camera.prototype.getActiveMeshes = function () {
  20194. return this._activeMeshes;
  20195. };
  20196. Camera.prototype.isActiveMesh = function (mesh) {
  20197. return (this._activeMeshes.indexOf(mesh) !== -1);
  20198. };
  20199. /**
  20200. * Is this camera ready to be used/rendered
  20201. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  20202. * @return true if the camera is ready
  20203. */
  20204. Camera.prototype.isReady = function (completeCheck) {
  20205. if (completeCheck === void 0) { completeCheck = false; }
  20206. if (completeCheck) {
  20207. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  20208. var pp = _a[_i];
  20209. if (pp && !pp.isReady()) {
  20210. return false;
  20211. }
  20212. }
  20213. }
  20214. return _super.prototype.isReady.call(this, completeCheck);
  20215. };
  20216. //Cache
  20217. Camera.prototype._initCache = function () {
  20218. _super.prototype._initCache.call(this);
  20219. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20220. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20221. this._cache.mode = undefined;
  20222. this._cache.minZ = undefined;
  20223. this._cache.maxZ = undefined;
  20224. this._cache.fov = undefined;
  20225. this._cache.fovMode = undefined;
  20226. this._cache.aspectRatio = undefined;
  20227. this._cache.orthoLeft = undefined;
  20228. this._cache.orthoRight = undefined;
  20229. this._cache.orthoBottom = undefined;
  20230. this._cache.orthoTop = undefined;
  20231. this._cache.renderWidth = undefined;
  20232. this._cache.renderHeight = undefined;
  20233. };
  20234. Camera.prototype._updateCache = function (ignoreParentClass) {
  20235. if (!ignoreParentClass) {
  20236. _super.prototype._updateCache.call(this);
  20237. }
  20238. this._cache.position.copyFrom(this.position);
  20239. this._cache.upVector.copyFrom(this.upVector);
  20240. };
  20241. // Synchronized
  20242. Camera.prototype._isSynchronized = function () {
  20243. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20244. };
  20245. Camera.prototype._isSynchronizedViewMatrix = function () {
  20246. if (!_super.prototype._isSynchronized.call(this))
  20247. return false;
  20248. return this._cache.position.equals(this.position)
  20249. && this._cache.upVector.equals(this.upVector)
  20250. && this.isSynchronizedWithParent();
  20251. };
  20252. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20253. var check = this._cache.mode === this.mode
  20254. && this._cache.minZ === this.minZ
  20255. && this._cache.maxZ === this.maxZ;
  20256. if (!check) {
  20257. return false;
  20258. }
  20259. var engine = this.getEngine();
  20260. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20261. check = this._cache.fov === this.fov
  20262. && this._cache.fovMode === this.fovMode
  20263. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20264. }
  20265. else {
  20266. check = this._cache.orthoLeft === this.orthoLeft
  20267. && this._cache.orthoRight === this.orthoRight
  20268. && this._cache.orthoBottom === this.orthoBottom
  20269. && this._cache.orthoTop === this.orthoTop
  20270. && this._cache.renderWidth === engine.getRenderWidth()
  20271. && this._cache.renderHeight === engine.getRenderHeight();
  20272. }
  20273. return check;
  20274. };
  20275. // Controls
  20276. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20277. };
  20278. Camera.prototype.detachControl = function (element) {
  20279. };
  20280. Camera.prototype.update = function () {
  20281. this._checkInputs();
  20282. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20283. this._updateRigCameras();
  20284. }
  20285. };
  20286. Camera.prototype._checkInputs = function () {
  20287. this.onAfterCheckInputsObservable.notifyObservers(this);
  20288. };
  20289. Object.defineProperty(Camera.prototype, "rigCameras", {
  20290. get: function () {
  20291. return this._rigCameras;
  20292. },
  20293. enumerable: true,
  20294. configurable: true
  20295. });
  20296. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20297. get: function () {
  20298. return this._rigPostProcess;
  20299. },
  20300. enumerable: true,
  20301. configurable: true
  20302. });
  20303. /**
  20304. * Internal, gets the first post proces.
  20305. * @returns the first post process to be run on this camera.
  20306. */
  20307. Camera.prototype._getFirstPostProcess = function () {
  20308. for (var pp in this._postProcesses) {
  20309. if (this._postProcesses[pp] !== null) {
  20310. return this._postProcesses[pp];
  20311. }
  20312. }
  20313. return null;
  20314. };
  20315. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20316. // invalidate framebuffer
  20317. var firstPostProcess = this._getFirstPostProcess();
  20318. if (firstPostProcess) {
  20319. firstPostProcess.markTextureDirty();
  20320. }
  20321. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20322. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20323. var cam = this._rigCameras[i];
  20324. var rigPostProcess = cam._rigPostProcess;
  20325. // for VR rig, there does not have to be a post process
  20326. if (rigPostProcess) {
  20327. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20328. if (isPass) {
  20329. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20330. cam.isIntermediate = this._postProcesses.length === 0;
  20331. }
  20332. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20333. rigPostProcess.markTextureDirty();
  20334. }
  20335. else {
  20336. cam._postProcesses = this._postProcesses.slice(0);
  20337. }
  20338. }
  20339. };
  20340. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20341. if (insertAt === void 0) { insertAt = null; }
  20342. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20343. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20344. return 0;
  20345. }
  20346. if (insertAt == null || insertAt < 0) {
  20347. this._postProcesses.push(postProcess);
  20348. }
  20349. else if (this._postProcesses[insertAt] === null) {
  20350. this._postProcesses[insertAt] = postProcess;
  20351. }
  20352. else {
  20353. this._postProcesses.splice(insertAt, 0, postProcess);
  20354. }
  20355. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20356. return this._postProcesses.indexOf(postProcess);
  20357. };
  20358. Camera.prototype.detachPostProcess = function (postProcess) {
  20359. var idx = this._postProcesses.indexOf(postProcess);
  20360. if (idx !== -1) {
  20361. this._postProcesses[idx] = null;
  20362. }
  20363. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20364. };
  20365. Camera.prototype.getWorldMatrix = function () {
  20366. if (!this._worldMatrix) {
  20367. this._worldMatrix = BABYLON.Matrix.Identity();
  20368. }
  20369. var viewMatrix = this.getViewMatrix();
  20370. viewMatrix.invertToRef(this._worldMatrix);
  20371. return this._worldMatrix;
  20372. };
  20373. Camera.prototype._getViewMatrix = function () {
  20374. return BABYLON.Matrix.Identity();
  20375. };
  20376. Camera.prototype.getViewMatrix = function (force) {
  20377. if (!force && this._isSynchronizedViewMatrix()) {
  20378. return this._computedViewMatrix;
  20379. }
  20380. this.updateCache();
  20381. this._computedViewMatrix = this._getViewMatrix();
  20382. this._currentRenderId = this.getScene().getRenderId();
  20383. this._refreshFrustumPlanes = true;
  20384. if (!this.parent || !this.parent.getWorldMatrix) {
  20385. this._globalPosition.copyFrom(this.position);
  20386. }
  20387. else {
  20388. if (!this._worldMatrix) {
  20389. this._worldMatrix = BABYLON.Matrix.Identity();
  20390. }
  20391. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20392. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20393. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20394. this._computedViewMatrix.invert();
  20395. this._markSyncedWithParent();
  20396. }
  20397. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20398. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20399. }
  20400. this.onViewMatrixChangedObservable.notifyObservers(this);
  20401. return this._computedViewMatrix;
  20402. };
  20403. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20404. this._doNotComputeProjectionMatrix = true;
  20405. if (projection !== undefined) {
  20406. this._projectionMatrix = projection;
  20407. }
  20408. };
  20409. ;
  20410. Camera.prototype.unfreezeProjectionMatrix = function () {
  20411. this._doNotComputeProjectionMatrix = false;
  20412. };
  20413. ;
  20414. Camera.prototype.getProjectionMatrix = function (force) {
  20415. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20416. return this._projectionMatrix;
  20417. }
  20418. // Cache
  20419. this._cache.mode = this.mode;
  20420. this._cache.minZ = this.minZ;
  20421. this._cache.maxZ = this.maxZ;
  20422. // Matrix
  20423. this._refreshFrustumPlanes = true;
  20424. var engine = this.getEngine();
  20425. var scene = this.getScene();
  20426. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20427. this._cache.fov = this.fov;
  20428. this._cache.fovMode = this.fovMode;
  20429. this._cache.aspectRatio = engine.getAspectRatio(this);
  20430. if (this.minZ <= 0) {
  20431. this.minZ = 0.1;
  20432. }
  20433. if (scene.useRightHandedSystem) {
  20434. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20435. }
  20436. else {
  20437. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20438. }
  20439. }
  20440. else {
  20441. var halfWidth = engine.getRenderWidth() / 2.0;
  20442. var halfHeight = engine.getRenderHeight() / 2.0;
  20443. if (scene.useRightHandedSystem) {
  20444. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20445. }
  20446. else {
  20447. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20448. }
  20449. this._cache.orthoLeft = this.orthoLeft;
  20450. this._cache.orthoRight = this.orthoRight;
  20451. this._cache.orthoBottom = this.orthoBottom;
  20452. this._cache.orthoTop = this.orthoTop;
  20453. this._cache.renderWidth = engine.getRenderWidth();
  20454. this._cache.renderHeight = engine.getRenderHeight();
  20455. }
  20456. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20457. return this._projectionMatrix;
  20458. };
  20459. Camera.prototype.getTranformationMatrix = function () {
  20460. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20461. return this._transformMatrix;
  20462. };
  20463. Camera.prototype.updateFrustumPlanes = function () {
  20464. if (!this._refreshFrustumPlanes) {
  20465. return;
  20466. }
  20467. this.getTranformationMatrix();
  20468. if (!this._frustumPlanes) {
  20469. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20470. }
  20471. else {
  20472. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20473. }
  20474. this._refreshFrustumPlanes = false;
  20475. };
  20476. Camera.prototype.isInFrustum = function (target) {
  20477. this.updateFrustumPlanes();
  20478. return target.isInFrustum(this._frustumPlanes);
  20479. };
  20480. Camera.prototype.isCompletelyInFrustum = function (target) {
  20481. this.updateFrustumPlanes();
  20482. return target.isCompletelyInFrustum(this._frustumPlanes);
  20483. };
  20484. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20485. if (length === void 0) { length = 100; }
  20486. if (!transform) {
  20487. transform = this.getWorldMatrix();
  20488. }
  20489. if (!origin) {
  20490. origin = this.position;
  20491. }
  20492. var forward = new BABYLON.Vector3(0, 0, 1);
  20493. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20494. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20495. return new BABYLON.Ray(origin, direction, length);
  20496. };
  20497. /**
  20498. * Releases resources associated with this node.
  20499. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20500. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20501. */
  20502. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20503. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20504. // Observables
  20505. this.onViewMatrixChangedObservable.clear();
  20506. this.onProjectionMatrixChangedObservable.clear();
  20507. this.onAfterCheckInputsObservable.clear();
  20508. this.onRestoreStateObservable.clear();
  20509. // Inputs
  20510. if (this.inputs) {
  20511. this.inputs.clear();
  20512. }
  20513. // Animations
  20514. this.getScene().stopAnimation(this);
  20515. // Remove from scene
  20516. this.getScene().removeCamera(this);
  20517. while (this._rigCameras.length > 0) {
  20518. var camera = this._rigCameras.pop();
  20519. if (camera) {
  20520. camera.dispose();
  20521. }
  20522. }
  20523. // Postprocesses
  20524. if (this._rigPostProcess) {
  20525. this._rigPostProcess.dispose(this);
  20526. this._rigPostProcess = null;
  20527. this._postProcesses = [];
  20528. }
  20529. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20530. this._rigPostProcess = null;
  20531. this._postProcesses = [];
  20532. }
  20533. else {
  20534. var i = this._postProcesses.length;
  20535. while (--i >= 0) {
  20536. var postProcess = this._postProcesses[i];
  20537. if (postProcess) {
  20538. postProcess.dispose(this);
  20539. }
  20540. }
  20541. }
  20542. // Render targets
  20543. var i = this.customRenderTargets.length;
  20544. while (--i >= 0) {
  20545. this.customRenderTargets[i].dispose();
  20546. }
  20547. this.customRenderTargets = [];
  20548. // Active Meshes
  20549. this._activeMeshes.dispose();
  20550. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20551. };
  20552. Object.defineProperty(Camera.prototype, "leftCamera", {
  20553. // ---- Camera rigs section ----
  20554. get: function () {
  20555. if (this._rigCameras.length < 1) {
  20556. return null;
  20557. }
  20558. return this._rigCameras[0];
  20559. },
  20560. enumerable: true,
  20561. configurable: true
  20562. });
  20563. Object.defineProperty(Camera.prototype, "rightCamera", {
  20564. get: function () {
  20565. if (this._rigCameras.length < 2) {
  20566. return null;
  20567. }
  20568. return this._rigCameras[1];
  20569. },
  20570. enumerable: true,
  20571. configurable: true
  20572. });
  20573. Camera.prototype.getLeftTarget = function () {
  20574. if (this._rigCameras.length < 1) {
  20575. return null;
  20576. }
  20577. return this._rigCameras[0].getTarget();
  20578. };
  20579. Camera.prototype.getRightTarget = function () {
  20580. if (this._rigCameras.length < 2) {
  20581. return null;
  20582. }
  20583. return this._rigCameras[1].getTarget();
  20584. };
  20585. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20586. if (this.cameraRigMode === mode) {
  20587. return;
  20588. }
  20589. while (this._rigCameras.length > 0) {
  20590. var camera = this._rigCameras.pop();
  20591. if (camera) {
  20592. camera.dispose();
  20593. }
  20594. }
  20595. this.cameraRigMode = mode;
  20596. this._cameraRigParams = {};
  20597. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20598. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20599. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20600. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20601. // create the rig cameras, unless none
  20602. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20603. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20604. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20605. if (leftCamera && rightCamera) {
  20606. this._rigCameras.push(leftCamera);
  20607. this._rigCameras.push(rightCamera);
  20608. }
  20609. }
  20610. switch (this.cameraRigMode) {
  20611. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20612. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20613. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20614. break;
  20615. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20616. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20617. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20618. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20619. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20620. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20621. break;
  20622. case Camera.RIG_MODE_VR:
  20623. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20624. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20625. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20626. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20627. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20628. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20629. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20630. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20631. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20632. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20633. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20634. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20635. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20636. if (metrics.compensateDistortion) {
  20637. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20638. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20639. }
  20640. break;
  20641. case Camera.RIG_MODE_WEBVR:
  20642. if (rigParams.vrDisplay) {
  20643. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20644. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20645. //Left eye
  20646. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20647. this._rigCameras[0].setCameraRigParameter("left", true);
  20648. //leaving this for future reference
  20649. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20650. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20651. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20652. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20653. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20654. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20655. this._rigCameras[0].parent = this;
  20656. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20657. //Right eye
  20658. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20659. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20660. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20661. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20662. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20663. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20664. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20665. this._rigCameras[1].parent = this;
  20666. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20667. if (Camera.UseAlternateWebVRRendering) {
  20668. this._rigCameras[1]._skipRendering = true;
  20669. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20670. }
  20671. }
  20672. break;
  20673. }
  20674. this._cascadePostProcessesToRigCams();
  20675. this.update();
  20676. };
  20677. Camera.prototype._getVRProjectionMatrix = function () {
  20678. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20679. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20680. return this._projectionMatrix;
  20681. };
  20682. Camera.prototype._updateCameraRotationMatrix = function () {
  20683. //Here for WebVR
  20684. };
  20685. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20686. //Here for WebVR
  20687. };
  20688. /**
  20689. * This function MUST be overwritten by the different WebVR cameras available.
  20690. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20691. */
  20692. Camera.prototype._getWebVRProjectionMatrix = function () {
  20693. return BABYLON.Matrix.Identity();
  20694. };
  20695. /**
  20696. * This function MUST be overwritten by the different WebVR cameras available.
  20697. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20698. */
  20699. Camera.prototype._getWebVRViewMatrix = function () {
  20700. return BABYLON.Matrix.Identity();
  20701. };
  20702. Camera.prototype.setCameraRigParameter = function (name, value) {
  20703. if (!this._cameraRigParams) {
  20704. this._cameraRigParams = {};
  20705. }
  20706. this._cameraRigParams[name] = value;
  20707. //provisionnally:
  20708. if (name === "interaxialDistance") {
  20709. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20710. }
  20711. };
  20712. /**
  20713. * needs to be overridden by children so sub has required properties to be copied
  20714. */
  20715. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20716. return null;
  20717. };
  20718. /**
  20719. * May need to be overridden by children
  20720. */
  20721. Camera.prototype._updateRigCameras = function () {
  20722. for (var i = 0; i < this._rigCameras.length; i++) {
  20723. this._rigCameras[i].minZ = this.minZ;
  20724. this._rigCameras[i].maxZ = this.maxZ;
  20725. this._rigCameras[i].fov = this.fov;
  20726. }
  20727. // only update viewport when ANAGLYPH
  20728. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20729. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20730. }
  20731. };
  20732. Camera.prototype._setupInputs = function () {
  20733. };
  20734. Camera.prototype.serialize = function () {
  20735. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20736. // Type
  20737. serializationObject.type = this.getClassName();
  20738. // Parent
  20739. if (this.parent) {
  20740. serializationObject.parentId = this.parent.id;
  20741. }
  20742. if (this.inputs) {
  20743. this.inputs.serialize(serializationObject);
  20744. }
  20745. // Animations
  20746. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20747. serializationObject.ranges = this.serializeAnimationRanges();
  20748. return serializationObject;
  20749. };
  20750. Camera.prototype.clone = function (name) {
  20751. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20752. };
  20753. Camera.prototype.getDirection = function (localAxis) {
  20754. var result = BABYLON.Vector3.Zero();
  20755. this.getDirectionToRef(localAxis, result);
  20756. return result;
  20757. };
  20758. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20759. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20760. };
  20761. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20762. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20763. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20764. switch (type) {
  20765. case "ArcRotateCamera":
  20766. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20767. case "DeviceOrientationCamera":
  20768. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20769. case "FollowCamera":
  20770. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20771. case "ArcFollowCamera":
  20772. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20773. case "GamepadCamera":
  20774. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20775. case "TouchCamera":
  20776. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20777. case "VirtualJoysticksCamera":
  20778. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20779. case "WebVRFreeCamera":
  20780. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20781. case "WebVRGamepadCamera":
  20782. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20783. case "VRDeviceOrientationFreeCamera":
  20784. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20785. case "VRDeviceOrientationGamepadCamera":
  20786. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20787. case "AnaglyphArcRotateCamera":
  20788. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20789. case "AnaglyphFreeCamera":
  20790. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20791. case "AnaglyphGamepadCamera":
  20792. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20793. case "AnaglyphUniversalCamera":
  20794. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20795. case "StereoscopicArcRotateCamera":
  20796. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20797. case "StereoscopicFreeCamera":
  20798. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20799. case "StereoscopicGamepadCamera":
  20800. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20801. case "StereoscopicUniversalCamera":
  20802. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20803. case "FreeCamera":// Forcing Universal here
  20804. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20805. default:// Universal Camera is the default value
  20806. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20807. }
  20808. };
  20809. Camera.prototype.computeWorldMatrix = function () {
  20810. return this.getWorldMatrix();
  20811. };
  20812. Camera.Parse = function (parsedCamera, scene) {
  20813. var type = parsedCamera.type;
  20814. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20815. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20816. // Parent
  20817. if (parsedCamera.parentId) {
  20818. camera._waitingParentId = parsedCamera.parentId;
  20819. }
  20820. //If camera has an input manager, let it parse inputs settings
  20821. if (camera.inputs) {
  20822. camera.inputs.parse(parsedCamera);
  20823. camera._setupInputs();
  20824. }
  20825. if (camera.setPosition) {
  20826. camera.position.copyFromFloats(0, 0, 0);
  20827. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20828. }
  20829. // Target
  20830. if (parsedCamera.target) {
  20831. if (camera.setTarget) {
  20832. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20833. }
  20834. }
  20835. // Apply 3d rig, when found
  20836. if (parsedCamera.cameraRigMode) {
  20837. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20838. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20839. }
  20840. // Animations
  20841. if (parsedCamera.animations) {
  20842. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20843. var parsedAnimation = parsedCamera.animations[animationIndex];
  20844. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20845. }
  20846. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20847. }
  20848. if (parsedCamera.autoAnimate) {
  20849. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20850. }
  20851. return camera;
  20852. };
  20853. // Statics
  20854. Camera._PERSPECTIVE_CAMERA = 0;
  20855. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20856. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20857. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20858. Camera._RIG_MODE_NONE = 0;
  20859. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20860. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20861. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20862. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20863. Camera._RIG_MODE_VR = 20;
  20864. Camera._RIG_MODE_WEBVR = 21;
  20865. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20866. Camera.UseAlternateWebVRRendering = false;
  20867. __decorate([
  20868. BABYLON.serializeAsVector3()
  20869. ], Camera.prototype, "position", void 0);
  20870. __decorate([
  20871. BABYLON.serializeAsVector3()
  20872. ], Camera.prototype, "upVector", void 0);
  20873. __decorate([
  20874. BABYLON.serialize()
  20875. ], Camera.prototype, "orthoLeft", void 0);
  20876. __decorate([
  20877. BABYLON.serialize()
  20878. ], Camera.prototype, "orthoRight", void 0);
  20879. __decorate([
  20880. BABYLON.serialize()
  20881. ], Camera.prototype, "orthoBottom", void 0);
  20882. __decorate([
  20883. BABYLON.serialize()
  20884. ], Camera.prototype, "orthoTop", void 0);
  20885. __decorate([
  20886. BABYLON.serialize()
  20887. ], Camera.prototype, "fov", void 0);
  20888. __decorate([
  20889. BABYLON.serialize()
  20890. ], Camera.prototype, "minZ", void 0);
  20891. __decorate([
  20892. BABYLON.serialize()
  20893. ], Camera.prototype, "maxZ", void 0);
  20894. __decorate([
  20895. BABYLON.serialize()
  20896. ], Camera.prototype, "inertia", void 0);
  20897. __decorate([
  20898. BABYLON.serialize()
  20899. ], Camera.prototype, "mode", void 0);
  20900. __decorate([
  20901. BABYLON.serialize()
  20902. ], Camera.prototype, "layerMask", void 0);
  20903. __decorate([
  20904. BABYLON.serialize()
  20905. ], Camera.prototype, "fovMode", void 0);
  20906. __decorate([
  20907. BABYLON.serialize()
  20908. ], Camera.prototype, "cameraRigMode", void 0);
  20909. __decorate([
  20910. BABYLON.serialize()
  20911. ], Camera.prototype, "interaxialDistance", void 0);
  20912. __decorate([
  20913. BABYLON.serialize()
  20914. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20915. return Camera;
  20916. }(BABYLON.Node));
  20917. BABYLON.Camera = Camera;
  20918. })(BABYLON || (BABYLON = {}));
  20919. //# sourceMappingURL=babylon.camera.js.map
  20920. "use strict";
  20921. var BABYLON;
  20922. (function (BABYLON) {
  20923. var RenderingManager = /** @class */ (function () {
  20924. function RenderingManager(scene) {
  20925. this._renderingGroups = new Array();
  20926. this._autoClearDepthStencil = {};
  20927. this._customOpaqueSortCompareFn = {};
  20928. this._customAlphaTestSortCompareFn = {};
  20929. this._customTransparentSortCompareFn = {};
  20930. this._renderinGroupInfo = null;
  20931. this._scene = scene;
  20932. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20933. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20934. }
  20935. }
  20936. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20937. if (depth === void 0) { depth = true; }
  20938. if (stencil === void 0) { stencil = true; }
  20939. if (this._depthStencilBufferAlreadyCleaned) {
  20940. return;
  20941. }
  20942. this._scene.getEngine().clear(null, false, depth, stencil);
  20943. this._depthStencilBufferAlreadyCleaned = true;
  20944. };
  20945. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20946. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20947. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20948. var info = null;
  20949. if (observable) {
  20950. if (!this._renderinGroupInfo) {
  20951. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20952. }
  20953. info = this._renderinGroupInfo;
  20954. info.scene = this._scene;
  20955. info.camera = this._scene.activeCamera;
  20956. }
  20957. // Dispatch sprites
  20958. if (renderSprites) {
  20959. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20960. var manager = this._scene.spriteManagers[index];
  20961. this.dispatchSprites(manager);
  20962. }
  20963. }
  20964. // Render
  20965. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20966. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20967. var renderingGroup = this._renderingGroups[index];
  20968. if (!renderingGroup && !observable)
  20969. continue;
  20970. var renderingGroupMask = 0;
  20971. // Fire PRECLEAR stage
  20972. if (observable && info) {
  20973. renderingGroupMask = Math.pow(2, index);
  20974. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20975. info.renderingGroupId = index;
  20976. observable.notifyObservers(info, renderingGroupMask);
  20977. }
  20978. // Clear depth/stencil if needed
  20979. if (RenderingManager.AUTOCLEAR) {
  20980. var autoClear = this._autoClearDepthStencil[index];
  20981. if (autoClear && autoClear.autoClear) {
  20982. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20983. }
  20984. }
  20985. if (observable && info) {
  20986. // Fire PREOPAQUE stage
  20987. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20988. observable.notifyObservers(info, renderingGroupMask);
  20989. // Fire PRETRANSPARENT stage
  20990. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20991. observable.notifyObservers(info, renderingGroupMask);
  20992. }
  20993. if (renderingGroup)
  20994. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20995. // Fire POSTTRANSPARENT stage
  20996. if (observable && info) {
  20997. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20998. observable.notifyObservers(info, renderingGroupMask);
  20999. }
  21000. }
  21001. };
  21002. RenderingManager.prototype.reset = function () {
  21003. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21004. var renderingGroup = this._renderingGroups[index];
  21005. if (renderingGroup) {
  21006. renderingGroup.prepare();
  21007. }
  21008. }
  21009. };
  21010. RenderingManager.prototype.dispose = function () {
  21011. this.freeRenderingGroups();
  21012. this._renderingGroups.length = 0;
  21013. };
  21014. /**
  21015. * Clear the info related to rendering groups preventing retention points during dispose.
  21016. */
  21017. RenderingManager.prototype.freeRenderingGroups = function () {
  21018. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21019. var renderingGroup = this._renderingGroups[index];
  21020. if (renderingGroup) {
  21021. renderingGroup.dispose();
  21022. }
  21023. }
  21024. };
  21025. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  21026. if (this._renderingGroups[renderingGroupId] === undefined) {
  21027. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  21028. }
  21029. };
  21030. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  21031. var renderingGroupId = spriteManager.renderingGroupId || 0;
  21032. this._prepareRenderingGroup(renderingGroupId);
  21033. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  21034. };
  21035. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  21036. var renderingGroupId = particleSystem.renderingGroupId || 0;
  21037. this._prepareRenderingGroup(renderingGroupId);
  21038. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  21039. };
  21040. /**
  21041. * @param subMesh The submesh to dispatch
  21042. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21043. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21044. */
  21045. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  21046. if (mesh === undefined) {
  21047. mesh = subMesh.getMesh();
  21048. }
  21049. var renderingGroupId = mesh.renderingGroupId || 0;
  21050. this._prepareRenderingGroup(renderingGroupId);
  21051. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  21052. };
  21053. /**
  21054. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21055. * This allowed control for front to back rendering or reversly depending of the special needs.
  21056. *
  21057. * @param renderingGroupId The rendering group id corresponding to its index
  21058. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21059. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21060. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21061. */
  21062. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21063. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21064. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21065. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21066. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21067. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21068. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21069. if (this._renderingGroups[renderingGroupId]) {
  21070. var group = this._renderingGroups[renderingGroupId];
  21071. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21072. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21073. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21074. }
  21075. };
  21076. /**
  21077. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21078. *
  21079. * @param renderingGroupId The rendering group id corresponding to its index
  21080. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21081. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21082. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21083. */
  21084. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21085. if (depth === void 0) { depth = true; }
  21086. if (stencil === void 0) { stencil = true; }
  21087. this._autoClearDepthStencil[renderingGroupId] = {
  21088. autoClear: autoClearDepthStencil,
  21089. depth: depth,
  21090. stencil: stencil
  21091. };
  21092. };
  21093. /**
  21094. * The max id used for rendering groups (not included)
  21095. */
  21096. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21097. /**
  21098. * The min id used for rendering groups (included)
  21099. */
  21100. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21101. /**
  21102. * Used to globally prevent autoclearing scenes.
  21103. */
  21104. RenderingManager.AUTOCLEAR = true;
  21105. return RenderingManager;
  21106. }());
  21107. BABYLON.RenderingManager = RenderingManager;
  21108. })(BABYLON || (BABYLON = {}));
  21109. //# sourceMappingURL=babylon.renderingManager.js.map
  21110. "use strict";
  21111. var BABYLON;
  21112. (function (BABYLON) {
  21113. var RenderingGroup = /** @class */ (function () {
  21114. /**
  21115. * Creates a new rendering group.
  21116. * @param index The rendering group index
  21117. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21118. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21119. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21120. */
  21121. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21122. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21123. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21124. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21125. this.index = index;
  21126. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21127. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21128. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21129. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21130. this._particleSystems = new BABYLON.SmartArray(256);
  21131. this._spriteManagers = new BABYLON.SmartArray(256);
  21132. this._edgesRenderers = new BABYLON.SmartArray(16);
  21133. this._scene = scene;
  21134. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21135. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21136. this.transparentSortCompareFn = transparentSortCompareFn;
  21137. }
  21138. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21139. /**
  21140. * Set the opaque sort comparison function.
  21141. * If null the sub meshes will be render in the order they were created
  21142. */
  21143. set: function (value) {
  21144. this._opaqueSortCompareFn = value;
  21145. if (value) {
  21146. this._renderOpaque = this.renderOpaqueSorted;
  21147. }
  21148. else {
  21149. this._renderOpaque = RenderingGroup.renderUnsorted;
  21150. }
  21151. },
  21152. enumerable: true,
  21153. configurable: true
  21154. });
  21155. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21156. /**
  21157. * Set the alpha test sort comparison function.
  21158. * If null the sub meshes will be render in the order they were created
  21159. */
  21160. set: function (value) {
  21161. this._alphaTestSortCompareFn = value;
  21162. if (value) {
  21163. this._renderAlphaTest = this.renderAlphaTestSorted;
  21164. }
  21165. else {
  21166. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21167. }
  21168. },
  21169. enumerable: true,
  21170. configurable: true
  21171. });
  21172. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21173. /**
  21174. * Set the transparent sort comparison function.
  21175. * If null the sub meshes will be render in the order they were created
  21176. */
  21177. set: function (value) {
  21178. if (value) {
  21179. this._transparentSortCompareFn = value;
  21180. }
  21181. else {
  21182. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21183. }
  21184. this._renderTransparent = this.renderTransparentSorted;
  21185. },
  21186. enumerable: true,
  21187. configurable: true
  21188. });
  21189. /**
  21190. * Render all the sub meshes contained in the group.
  21191. * @param customRenderFunction Used to override the default render behaviour of the group.
  21192. * @returns true if rendered some submeshes.
  21193. */
  21194. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21195. if (customRenderFunction) {
  21196. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21197. return;
  21198. }
  21199. var engine = this._scene.getEngine();
  21200. // Depth only
  21201. if (this._depthOnlySubMeshes.length !== 0) {
  21202. engine.setColorWrite(false);
  21203. this._renderAlphaTest(this._depthOnlySubMeshes);
  21204. engine.setColorWrite(true);
  21205. }
  21206. // Opaque
  21207. if (this._opaqueSubMeshes.length !== 0) {
  21208. this._renderOpaque(this._opaqueSubMeshes);
  21209. }
  21210. // Alpha test
  21211. if (this._alphaTestSubMeshes.length !== 0) {
  21212. this._renderAlphaTest(this._alphaTestSubMeshes);
  21213. }
  21214. var stencilState = engine.getStencilBuffer();
  21215. engine.setStencilBuffer(false);
  21216. // Sprites
  21217. if (renderSprites) {
  21218. this._renderSprites();
  21219. }
  21220. // Particles
  21221. if (renderParticles) {
  21222. this._renderParticles(activeMeshes);
  21223. }
  21224. if (this.onBeforeTransparentRendering) {
  21225. this.onBeforeTransparentRendering();
  21226. }
  21227. // Transparent
  21228. if (this._transparentSubMeshes.length !== 0) {
  21229. this._renderTransparent(this._transparentSubMeshes);
  21230. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21231. }
  21232. // Set back stencil to false in case it changes before the edge renderer.
  21233. engine.setStencilBuffer(false);
  21234. // Edges
  21235. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21236. this._edgesRenderers.data[edgesRendererIndex].render();
  21237. }
  21238. // Restore Stencil state.
  21239. engine.setStencilBuffer(stencilState);
  21240. };
  21241. /**
  21242. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21243. * @param subMeshes The submeshes to render
  21244. */
  21245. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21246. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21247. };
  21248. /**
  21249. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21250. * @param subMeshes The submeshes to render
  21251. */
  21252. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21253. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21254. };
  21255. /**
  21256. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21257. * @param subMeshes The submeshes to render
  21258. */
  21259. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21260. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21261. };
  21262. /**
  21263. * Renders the submeshes in a specified order.
  21264. * @param subMeshes The submeshes to sort before render
  21265. * @param sortCompareFn The comparison function use to sort
  21266. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21267. * @param transparent Specifies to activate blending if true
  21268. */
  21269. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21270. var subIndex = 0;
  21271. var subMesh;
  21272. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21273. for (; subIndex < subMeshes.length; subIndex++) {
  21274. subMesh = subMeshes.data[subIndex];
  21275. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21276. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21277. }
  21278. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21279. if (sortCompareFn) {
  21280. sortedArray.sort(sortCompareFn);
  21281. }
  21282. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21283. subMesh = sortedArray[subIndex];
  21284. if (transparent) {
  21285. var material = subMesh.getMaterial();
  21286. if (material && material.needDepthPrePass) {
  21287. var engine = material.getScene().getEngine();
  21288. engine.setColorWrite(false);
  21289. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21290. subMesh.render(false);
  21291. engine.setColorWrite(true);
  21292. }
  21293. }
  21294. subMesh.render(transparent);
  21295. }
  21296. };
  21297. /**
  21298. * Renders the submeshes in the order they were dispatched (no sort applied).
  21299. * @param subMeshes The submeshes to render
  21300. */
  21301. RenderingGroup.renderUnsorted = function (subMeshes) {
  21302. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21303. var submesh = subMeshes.data[subIndex];
  21304. submesh.render(false);
  21305. }
  21306. };
  21307. /**
  21308. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21309. * are rendered back to front if in the same alpha index.
  21310. *
  21311. * @param a The first submesh
  21312. * @param b The second submesh
  21313. * @returns The result of the comparison
  21314. */
  21315. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21316. // Alpha index first
  21317. if (a._alphaIndex > b._alphaIndex) {
  21318. return 1;
  21319. }
  21320. if (a._alphaIndex < b._alphaIndex) {
  21321. return -1;
  21322. }
  21323. // Then distance to camera
  21324. return RenderingGroup.backToFrontSortCompare(a, b);
  21325. };
  21326. /**
  21327. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21328. * are rendered back to front.
  21329. *
  21330. * @param a The first submesh
  21331. * @param b The second submesh
  21332. * @returns The result of the comparison
  21333. */
  21334. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21335. // Then distance to camera
  21336. if (a._distanceToCamera < b._distanceToCamera) {
  21337. return 1;
  21338. }
  21339. if (a._distanceToCamera > b._distanceToCamera) {
  21340. return -1;
  21341. }
  21342. return 0;
  21343. };
  21344. /**
  21345. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21346. * are rendered front to back (prevent overdraw).
  21347. *
  21348. * @param a The first submesh
  21349. * @param b The second submesh
  21350. * @returns The result of the comparison
  21351. */
  21352. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21353. // Then distance to camera
  21354. if (a._distanceToCamera < b._distanceToCamera) {
  21355. return -1;
  21356. }
  21357. if (a._distanceToCamera > b._distanceToCamera) {
  21358. return 1;
  21359. }
  21360. return 0;
  21361. };
  21362. /**
  21363. * Resets the different lists of submeshes to prepare a new frame.
  21364. */
  21365. RenderingGroup.prototype.prepare = function () {
  21366. this._opaqueSubMeshes.reset();
  21367. this._transparentSubMeshes.reset();
  21368. this._alphaTestSubMeshes.reset();
  21369. this._depthOnlySubMeshes.reset();
  21370. this._particleSystems.reset();
  21371. this._spriteManagers.reset();
  21372. this._edgesRenderers.reset();
  21373. };
  21374. RenderingGroup.prototype.dispose = function () {
  21375. this._opaqueSubMeshes.dispose();
  21376. this._transparentSubMeshes.dispose();
  21377. this._alphaTestSubMeshes.dispose();
  21378. this._depthOnlySubMeshes.dispose();
  21379. this._particleSystems.dispose();
  21380. this._spriteManagers.dispose();
  21381. this._edgesRenderers.dispose();
  21382. };
  21383. /**
  21384. * Inserts the submesh in its correct queue depending on its material.
  21385. * @param subMesh The submesh to dispatch
  21386. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21387. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21388. */
  21389. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21390. // Get mesh and materials if not provided
  21391. if (mesh === undefined) {
  21392. mesh = subMesh.getMesh();
  21393. }
  21394. if (material === undefined) {
  21395. material = subMesh.getMaterial();
  21396. }
  21397. if (material === null || material === undefined) {
  21398. return;
  21399. }
  21400. if (material.needAlphaBlendingForMesh(mesh)) {
  21401. this._transparentSubMeshes.push(subMesh);
  21402. }
  21403. else if (material.needAlphaTesting()) {
  21404. if (material.needDepthPrePass) {
  21405. this._depthOnlySubMeshes.push(subMesh);
  21406. }
  21407. this._alphaTestSubMeshes.push(subMesh);
  21408. }
  21409. else {
  21410. if (material.needDepthPrePass) {
  21411. this._depthOnlySubMeshes.push(subMesh);
  21412. }
  21413. this._opaqueSubMeshes.push(subMesh); // Opaque
  21414. }
  21415. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21416. this._edgesRenderers.push(mesh._edgesRenderer);
  21417. }
  21418. };
  21419. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21420. this._spriteManagers.push(spriteManager);
  21421. };
  21422. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21423. this._particleSystems.push(particleSystem);
  21424. };
  21425. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21426. if (this._particleSystems.length === 0) {
  21427. return;
  21428. }
  21429. // Particles
  21430. var activeCamera = this._scene.activeCamera;
  21431. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21432. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21433. var particleSystem = this._particleSystems.data[particleIndex];
  21434. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21435. continue;
  21436. }
  21437. var emitter = particleSystem.emitter;
  21438. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21439. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21440. }
  21441. }
  21442. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21443. };
  21444. RenderingGroup.prototype._renderSprites = function () {
  21445. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21446. return;
  21447. }
  21448. // Sprites
  21449. var activeCamera = this._scene.activeCamera;
  21450. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21451. for (var id = 0; id < this._spriteManagers.length; id++) {
  21452. var spriteManager = this._spriteManagers.data[id];
  21453. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21454. spriteManager.render();
  21455. }
  21456. }
  21457. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21458. };
  21459. return RenderingGroup;
  21460. }());
  21461. BABYLON.RenderingGroup = RenderingGroup;
  21462. })(BABYLON || (BABYLON = {}));
  21463. //# sourceMappingURL=babylon.renderingGroup.js.map
  21464. "use strict";
  21465. var BABYLON;
  21466. (function (BABYLON) {
  21467. var ClickInfo = /** @class */ (function () {
  21468. function ClickInfo() {
  21469. this._singleClick = false;
  21470. this._doubleClick = false;
  21471. this._hasSwiped = false;
  21472. this._ignore = false;
  21473. }
  21474. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21475. get: function () {
  21476. return this._singleClick;
  21477. },
  21478. set: function (b) {
  21479. this._singleClick = b;
  21480. },
  21481. enumerable: true,
  21482. configurable: true
  21483. });
  21484. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21485. get: function () {
  21486. return this._doubleClick;
  21487. },
  21488. set: function (b) {
  21489. this._doubleClick = b;
  21490. },
  21491. enumerable: true,
  21492. configurable: true
  21493. });
  21494. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21495. get: function () {
  21496. return this._hasSwiped;
  21497. },
  21498. set: function (b) {
  21499. this._hasSwiped = b;
  21500. },
  21501. enumerable: true,
  21502. configurable: true
  21503. });
  21504. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21505. get: function () {
  21506. return this._ignore;
  21507. },
  21508. set: function (b) {
  21509. this._ignore = b;
  21510. },
  21511. enumerable: true,
  21512. configurable: true
  21513. });
  21514. return ClickInfo;
  21515. }());
  21516. /**
  21517. * This class is used by the onRenderingGroupObservable
  21518. */
  21519. var RenderingGroupInfo = /** @class */ (function () {
  21520. function RenderingGroupInfo() {
  21521. }
  21522. /**
  21523. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21524. * This stage will be fired no matter what
  21525. */
  21526. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21527. /**
  21528. * Called before opaque object are rendered.
  21529. * This stage will be fired only if there's 3D Opaque content to render
  21530. */
  21531. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21532. /**
  21533. * Called after the opaque objects are rendered and before the transparent ones
  21534. * This stage will be fired only if there's 3D transparent content to render
  21535. */
  21536. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21537. /**
  21538. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21539. * This stage will be fired no matter what
  21540. */
  21541. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21542. return RenderingGroupInfo;
  21543. }());
  21544. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21545. /**
  21546. * Represents a scene to be rendered by the engine.
  21547. * @see http://doc.babylonjs.com/page.php?p=21911
  21548. */
  21549. var Scene = /** @class */ (function () {
  21550. /**
  21551. * @constructor
  21552. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21553. */
  21554. function Scene(engine) {
  21555. // Members
  21556. this.autoClear = true;
  21557. this.autoClearDepthAndStencil = true;
  21558. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21559. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21560. this._forceWireframe = false;
  21561. this._forcePointsCloud = false;
  21562. this.forceShowBoundingBoxes = false;
  21563. this.animationsEnabled = true;
  21564. this.useConstantAnimationDeltaTime = false;
  21565. this.constantlyUpdateMeshUnderPointer = false;
  21566. this.hoverCursor = "pointer";
  21567. this.defaultCursor = "";
  21568. /**
  21569. * This is used to call preventDefault() on pointer down
  21570. * in order to block unwanted artifacts like system double clicks
  21571. */
  21572. this.preventDefaultOnPointerDown = true;
  21573. // Metadata
  21574. this.metadata = null;
  21575. /**
  21576. * Use this array to add regular expressions used to disable offline support for specific urls
  21577. */
  21578. this.disableOfflineSupportExceptionRules = new Array();
  21579. /**
  21580. * An event triggered when the scene is disposed.
  21581. * @type {BABYLON.Observable}
  21582. */
  21583. this.onDisposeObservable = new BABYLON.Observable();
  21584. this._onDisposeObserver = null;
  21585. /**
  21586. * An event triggered before rendering the scene (right after animations and physics)
  21587. * @type {BABYLON.Observable}
  21588. */
  21589. this.onBeforeRenderObservable = new BABYLON.Observable();
  21590. this._onBeforeRenderObserver = null;
  21591. /**
  21592. * An event triggered after rendering the scene
  21593. * @type {BABYLON.Observable}
  21594. */
  21595. this.onAfterRenderObservable = new BABYLON.Observable();
  21596. this._onAfterRenderObserver = null;
  21597. /**
  21598. * An event triggered before animating the scene
  21599. * @type {BABYLON.Observable}
  21600. */
  21601. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21602. /**
  21603. * An event triggered after animations processing
  21604. * @type {BABYLON.Observable}
  21605. */
  21606. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21607. /**
  21608. * An event triggered before draw calls are ready to be sent
  21609. * @type {BABYLON.Observable}
  21610. */
  21611. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21612. /**
  21613. * An event triggered after draw calls have been sent
  21614. * @type {BABYLON.Observable}
  21615. */
  21616. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21617. /**
  21618. * An event triggered when physic simulation is about to be run
  21619. * @type {BABYLON.Observable}
  21620. */
  21621. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21622. /**
  21623. * An event triggered when physic simulation has been done
  21624. * @type {BABYLON.Observable}
  21625. */
  21626. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21627. /**
  21628. * An event triggered when the scene is ready
  21629. * @type {BABYLON.Observable}
  21630. */
  21631. this.onReadyObservable = new BABYLON.Observable();
  21632. /**
  21633. * An event triggered before rendering a camera
  21634. * @type {BABYLON.Observable}
  21635. */
  21636. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21637. this._onBeforeCameraRenderObserver = null;
  21638. /**
  21639. * An event triggered after rendering a camera
  21640. * @type {BABYLON.Observable}
  21641. */
  21642. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21643. this._onAfterCameraRenderObserver = null;
  21644. /**
  21645. * An event triggered when active meshes evaluation is about to start
  21646. * @type {BABYLON.Observable}
  21647. */
  21648. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21649. /**
  21650. * An event triggered when active meshes evaluation is done
  21651. * @type {BABYLON.Observable}
  21652. */
  21653. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21654. /**
  21655. * An event triggered when particles rendering is about to start
  21656. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21657. * @type {BABYLON.Observable}
  21658. */
  21659. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21660. /**
  21661. * An event triggered when particles rendering is done
  21662. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21663. * @type {BABYLON.Observable}
  21664. */
  21665. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21666. /**
  21667. * An event triggered when sprites rendering is about to start
  21668. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21669. * @type {BABYLON.Observable}
  21670. */
  21671. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21672. /**
  21673. * An event triggered when sprites rendering is done
  21674. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21675. * @type {BABYLON.Observable}
  21676. */
  21677. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21678. /**
  21679. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21680. * @type {BABYLON.Observable}
  21681. */
  21682. this.onDataLoadedObservable = new BABYLON.Observable();
  21683. /**
  21684. * An event triggered when a camera is created
  21685. * @type {BABYLON.Observable}
  21686. */
  21687. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21688. /**
  21689. * An event triggered when a camera is removed
  21690. * @type {BABYLON.Observable}
  21691. */
  21692. this.onCameraRemovedObservable = new BABYLON.Observable();
  21693. /**
  21694. * An event triggered when a light is created
  21695. * @type {BABYLON.Observable}
  21696. */
  21697. this.onNewLightAddedObservable = new BABYLON.Observable();
  21698. /**
  21699. * An event triggered when a light is removed
  21700. * @type {BABYLON.Observable}
  21701. */
  21702. this.onLightRemovedObservable = new BABYLON.Observable();
  21703. /**
  21704. * An event triggered when a geometry is created
  21705. * @type {BABYLON.Observable}
  21706. */
  21707. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21708. /**
  21709. * An event triggered when a geometry is removed
  21710. * @type {BABYLON.Observable}
  21711. */
  21712. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21713. /**
  21714. * An event triggered when a transform node is created
  21715. * @type {BABYLON.Observable}
  21716. */
  21717. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21718. /**
  21719. * An event triggered when a transform node is removed
  21720. * @type {BABYLON.Observable}
  21721. */
  21722. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21723. /**
  21724. * An event triggered when a mesh is created
  21725. * @type {BABYLON.Observable}
  21726. */
  21727. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21728. /**
  21729. * An event triggered when a mesh is removed
  21730. * @type {BABYLON.Observable}
  21731. */
  21732. this.onMeshRemovedObservable = new BABYLON.Observable();
  21733. /**
  21734. * An event triggered when render targets are about to be rendered
  21735. * Can happen multiple times per frame.
  21736. * @type {BABYLON.Observable}
  21737. */
  21738. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21739. /**
  21740. * An event triggered when render targets were rendered.
  21741. * Can happen multiple times per frame.
  21742. * @type {BABYLON.Observable}
  21743. */
  21744. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21745. /**
  21746. * An event triggered before calculating deterministic simulation step
  21747. * @type {BABYLON.Observable}
  21748. */
  21749. this.onBeforeStepObservable = new BABYLON.Observable();
  21750. /**
  21751. * An event triggered after calculating deterministic simulation step
  21752. * @type {BABYLON.Observable}
  21753. */
  21754. this.onAfterStepObservable = new BABYLON.Observable();
  21755. /**
  21756. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21757. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21758. * 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)
  21759. */
  21760. this.onRenderingGroupObservable = new BABYLON.Observable();
  21761. // Animations
  21762. this.animations = [];
  21763. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21764. /**
  21765. * 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).
  21766. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21767. */
  21768. this.onPrePointerObservable = new BABYLON.Observable();
  21769. /**
  21770. * Observable event triggered each time an input event is received from the rendering canvas
  21771. */
  21772. this.onPointerObservable = new BABYLON.Observable();
  21773. this._meshPickProceed = false;
  21774. this._currentPickResult = null;
  21775. this._previousPickResult = null;
  21776. this._totalPointersPressed = 0;
  21777. this._doubleClickOccured = false;
  21778. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21779. this.cameraToUseForPointers = null;
  21780. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21781. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21782. this._startingPointerTime = 0;
  21783. this._previousStartingPointerTime = 0;
  21784. // Deterministic lockstep
  21785. this._timeAccumulator = 0;
  21786. this._currentStepId = 0;
  21787. this._currentInternalStep = 0;
  21788. // Keyboard
  21789. /**
  21790. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21791. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21792. */
  21793. this.onPreKeyboardObservable = new BABYLON.Observable();
  21794. /**
  21795. * Observable event triggered each time an keyboard event is received from the hosting window
  21796. */
  21797. this.onKeyboardObservable = new BABYLON.Observable();
  21798. // Coordinate system
  21799. /**
  21800. * use right-handed coordinate system on this scene.
  21801. * @type {boolean}
  21802. */
  21803. this._useRightHandedSystem = false;
  21804. // Fog
  21805. this._fogEnabled = true;
  21806. this._fogMode = Scene.FOGMODE_NONE;
  21807. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21808. this.fogDensity = 0.1;
  21809. this.fogStart = 0;
  21810. this.fogEnd = 1000.0;
  21811. // Lights
  21812. /**
  21813. * is shadow enabled on this scene.
  21814. * @type {boolean}
  21815. */
  21816. this._shadowsEnabled = true;
  21817. /**
  21818. * is light enabled on this scene.
  21819. * @type {boolean}
  21820. */
  21821. this._lightsEnabled = true;
  21822. /**
  21823. * All of the lights added to this scene.
  21824. * @see BABYLON.Light
  21825. * @type {BABYLON.Light[]}
  21826. */
  21827. this.lights = new Array();
  21828. // Cameras
  21829. /** All of the cameras added to this scene. */
  21830. this.cameras = new Array();
  21831. /** All of the active cameras added to this scene. */
  21832. this.activeCameras = new Array();
  21833. // Meshes
  21834. /**
  21835. * All of the tranform nodes added to this scene.
  21836. * @see BABYLON.TransformNode
  21837. * @type {BABYLON.TransformNode[]}
  21838. */
  21839. this.transformNodes = new Array();
  21840. /**
  21841. * All of the (abstract) meshes added to this scene.
  21842. * @see BABYLON.AbstractMesh
  21843. * @type {BABYLON.AbstractMesh[]}
  21844. */
  21845. this.meshes = new Array();
  21846. /**
  21847. * All of the animation groups added to this scene.
  21848. * @see BABYLON.AnimationGroup
  21849. * @type {BABYLON.AnimationGroup[]}
  21850. */
  21851. this.animationGroups = new Array();
  21852. // Geometries
  21853. this._geometries = new Array();
  21854. this.materials = new Array();
  21855. this.multiMaterials = new Array();
  21856. // Textures
  21857. this._texturesEnabled = true;
  21858. this.textures = new Array();
  21859. // Particles
  21860. this.particlesEnabled = true;
  21861. this.particleSystems = new Array();
  21862. // Sprites
  21863. this.spritesEnabled = true;
  21864. this.spriteManagers = new Array();
  21865. /**
  21866. * The list of layers (background and foreground) of the scene.
  21867. */
  21868. this.layers = new Array();
  21869. /**
  21870. * The list of effect layers (highlights/glow) contained in the scene.
  21871. */
  21872. this.effectLayers = new Array();
  21873. // Skeletons
  21874. this._skeletonsEnabled = true;
  21875. this.skeletons = new Array();
  21876. // Morph targets
  21877. this.morphTargetManagers = new Array();
  21878. // Lens flares
  21879. this.lensFlaresEnabled = true;
  21880. this.lensFlareSystems = new Array();
  21881. // Collisions
  21882. this.collisionsEnabled = true;
  21883. /** Defines the gravity applied to this scene */
  21884. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21885. // Postprocesses
  21886. this.postProcesses = new Array();
  21887. this.postProcessesEnabled = true;
  21888. // Customs render targets
  21889. this.renderTargetsEnabled = true;
  21890. this.dumpNextRenderTargets = false;
  21891. this.customRenderTargets = new Array();
  21892. // Imported meshes
  21893. this.importedMeshesFiles = new Array();
  21894. // Probes
  21895. this.probesEnabled = true;
  21896. this.reflectionProbes = new Array();
  21897. this._actionManagers = new Array();
  21898. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21899. // Procedural textures
  21900. this.proceduralTexturesEnabled = true;
  21901. this._proceduralTextures = new Array();
  21902. this.soundTracks = new Array();
  21903. this._audioEnabled = true;
  21904. this._headphone = false;
  21905. // Performance counters
  21906. this._totalVertices = new BABYLON.PerfCounter();
  21907. this._activeIndices = new BABYLON.PerfCounter();
  21908. this._activeParticles = new BABYLON.PerfCounter();
  21909. this._activeBones = new BABYLON.PerfCounter();
  21910. this._animationTime = 0;
  21911. this.animationTimeScale = 1;
  21912. this._renderId = 0;
  21913. this._executeWhenReadyTimeoutId = -1;
  21914. this._intermediateRendering = false;
  21915. this._viewUpdateFlag = -1;
  21916. this._projectionUpdateFlag = -1;
  21917. this._alternateViewUpdateFlag = -1;
  21918. this._alternateProjectionUpdateFlag = -1;
  21919. this._toBeDisposed = new BABYLON.SmartArray(256);
  21920. this._activeRequests = new Array();
  21921. this._pendingData = new Array();
  21922. this._isDisposed = false;
  21923. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21924. this._activeMeshes = new BABYLON.SmartArray(256);
  21925. this._processedMaterials = new BABYLON.SmartArray(256);
  21926. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21927. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21928. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21929. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21930. this._activeAnimatables = new Array();
  21931. this._transformMatrix = BABYLON.Matrix.Zero();
  21932. this._useAlternateCameraConfiguration = false;
  21933. this._alternateRendering = false;
  21934. this.requireLightSorting = false;
  21935. this._depthRenderer = {};
  21936. this._activeMeshesFrozen = false;
  21937. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21938. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21939. this._engine.scenes.push(this);
  21940. this._uid = null;
  21941. this._renderingManager = new BABYLON.RenderingManager(this);
  21942. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21943. if (BABYLON.OutlineRenderer) {
  21944. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21945. }
  21946. if (BABYLON.Tools.IsWindowObjectExist()) {
  21947. this.attachControl();
  21948. }
  21949. //simplification queue
  21950. if (BABYLON.SimplificationQueue) {
  21951. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21952. }
  21953. //collision coordinator initialization. For now legacy per default.
  21954. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21955. // Uniform Buffer
  21956. this._createUbo();
  21957. // Default Image processing definition.
  21958. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21959. }
  21960. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21961. /** The fog is deactivated */
  21962. get: function () {
  21963. return Scene._FOGMODE_NONE;
  21964. },
  21965. enumerable: true,
  21966. configurable: true
  21967. });
  21968. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21969. /** The fog density is following an exponential function */
  21970. get: function () {
  21971. return Scene._FOGMODE_EXP;
  21972. },
  21973. enumerable: true,
  21974. configurable: true
  21975. });
  21976. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21977. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21978. get: function () {
  21979. return Scene._FOGMODE_EXP2;
  21980. },
  21981. enumerable: true,
  21982. configurable: true
  21983. });
  21984. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21985. /** The fog density is following a linear function. */
  21986. get: function () {
  21987. return Scene._FOGMODE_LINEAR;
  21988. },
  21989. enumerable: true,
  21990. configurable: true
  21991. });
  21992. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21993. /**
  21994. * Texture used in all pbr material as the reflection texture.
  21995. * As in the majority of the scene they are the same (exception for multi room and so on),
  21996. * this is easier to reference from here than from all the materials.
  21997. */
  21998. get: function () {
  21999. return this._environmentTexture;
  22000. },
  22001. /**
  22002. * Texture used in all pbr material as the reflection texture.
  22003. * As in the majority of the scene they are the same (exception for multi room and so on),
  22004. * this is easier to set here than in all the materials.
  22005. */
  22006. set: function (value) {
  22007. if (this._environmentTexture === value) {
  22008. return;
  22009. }
  22010. this._environmentTexture = value;
  22011. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22012. },
  22013. enumerable: true,
  22014. configurable: true
  22015. });
  22016. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  22017. /**
  22018. * Default image processing configuration used either in the rendering
  22019. * Forward main pass or through the imageProcessingPostProcess if present.
  22020. * As in the majority of the scene they are the same (exception for multi camera),
  22021. * this is easier to reference from here than from all the materials and post process.
  22022. *
  22023. * No setter as we it is a shared configuration, you can set the values instead.
  22024. */
  22025. get: function () {
  22026. return this._imageProcessingConfiguration;
  22027. },
  22028. enumerable: true,
  22029. configurable: true
  22030. });
  22031. Object.defineProperty(Scene.prototype, "forceWireframe", {
  22032. get: function () {
  22033. return this._forceWireframe;
  22034. },
  22035. set: function (value) {
  22036. if (this._forceWireframe === value) {
  22037. return;
  22038. }
  22039. this._forceWireframe = value;
  22040. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22041. },
  22042. enumerable: true,
  22043. configurable: true
  22044. });
  22045. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  22046. get: function () {
  22047. return this._forcePointsCloud;
  22048. },
  22049. set: function (value) {
  22050. if (this._forcePointsCloud === value) {
  22051. return;
  22052. }
  22053. this._forcePointsCloud = value;
  22054. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22055. },
  22056. enumerable: true,
  22057. configurable: true
  22058. });
  22059. Object.defineProperty(Scene.prototype, "onDispose", {
  22060. /** A function to be executed when this scene is disposed. */
  22061. set: function (callback) {
  22062. if (this._onDisposeObserver) {
  22063. this.onDisposeObservable.remove(this._onDisposeObserver);
  22064. }
  22065. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22066. },
  22067. enumerable: true,
  22068. configurable: true
  22069. });
  22070. Object.defineProperty(Scene.prototype, "beforeRender", {
  22071. /** A function to be executed before rendering this scene */
  22072. set: function (callback) {
  22073. if (this._onBeforeRenderObserver) {
  22074. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22075. }
  22076. if (callback) {
  22077. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22078. }
  22079. },
  22080. enumerable: true,
  22081. configurable: true
  22082. });
  22083. Object.defineProperty(Scene.prototype, "afterRender", {
  22084. /** A function to be executed after rendering this scene */
  22085. set: function (callback) {
  22086. if (this._onAfterRenderObserver) {
  22087. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22088. }
  22089. if (callback) {
  22090. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22091. }
  22092. },
  22093. enumerable: true,
  22094. configurable: true
  22095. });
  22096. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22097. set: function (callback) {
  22098. if (this._onBeforeCameraRenderObserver) {
  22099. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22100. }
  22101. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22102. },
  22103. enumerable: true,
  22104. configurable: true
  22105. });
  22106. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22107. set: function (callback) {
  22108. if (this._onAfterCameraRenderObserver) {
  22109. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22110. }
  22111. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22112. },
  22113. enumerable: true,
  22114. configurable: true
  22115. });
  22116. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22117. get: function () {
  22118. if (!this._gamepadManager) {
  22119. this._gamepadManager = new BABYLON.GamepadManager(this);
  22120. }
  22121. return this._gamepadManager;
  22122. },
  22123. enumerable: true,
  22124. configurable: true
  22125. });
  22126. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22127. get: function () {
  22128. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22129. },
  22130. enumerable: true,
  22131. configurable: true
  22132. });
  22133. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22134. get: function () {
  22135. return this._useRightHandedSystem;
  22136. },
  22137. set: function (value) {
  22138. if (this._useRightHandedSystem === value) {
  22139. return;
  22140. }
  22141. this._useRightHandedSystem = value;
  22142. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22143. },
  22144. enumerable: true,
  22145. configurable: true
  22146. });
  22147. Scene.prototype.setStepId = function (newStepId) {
  22148. this._currentStepId = newStepId;
  22149. };
  22150. ;
  22151. Scene.prototype.getStepId = function () {
  22152. return this._currentStepId;
  22153. };
  22154. ;
  22155. Scene.prototype.getInternalStep = function () {
  22156. return this._currentInternalStep;
  22157. };
  22158. ;
  22159. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22160. get: function () {
  22161. return this._fogEnabled;
  22162. },
  22163. /**
  22164. * is fog enabled on this scene.
  22165. */
  22166. set: function (value) {
  22167. if (this._fogEnabled === value) {
  22168. return;
  22169. }
  22170. this._fogEnabled = value;
  22171. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22172. },
  22173. enumerable: true,
  22174. configurable: true
  22175. });
  22176. Object.defineProperty(Scene.prototype, "fogMode", {
  22177. get: function () {
  22178. return this._fogMode;
  22179. },
  22180. set: function (value) {
  22181. if (this._fogMode === value) {
  22182. return;
  22183. }
  22184. this._fogMode = value;
  22185. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22186. },
  22187. enumerable: true,
  22188. configurable: true
  22189. });
  22190. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22191. get: function () {
  22192. return this._shadowsEnabled;
  22193. },
  22194. set: function (value) {
  22195. if (this._shadowsEnabled === value) {
  22196. return;
  22197. }
  22198. this._shadowsEnabled = value;
  22199. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22200. },
  22201. enumerable: true,
  22202. configurable: true
  22203. });
  22204. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22205. get: function () {
  22206. return this._lightsEnabled;
  22207. },
  22208. set: function (value) {
  22209. if (this._lightsEnabled === value) {
  22210. return;
  22211. }
  22212. this._lightsEnabled = value;
  22213. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22214. },
  22215. enumerable: true,
  22216. configurable: true
  22217. });
  22218. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22219. /** The default material used on meshes when no material is affected */
  22220. get: function () {
  22221. if (!this._defaultMaterial) {
  22222. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22223. }
  22224. return this._defaultMaterial;
  22225. },
  22226. /** The default material used on meshes when no material is affected */
  22227. set: function (value) {
  22228. this._defaultMaterial = value;
  22229. },
  22230. enumerable: true,
  22231. configurable: true
  22232. });
  22233. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22234. get: function () {
  22235. return this._texturesEnabled;
  22236. },
  22237. set: function (value) {
  22238. if (this._texturesEnabled === value) {
  22239. return;
  22240. }
  22241. this._texturesEnabled = value;
  22242. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22243. },
  22244. enumerable: true,
  22245. configurable: true
  22246. });
  22247. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22248. get: function () {
  22249. return this._skeletonsEnabled;
  22250. },
  22251. set: function (value) {
  22252. if (this._skeletonsEnabled === value) {
  22253. return;
  22254. }
  22255. this._skeletonsEnabled = value;
  22256. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22257. },
  22258. enumerable: true,
  22259. configurable: true
  22260. });
  22261. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22262. get: function () {
  22263. if (!this._postProcessRenderPipelineManager) {
  22264. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22265. }
  22266. return this._postProcessRenderPipelineManager;
  22267. },
  22268. enumerable: true,
  22269. configurable: true
  22270. });
  22271. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22272. get: function () {
  22273. if (!this._mainSoundTrack) {
  22274. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22275. }
  22276. return this._mainSoundTrack;
  22277. },
  22278. enumerable: true,
  22279. configurable: true
  22280. });
  22281. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22282. get: function () {
  22283. return this._alternateRendering;
  22284. },
  22285. enumerable: true,
  22286. configurable: true
  22287. });
  22288. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22289. get: function () {
  22290. return this._frustumPlanes;
  22291. },
  22292. enumerable: true,
  22293. configurable: true
  22294. });
  22295. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22296. /**
  22297. * Gets the current geometry buffer associated to the scene.
  22298. */
  22299. get: function () {
  22300. return this._geometryBufferRenderer;
  22301. },
  22302. /**
  22303. * Sets the current geometry buffer for the scene.
  22304. */
  22305. set: function (geometryBufferRenderer) {
  22306. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22307. this._geometryBufferRenderer = geometryBufferRenderer;
  22308. }
  22309. },
  22310. enumerable: true,
  22311. configurable: true
  22312. });
  22313. Object.defineProperty(Scene.prototype, "debugLayer", {
  22314. // Properties
  22315. get: function () {
  22316. if (!this._debugLayer) {
  22317. this._debugLayer = new BABYLON.DebugLayer(this);
  22318. }
  22319. return this._debugLayer;
  22320. },
  22321. enumerable: true,
  22322. configurable: true
  22323. });
  22324. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22325. get: function () {
  22326. return this._workerCollisions;
  22327. },
  22328. set: function (enabled) {
  22329. if (!BABYLON.CollisionCoordinatorLegacy) {
  22330. return;
  22331. }
  22332. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22333. this._workerCollisions = enabled;
  22334. if (this.collisionCoordinator) {
  22335. this.collisionCoordinator.destroy();
  22336. }
  22337. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22338. this.collisionCoordinator.init(this);
  22339. },
  22340. enumerable: true,
  22341. configurable: true
  22342. });
  22343. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22344. get: function () {
  22345. return this._selectionOctree;
  22346. },
  22347. enumerable: true,
  22348. configurable: true
  22349. });
  22350. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22351. /**
  22352. * The mesh that is currently under the pointer.
  22353. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22354. */
  22355. get: function () {
  22356. return this._pointerOverMesh;
  22357. },
  22358. enumerable: true,
  22359. configurable: true
  22360. });
  22361. Object.defineProperty(Scene.prototype, "pointerX", {
  22362. /**
  22363. * Current on-screen X position of the pointer
  22364. * @return {number} X position of the pointer
  22365. */
  22366. get: function () {
  22367. return this._pointerX;
  22368. },
  22369. enumerable: true,
  22370. configurable: true
  22371. });
  22372. Object.defineProperty(Scene.prototype, "pointerY", {
  22373. /**
  22374. * Current on-screen Y position of the pointer
  22375. * @return {number} Y position of the pointer
  22376. */
  22377. get: function () {
  22378. return this._pointerY;
  22379. },
  22380. enumerable: true,
  22381. configurable: true
  22382. });
  22383. Scene.prototype.getCachedMaterial = function () {
  22384. return this._cachedMaterial;
  22385. };
  22386. Scene.prototype.getCachedEffect = function () {
  22387. return this._cachedEffect;
  22388. };
  22389. Scene.prototype.getCachedVisibility = function () {
  22390. return this._cachedVisibility;
  22391. };
  22392. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22393. if (visibility === void 0) { visibility = 1; }
  22394. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22395. };
  22396. Scene.prototype.getBoundingBoxRenderer = function () {
  22397. if (!this._boundingBoxRenderer) {
  22398. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22399. }
  22400. return this._boundingBoxRenderer;
  22401. };
  22402. Scene.prototype.getOutlineRenderer = function () {
  22403. return this._outlineRenderer;
  22404. };
  22405. Scene.prototype.getEngine = function () {
  22406. return this._engine;
  22407. };
  22408. Scene.prototype.getTotalVertices = function () {
  22409. return this._totalVertices.current;
  22410. };
  22411. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22412. get: function () {
  22413. return this._totalVertices;
  22414. },
  22415. enumerable: true,
  22416. configurable: true
  22417. });
  22418. Scene.prototype.getActiveIndices = function () {
  22419. return this._activeIndices.current;
  22420. };
  22421. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22422. get: function () {
  22423. return this._activeIndices;
  22424. },
  22425. enumerable: true,
  22426. configurable: true
  22427. });
  22428. Scene.prototype.getActiveParticles = function () {
  22429. return this._activeParticles.current;
  22430. };
  22431. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22432. get: function () {
  22433. return this._activeParticles;
  22434. },
  22435. enumerable: true,
  22436. configurable: true
  22437. });
  22438. Scene.prototype.getActiveBones = function () {
  22439. return this._activeBones.current;
  22440. };
  22441. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22442. get: function () {
  22443. return this._activeBones;
  22444. },
  22445. enumerable: true,
  22446. configurable: true
  22447. });
  22448. // Stats
  22449. Scene.prototype.getInterFramePerfCounter = function () {
  22450. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22451. return 0;
  22452. };
  22453. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22454. get: function () {
  22455. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22456. return null;
  22457. },
  22458. enumerable: true,
  22459. configurable: true
  22460. });
  22461. Scene.prototype.getLastFrameDuration = function () {
  22462. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22463. return 0;
  22464. };
  22465. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22466. get: function () {
  22467. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22468. return null;
  22469. },
  22470. enumerable: true,
  22471. configurable: true
  22472. });
  22473. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22474. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22475. return 0;
  22476. };
  22477. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22478. get: function () {
  22479. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22480. return null;
  22481. },
  22482. enumerable: true,
  22483. configurable: true
  22484. });
  22485. Scene.prototype.getActiveMeshes = function () {
  22486. return this._activeMeshes;
  22487. };
  22488. Scene.prototype.getRenderTargetsDuration = function () {
  22489. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22490. return 0;
  22491. };
  22492. Scene.prototype.getRenderDuration = function () {
  22493. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22494. return 0;
  22495. };
  22496. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22497. get: function () {
  22498. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22499. return null;
  22500. },
  22501. enumerable: true,
  22502. configurable: true
  22503. });
  22504. Scene.prototype.getParticlesDuration = function () {
  22505. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22506. return 0;
  22507. };
  22508. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22509. get: function () {
  22510. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22511. return null;
  22512. },
  22513. enumerable: true,
  22514. configurable: true
  22515. });
  22516. Scene.prototype.getSpritesDuration = function () {
  22517. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22518. return 0;
  22519. };
  22520. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22521. get: function () {
  22522. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22523. return null;
  22524. },
  22525. enumerable: true,
  22526. configurable: true
  22527. });
  22528. Scene.prototype.getAnimationRatio = function () {
  22529. return this._animationRatio;
  22530. };
  22531. Scene.prototype.getRenderId = function () {
  22532. return this._renderId;
  22533. };
  22534. Scene.prototype.incrementRenderId = function () {
  22535. this._renderId++;
  22536. };
  22537. Scene.prototype._updatePointerPosition = function (evt) {
  22538. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22539. if (!canvasRect) {
  22540. return;
  22541. }
  22542. this._pointerX = evt.clientX - canvasRect.left;
  22543. this._pointerY = evt.clientY - canvasRect.top;
  22544. this._unTranslatedPointerX = this._pointerX;
  22545. this._unTranslatedPointerY = this._pointerY;
  22546. };
  22547. Scene.prototype._createUbo = function () {
  22548. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22549. this._sceneUbo.addUniform("viewProjection", 16);
  22550. this._sceneUbo.addUniform("view", 16);
  22551. };
  22552. Scene.prototype._createAlternateUbo = function () {
  22553. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22554. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22555. this._alternateSceneUbo.addUniform("view", 16);
  22556. };
  22557. // Pointers handling
  22558. /**
  22559. * Use this method to simulate a pointer move on a mesh
  22560. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22561. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22562. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22563. */
  22564. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22565. var evt = new PointerEvent("pointermove", pointerEventInit);
  22566. return this._processPointerMove(pickResult, evt);
  22567. };
  22568. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22569. var canvas = this._engine.getRenderingCanvas();
  22570. if (!canvas) {
  22571. return this;
  22572. }
  22573. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22574. this.setPointerOverSprite(null);
  22575. this.setPointerOverMesh(pickResult.pickedMesh);
  22576. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22577. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22578. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22579. }
  22580. else {
  22581. canvas.style.cursor = this.hoverCursor;
  22582. }
  22583. }
  22584. else {
  22585. canvas.style.cursor = this.defaultCursor;
  22586. }
  22587. }
  22588. else {
  22589. this.setPointerOverMesh(null);
  22590. // Sprites
  22591. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22592. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22593. this.setPointerOverSprite(pickResult.pickedSprite);
  22594. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22595. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22596. }
  22597. else {
  22598. canvas.style.cursor = this.hoverCursor;
  22599. }
  22600. }
  22601. else {
  22602. this.setPointerOverSprite(null);
  22603. // Restore pointer
  22604. canvas.style.cursor = this.defaultCursor;
  22605. }
  22606. }
  22607. if (pickResult) {
  22608. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22609. if (this.onPointerMove) {
  22610. this.onPointerMove(evt, pickResult, type);
  22611. }
  22612. if (this.onPointerObservable.hasObservers()) {
  22613. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22614. this.onPointerObservable.notifyObservers(pi, type);
  22615. }
  22616. }
  22617. return this;
  22618. };
  22619. /**
  22620. * Use this method to simulate a pointer down on a mesh
  22621. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22622. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22623. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22624. */
  22625. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22626. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22627. return this._processPointerDown(pickResult, evt);
  22628. };
  22629. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22630. var _this = this;
  22631. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22632. this._pickedDownMesh = pickResult.pickedMesh;
  22633. var actionManager = pickResult.pickedMesh.actionManager;
  22634. if (actionManager) {
  22635. if (actionManager.hasPickTriggers) {
  22636. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22637. switch (evt.button) {
  22638. case 0:
  22639. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22640. break;
  22641. case 1:
  22642. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22643. break;
  22644. case 2:
  22645. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22646. break;
  22647. }
  22648. }
  22649. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22650. window.setTimeout(function () {
  22651. 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);
  22652. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22653. if (_this._totalPointersPressed !== 0 &&
  22654. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22655. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22656. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22657. _this._startingPointerTime = 0;
  22658. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22659. }
  22660. }
  22661. }, Scene.LongPressDelay);
  22662. }
  22663. }
  22664. }
  22665. if (pickResult) {
  22666. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22667. if (this.onPointerDown) {
  22668. this.onPointerDown(evt, pickResult, type);
  22669. }
  22670. if (this.onPointerObservable.hasObservers()) {
  22671. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22672. this.onPointerObservable.notifyObservers(pi, type);
  22673. }
  22674. }
  22675. return this;
  22676. };
  22677. /**
  22678. * Use this method to simulate a pointer up on a mesh
  22679. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22680. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22681. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22682. */
  22683. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22684. var evt = new PointerEvent("pointerup", pointerEventInit);
  22685. var clickInfo = new ClickInfo();
  22686. clickInfo.singleClick = true;
  22687. clickInfo.ignore = true;
  22688. return this._processPointerUp(pickResult, evt, clickInfo);
  22689. };
  22690. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22691. if (pickResult && pickResult && pickResult.pickedMesh) {
  22692. this._pickedUpMesh = pickResult.pickedMesh;
  22693. if (this._pickedDownMesh === this._pickedUpMesh) {
  22694. if (this.onPointerPick) {
  22695. this.onPointerPick(evt, pickResult);
  22696. }
  22697. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22698. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22699. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22700. this.onPointerObservable.notifyObservers(pi, type_1);
  22701. }
  22702. }
  22703. if (pickResult.pickedMesh.actionManager) {
  22704. if (clickInfo.ignore) {
  22705. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22706. }
  22707. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22708. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22709. }
  22710. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22711. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22712. }
  22713. }
  22714. }
  22715. if (this._pickedDownMesh &&
  22716. this._pickedDownMesh.actionManager &&
  22717. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22718. this._pickedDownMesh !== this._pickedUpMesh) {
  22719. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22720. }
  22721. var type = BABYLON.PointerEventTypes.POINTERUP;
  22722. if (this.onPointerObservable.hasObservers()) {
  22723. if (!clickInfo.ignore) {
  22724. if (!clickInfo.hasSwiped) {
  22725. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22726. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22727. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22728. this.onPointerObservable.notifyObservers(pi, type_2);
  22729. }
  22730. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22731. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22732. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22733. this.onPointerObservable.notifyObservers(pi, type_3);
  22734. }
  22735. }
  22736. }
  22737. else {
  22738. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22739. this.onPointerObservable.notifyObservers(pi, type);
  22740. }
  22741. }
  22742. if (this.onPointerUp) {
  22743. this.onPointerUp(evt, pickResult, type);
  22744. }
  22745. return this;
  22746. };
  22747. /**
  22748. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22749. * @param attachUp defines if you want to attach events to pointerup
  22750. * @param attachDown defines if you want to attach events to pointerdown
  22751. * @param attachMove defines if you want to attach events to pointermove
  22752. */
  22753. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22754. var _this = this;
  22755. if (attachUp === void 0) { attachUp = true; }
  22756. if (attachDown === void 0) { attachDown = true; }
  22757. if (attachMove === void 0) { attachMove = true; }
  22758. this._initActionManager = function (act, clickInfo) {
  22759. if (!_this._meshPickProceed) {
  22760. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22761. _this._currentPickResult = pickResult;
  22762. if (pickResult) {
  22763. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22764. }
  22765. _this._meshPickProceed = true;
  22766. }
  22767. return act;
  22768. };
  22769. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22770. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22771. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22772. btn !== _this._previousButtonPressed) {
  22773. _this._doubleClickOccured = false;
  22774. clickInfo.singleClick = true;
  22775. clickInfo.ignore = false;
  22776. cb(clickInfo, _this._currentPickResult);
  22777. }
  22778. };
  22779. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22780. var clickInfo = new ClickInfo();
  22781. _this._currentPickResult = null;
  22782. var act = null;
  22783. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22784. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22785. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22786. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22787. act = _this._initActionManager(act, clickInfo);
  22788. if (act)
  22789. checkPicking = act.hasPickTriggers;
  22790. }
  22791. if (checkPicking) {
  22792. var btn = evt.button;
  22793. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22794. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22795. if (!clickInfo.hasSwiped) {
  22796. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22797. if (!checkSingleClickImmediately) {
  22798. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22799. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22800. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22801. act = _this._initActionManager(act, clickInfo);
  22802. if (act)
  22803. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22804. }
  22805. }
  22806. if (checkSingleClickImmediately) {
  22807. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22808. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22809. btn !== _this._previousButtonPressed) {
  22810. clickInfo.singleClick = true;
  22811. cb(clickInfo, _this._currentPickResult);
  22812. }
  22813. }
  22814. else {
  22815. // wait that no double click has been raised during the double click delay
  22816. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22817. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22818. }
  22819. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22820. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22821. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22822. act = _this._initActionManager(act, clickInfo);
  22823. if (act)
  22824. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22825. }
  22826. if (checkDoubleClick) {
  22827. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22828. if (btn === _this._previousButtonPressed &&
  22829. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22830. !_this._doubleClickOccured) {
  22831. // pointer has not moved for 2 clicks, it's a double click
  22832. if (!clickInfo.hasSwiped &&
  22833. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22834. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22835. _this._previousStartingPointerTime = 0;
  22836. _this._doubleClickOccured = true;
  22837. clickInfo.doubleClick = true;
  22838. clickInfo.ignore = false;
  22839. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22840. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22841. }
  22842. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22843. cb(clickInfo, _this._currentPickResult);
  22844. }
  22845. else {
  22846. _this._doubleClickOccured = false;
  22847. _this._previousStartingPointerTime = _this._startingPointerTime;
  22848. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22849. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22850. _this._previousButtonPressed = btn;
  22851. if (Scene.ExclusiveDoubleClickMode) {
  22852. if (_this._previousDelayedSimpleClickTimeout) {
  22853. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22854. }
  22855. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22856. cb(clickInfo, _this._previousPickResult);
  22857. }
  22858. else {
  22859. cb(clickInfo, _this._currentPickResult);
  22860. }
  22861. }
  22862. }
  22863. else {
  22864. _this._doubleClickOccured = false;
  22865. _this._previousStartingPointerTime = _this._startingPointerTime;
  22866. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22867. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22868. _this._previousButtonPressed = btn;
  22869. }
  22870. }
  22871. }
  22872. }
  22873. clickInfo.ignore = true;
  22874. cb(clickInfo, _this._currentPickResult);
  22875. };
  22876. this._spritePredicate = function (sprite) {
  22877. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22878. };
  22879. this._onPointerMove = function (evt) {
  22880. _this._updatePointerPosition(evt);
  22881. // PreObservable support
  22882. if (_this.onPrePointerObservable.hasObservers()) {
  22883. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22884. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22885. _this.onPrePointerObservable.notifyObservers(pi, type);
  22886. if (pi.skipOnPointerObservable) {
  22887. return;
  22888. }
  22889. }
  22890. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22891. return;
  22892. }
  22893. if (!_this.pointerMovePredicate) {
  22894. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22895. }
  22896. // Meshes
  22897. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22898. _this._processPointerMove(pickResult, evt);
  22899. };
  22900. this._onPointerDown = function (evt) {
  22901. _this._totalPointersPressed++;
  22902. _this._pickedDownMesh = null;
  22903. _this._meshPickProceed = false;
  22904. _this._updatePointerPosition(evt);
  22905. if (_this.preventDefaultOnPointerDown && canvas) {
  22906. evt.preventDefault();
  22907. canvas.focus();
  22908. }
  22909. // PreObservable support
  22910. if (_this.onPrePointerObservable.hasObservers()) {
  22911. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22912. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22913. _this.onPrePointerObservable.notifyObservers(pi, type);
  22914. if (pi.skipOnPointerObservable) {
  22915. return;
  22916. }
  22917. }
  22918. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22919. return;
  22920. }
  22921. _this._startingPointerPosition.x = _this._pointerX;
  22922. _this._startingPointerPosition.y = _this._pointerY;
  22923. _this._startingPointerTime = new Date().getTime();
  22924. if (!_this.pointerDownPredicate) {
  22925. _this.pointerDownPredicate = function (mesh) {
  22926. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22927. };
  22928. }
  22929. // Meshes
  22930. _this._pickedDownMesh = null;
  22931. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22932. _this._processPointerDown(pickResult, evt);
  22933. // Sprites
  22934. _this._pickedDownSprite = null;
  22935. if (_this.spriteManagers.length > 0) {
  22936. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22937. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22938. if (pickResult.pickedSprite.actionManager) {
  22939. _this._pickedDownSprite = pickResult.pickedSprite;
  22940. switch (evt.button) {
  22941. case 0:
  22942. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22943. break;
  22944. case 1:
  22945. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22946. break;
  22947. case 2:
  22948. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22949. break;
  22950. }
  22951. if (pickResult.pickedSprite.actionManager) {
  22952. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22953. }
  22954. }
  22955. }
  22956. }
  22957. };
  22958. this._onPointerUp = function (evt) {
  22959. if (_this._totalPointersPressed === 0) {
  22960. return; // So we need to test it the pointer down was pressed before.
  22961. }
  22962. _this._totalPointersPressed--;
  22963. _this._pickedUpMesh = null;
  22964. _this._meshPickProceed = false;
  22965. _this._updatePointerPosition(evt);
  22966. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22967. // PreObservable support
  22968. if (_this.onPrePointerObservable.hasObservers()) {
  22969. if (!clickInfo.ignore) {
  22970. if (!clickInfo.hasSwiped) {
  22971. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22972. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22973. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22974. _this.onPrePointerObservable.notifyObservers(pi, type);
  22975. if (pi.skipOnPointerObservable) {
  22976. return;
  22977. }
  22978. }
  22979. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22980. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22981. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22982. _this.onPrePointerObservable.notifyObservers(pi, type);
  22983. if (pi.skipOnPointerObservable) {
  22984. return;
  22985. }
  22986. }
  22987. }
  22988. }
  22989. else {
  22990. var type = BABYLON.PointerEventTypes.POINTERUP;
  22991. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22992. _this.onPrePointerObservable.notifyObservers(pi, type);
  22993. if (pi.skipOnPointerObservable) {
  22994. return;
  22995. }
  22996. }
  22997. }
  22998. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22999. return;
  23000. }
  23001. if (!_this.pointerUpPredicate) {
  23002. _this.pointerUpPredicate = function (mesh) {
  23003. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  23004. };
  23005. }
  23006. // Meshes
  23007. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  23008. _this._initActionManager(null, clickInfo);
  23009. }
  23010. if (!pickResult) {
  23011. pickResult = _this._currentPickResult;
  23012. }
  23013. _this._processPointerUp(pickResult, evt, clickInfo);
  23014. // Sprites
  23015. if (_this.spriteManagers.length > 0) {
  23016. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23017. if (spritePickResult) {
  23018. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  23019. if (spritePickResult.pickedSprite.actionManager) {
  23020. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23021. if (spritePickResult.pickedSprite.actionManager) {
  23022. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  23023. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23024. }
  23025. }
  23026. }
  23027. }
  23028. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  23029. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  23030. }
  23031. }
  23032. }
  23033. _this._previousPickResult = _this._currentPickResult;
  23034. });
  23035. };
  23036. this._onKeyDown = function (evt) {
  23037. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  23038. if (_this.onPreKeyboardObservable.hasObservers()) {
  23039. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23040. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23041. if (pi.skipOnPointerObservable) {
  23042. return;
  23043. }
  23044. }
  23045. if (_this.onKeyboardObservable.hasObservers()) {
  23046. var pi = new BABYLON.KeyboardInfo(type, evt);
  23047. _this.onKeyboardObservable.notifyObservers(pi, type);
  23048. }
  23049. if (_this.actionManager) {
  23050. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23051. }
  23052. };
  23053. this._onKeyUp = function (evt) {
  23054. var type = BABYLON.KeyboardEventTypes.KEYUP;
  23055. if (_this.onPreKeyboardObservable.hasObservers()) {
  23056. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23057. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23058. if (pi.skipOnPointerObservable) {
  23059. return;
  23060. }
  23061. }
  23062. if (_this.onKeyboardObservable.hasObservers()) {
  23063. var pi = new BABYLON.KeyboardInfo(type, evt);
  23064. _this.onKeyboardObservable.notifyObservers(pi, type);
  23065. }
  23066. if (_this.actionManager) {
  23067. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23068. }
  23069. };
  23070. var engine = this.getEngine();
  23071. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  23072. if (!canvas) {
  23073. return;
  23074. }
  23075. canvas.addEventListener("keydown", _this._onKeyDown, false);
  23076. canvas.addEventListener("keyup", _this._onKeyUp, false);
  23077. });
  23078. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  23079. if (!canvas) {
  23080. return;
  23081. }
  23082. canvas.removeEventListener("keydown", _this._onKeyDown);
  23083. canvas.removeEventListener("keyup", _this._onKeyUp);
  23084. });
  23085. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23086. var canvas = this._engine.getRenderingCanvas();
  23087. if (!canvas) {
  23088. return;
  23089. }
  23090. if (attachMove) {
  23091. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23092. // Wheel
  23093. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23094. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23095. }
  23096. if (attachDown) {
  23097. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23098. }
  23099. if (attachUp) {
  23100. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23101. }
  23102. canvas.tabIndex = 1;
  23103. };
  23104. Scene.prototype.detachControl = function () {
  23105. var engine = this.getEngine();
  23106. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23107. var canvas = engine.getRenderingCanvas();
  23108. if (!canvas) {
  23109. return;
  23110. }
  23111. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23112. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23113. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23114. if (this._onCanvasBlurObserver) {
  23115. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23116. }
  23117. if (this._onCanvasFocusObserver) {
  23118. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23119. }
  23120. // Wheel
  23121. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23122. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23123. // Keyboard
  23124. canvas.removeEventListener("keydown", this._onKeyDown);
  23125. canvas.removeEventListener("keyup", this._onKeyUp);
  23126. // Observables
  23127. this.onKeyboardObservable.clear();
  23128. this.onPreKeyboardObservable.clear();
  23129. this.onPointerObservable.clear();
  23130. this.onPrePointerObservable.clear();
  23131. };
  23132. /**
  23133. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23134. * Delay loaded resources are not taking in account
  23135. * @return true if all required resources are ready
  23136. */
  23137. Scene.prototype.isReady = function () {
  23138. if (this._isDisposed) {
  23139. return false;
  23140. }
  23141. if (this._pendingData.length > 0) {
  23142. return false;
  23143. }
  23144. var index;
  23145. var engine = this.getEngine();
  23146. // Geometries
  23147. for (index = 0; index < this._geometries.length; index++) {
  23148. var geometry = this._geometries[index];
  23149. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23150. return false;
  23151. }
  23152. }
  23153. // Meshes
  23154. for (index = 0; index < this.meshes.length; index++) {
  23155. var mesh = this.meshes[index];
  23156. if (!mesh.isEnabled()) {
  23157. continue;
  23158. }
  23159. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23160. continue;
  23161. }
  23162. if (!mesh.isReady(true)) {
  23163. return false;
  23164. }
  23165. // Effect layers
  23166. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23167. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23168. var layer = _a[_i];
  23169. if (!layer.hasMesh(mesh)) {
  23170. continue;
  23171. }
  23172. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23173. var subMesh = _c[_b];
  23174. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23175. return false;
  23176. }
  23177. }
  23178. }
  23179. }
  23180. // Post-processes
  23181. if (this.activeCameras && this.activeCameras.length > 0) {
  23182. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  23183. var camera = _e[_d];
  23184. if (!camera.isReady(true)) {
  23185. return false;
  23186. }
  23187. }
  23188. }
  23189. else if (this.activeCamera) {
  23190. if (!this.activeCamera.isReady(true)) {
  23191. return false;
  23192. }
  23193. }
  23194. // Particles
  23195. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  23196. var particleSystem = _g[_f];
  23197. if (!particleSystem.isReady()) {
  23198. return false;
  23199. }
  23200. }
  23201. return true;
  23202. };
  23203. Scene.prototype.resetCachedMaterial = function () {
  23204. this._cachedMaterial = null;
  23205. this._cachedEffect = null;
  23206. this._cachedVisibility = null;
  23207. };
  23208. Scene.prototype.registerBeforeRender = function (func) {
  23209. this.onBeforeRenderObservable.add(func);
  23210. };
  23211. Scene.prototype.unregisterBeforeRender = function (func) {
  23212. this.onBeforeRenderObservable.removeCallback(func);
  23213. };
  23214. Scene.prototype.registerAfterRender = function (func) {
  23215. this.onAfterRenderObservable.add(func);
  23216. };
  23217. Scene.prototype.unregisterAfterRender = function (func) {
  23218. this.onAfterRenderObservable.removeCallback(func);
  23219. };
  23220. Scene.prototype._executeOnceBeforeRender = function (func) {
  23221. var _this = this;
  23222. var execFunc = function () {
  23223. func();
  23224. setTimeout(function () {
  23225. _this.unregisterBeforeRender(execFunc);
  23226. });
  23227. };
  23228. this.registerBeforeRender(execFunc);
  23229. };
  23230. /**
  23231. * The provided function will run before render once and will be disposed afterwards.
  23232. * A timeout delay can be provided so that the function will be executed in N ms.
  23233. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23234. * @param func The function to be executed.
  23235. * @param timeout optional delay in ms
  23236. */
  23237. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23238. var _this = this;
  23239. if (timeout !== undefined) {
  23240. setTimeout(function () {
  23241. _this._executeOnceBeforeRender(func);
  23242. }, timeout);
  23243. }
  23244. else {
  23245. this._executeOnceBeforeRender(func);
  23246. }
  23247. };
  23248. Scene.prototype._addPendingData = function (data) {
  23249. this._pendingData.push(data);
  23250. };
  23251. Scene.prototype._removePendingData = function (data) {
  23252. var wasLoading = this.isLoading;
  23253. var index = this._pendingData.indexOf(data);
  23254. if (index !== -1) {
  23255. this._pendingData.splice(index, 1);
  23256. }
  23257. if (wasLoading && !this.isLoading) {
  23258. this.onDataLoadedObservable.notifyObservers(this);
  23259. }
  23260. };
  23261. Scene.prototype.getWaitingItemsCount = function () {
  23262. return this._pendingData.length;
  23263. };
  23264. Object.defineProperty(Scene.prototype, "isLoading", {
  23265. get: function () {
  23266. return this._pendingData.length > 0;
  23267. },
  23268. enumerable: true,
  23269. configurable: true
  23270. });
  23271. /**
  23272. * Registers a function to be executed when the scene is ready.
  23273. * @param {Function} func - the function to be executed.
  23274. */
  23275. Scene.prototype.executeWhenReady = function (func) {
  23276. var _this = this;
  23277. this.onReadyObservable.add(func);
  23278. if (this._executeWhenReadyTimeoutId !== -1) {
  23279. return;
  23280. }
  23281. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23282. _this._checkIsReady();
  23283. }, 150);
  23284. };
  23285. /**
  23286. * Returns a promise that resolves when the scene is ready.
  23287. * @returns A promise that resolves when the scene is ready.
  23288. */
  23289. Scene.prototype.whenReadyAsync = function () {
  23290. var _this = this;
  23291. return new Promise(function (resolve) {
  23292. _this.executeWhenReady(function () {
  23293. resolve();
  23294. });
  23295. });
  23296. };
  23297. Scene.prototype._checkIsReady = function () {
  23298. var _this = this;
  23299. if (this.isReady()) {
  23300. this.onReadyObservable.notifyObservers(this);
  23301. this.onReadyObservable.clear();
  23302. this._executeWhenReadyTimeoutId = -1;
  23303. return;
  23304. }
  23305. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23306. _this._checkIsReady();
  23307. }, 150);
  23308. };
  23309. // Animations
  23310. /**
  23311. * Will start the animation sequence of a given target
  23312. * @param target defines the target
  23313. * @param from defines from which frame should animation start
  23314. * @param to defines until which frame should animation run.
  23315. * @param weight defines the weight to apply to the animation (1.0 by default)
  23316. * @param loop defines if the animation loops
  23317. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23318. * @param onAnimationEnd defines the function to be executed when the animation ends
  23319. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23320. * @returns the animatable object created for this animation
  23321. * @see BABYLON.Animatable
  23322. */
  23323. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23324. if (weight === void 0) { weight = 1.0; }
  23325. if (speedRatio === void 0) { speedRatio = 1.0; }
  23326. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23327. returnedAnimatable.weight = weight;
  23328. return returnedAnimatable;
  23329. };
  23330. /**
  23331. * Will start the animation sequence of a given target
  23332. * @param target defines the target
  23333. * @param from defines from which frame should animation start
  23334. * @param to defines until which frame should animation run.
  23335. * @param loop defines if the animation loops
  23336. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23337. * @param onAnimationEnd defines the function to be executed when the animation ends
  23338. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23339. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23340. * @returns the animatable object created for this animation
  23341. * @see BABYLON.Animatable
  23342. */
  23343. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23344. if (speedRatio === void 0) { speedRatio = 1.0; }
  23345. if (stopCurrent === void 0) { stopCurrent = true; }
  23346. if (from > to && speedRatio > 0) {
  23347. speedRatio *= -1;
  23348. }
  23349. if (stopCurrent) {
  23350. this.stopAnimation(target);
  23351. }
  23352. if (!animatable) {
  23353. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23354. }
  23355. // Local animations
  23356. if (target.animations) {
  23357. animatable.appendAnimations(target, target.animations);
  23358. }
  23359. // Children animations
  23360. if (target.getAnimatables) {
  23361. var animatables = target.getAnimatables();
  23362. for (var index = 0; index < animatables.length; index++) {
  23363. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23364. }
  23365. }
  23366. animatable.reset();
  23367. return animatable;
  23368. };
  23369. /**
  23370. * Begin a new animation on a given node
  23371. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23372. * @param {BABYLON.Animation[]} defines the list of animations to start
  23373. * @param {number} from defines the initial value
  23374. * @param {number} to defines the final value
  23375. * @param {boolean} loop defines if you want animation to loop (off by default)
  23376. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23377. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23378. * @returns the list of created animatables
  23379. */
  23380. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23381. if (speedRatio === undefined) {
  23382. speedRatio = 1.0;
  23383. }
  23384. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23385. return animatable;
  23386. };
  23387. /**
  23388. * Begin a new animation on a given node and its hierarchy
  23389. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23390. * @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.
  23391. * @param {BABYLON.Animation[]} defines the list of animations to start
  23392. * @param {number} from defines the initial value
  23393. * @param {number} to defines the final value
  23394. * @param {boolean} loop defines if you want animation to loop (off by default)
  23395. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23396. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23397. * @returns the list of animatables created for all nodes
  23398. */
  23399. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23400. var children = target.getDescendants(directDescendantsOnly);
  23401. var result = [];
  23402. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23403. var child = children_1[_i];
  23404. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23405. }
  23406. return result;
  23407. };
  23408. Scene.prototype.getAnimatableByTarget = function (target) {
  23409. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23410. if (this._activeAnimatables[index].target === target) {
  23411. return this._activeAnimatables[index];
  23412. }
  23413. }
  23414. return null;
  23415. };
  23416. /**
  23417. * Gets all animatables associated with a given target
  23418. * @param target defines the target to look animatables for
  23419. * @returns an array of Animatables
  23420. */
  23421. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  23422. var result = [];
  23423. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23424. if (this._activeAnimatables[index].target === target) {
  23425. result.push(this._activeAnimatables[index]);
  23426. }
  23427. }
  23428. return result;
  23429. };
  23430. Object.defineProperty(Scene.prototype, "animatables", {
  23431. get: function () {
  23432. return this._activeAnimatables;
  23433. },
  23434. enumerable: true,
  23435. configurable: true
  23436. });
  23437. /**
  23438. * Will stop the animation of the given target
  23439. * @param target - the target
  23440. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  23441. * @see beginAnimation
  23442. */
  23443. Scene.prototype.stopAnimation = function (target, animationName) {
  23444. var animatables = this.getAllAnimatablesByTarget(target);
  23445. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  23446. var animatable = animatables_1[_i];
  23447. animatable.stop(animationName);
  23448. }
  23449. };
  23450. /**
  23451. * Stops and removes all animations that have been applied to the scene
  23452. */
  23453. Scene.prototype.stopAllAnimations = function () {
  23454. if (this._activeAnimatables) {
  23455. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23456. this._activeAnimatables[i].stop();
  23457. }
  23458. this._activeAnimatables = [];
  23459. }
  23460. };
  23461. Scene.prototype._animate = function () {
  23462. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23463. return;
  23464. }
  23465. // Getting time
  23466. var now = BABYLON.Tools.Now;
  23467. if (!this._animationTimeLast) {
  23468. if (this._pendingData.length > 0) {
  23469. return;
  23470. }
  23471. this._animationTimeLast = now;
  23472. }
  23473. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23474. this._animationTime += deltaTime;
  23475. this._animationTimeLast = now;
  23476. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23477. this._activeAnimatables[index]._animate(this._animationTime);
  23478. }
  23479. // Late animation bindings
  23480. this._processLateAnimationBindings();
  23481. };
  23482. /** @ignore */
  23483. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23484. var target = runtimeAnimation.target;
  23485. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23486. if (!target._lateAnimationHolders) {
  23487. target._lateAnimationHolders = {};
  23488. }
  23489. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23490. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23491. totalWeight: 0,
  23492. animations: []
  23493. };
  23494. }
  23495. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23496. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23497. };
  23498. Scene.prototype._processLateAnimationBindings = function () {
  23499. if (!this._registeredForLateAnimationBindings.length) {
  23500. return;
  23501. }
  23502. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23503. var target = this._registeredForLateAnimationBindings.data[index];
  23504. for (var path in target._lateAnimationHolders) {
  23505. var holder = target._lateAnimationHolders[path];
  23506. // Sanity check
  23507. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23508. continue;
  23509. }
  23510. var normalizer = 1.0;
  23511. var finalValue = void 0;
  23512. if (holder.totalWeight < 1.0) {
  23513. // We need to mix the original value in
  23514. var originalValue = holder.animations[0].originalValue;
  23515. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23516. }
  23517. else {
  23518. // We need to normalize the weights
  23519. normalizer = holder.totalWeight;
  23520. }
  23521. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23522. var runtimeAnimation = holder.animations[animIndex];
  23523. if (finalValue) {
  23524. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23525. }
  23526. else {
  23527. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23528. }
  23529. }
  23530. runtimeAnimation.target[path] = finalValue;
  23531. }
  23532. target._lateAnimationHolders = {};
  23533. }
  23534. this._registeredForLateAnimationBindings.reset();
  23535. };
  23536. // Matrix
  23537. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23538. this._useAlternateCameraConfiguration = active;
  23539. };
  23540. Scene.prototype.getViewMatrix = function () {
  23541. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23542. };
  23543. Scene.prototype.getProjectionMatrix = function () {
  23544. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23545. };
  23546. Scene.prototype.getTransformMatrix = function () {
  23547. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23548. };
  23549. Scene.prototype.setTransformMatrix = function (view, projection) {
  23550. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23551. return;
  23552. }
  23553. this._viewUpdateFlag = view.updateFlag;
  23554. this._projectionUpdateFlag = projection.updateFlag;
  23555. this._viewMatrix = view;
  23556. this._projectionMatrix = projection;
  23557. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23558. // Update frustum
  23559. if (!this._frustumPlanes) {
  23560. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23561. }
  23562. else {
  23563. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23564. }
  23565. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23566. var otherCamera = this.activeCamera._alternateCamera;
  23567. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23568. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23569. }
  23570. if (this._sceneUbo.useUbo) {
  23571. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23572. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23573. this._sceneUbo.update();
  23574. }
  23575. };
  23576. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23577. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23578. return;
  23579. }
  23580. this._alternateViewUpdateFlag = view.updateFlag;
  23581. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23582. this._alternateViewMatrix = view;
  23583. this._alternateProjectionMatrix = projection;
  23584. if (!this._alternateTransformMatrix) {
  23585. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23586. }
  23587. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23588. if (!this._alternateSceneUbo) {
  23589. this._createAlternateUbo();
  23590. }
  23591. if (this._alternateSceneUbo.useUbo) {
  23592. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23593. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23594. this._alternateSceneUbo.update();
  23595. }
  23596. };
  23597. Scene.prototype.getSceneUniformBuffer = function () {
  23598. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23599. };
  23600. // Methods
  23601. Scene.prototype.getUniqueId = function () {
  23602. var result = Scene._uniqueIdCounter;
  23603. Scene._uniqueIdCounter++;
  23604. return result;
  23605. };
  23606. Scene.prototype.addMesh = function (newMesh) {
  23607. this.meshes.push(newMesh);
  23608. //notify the collision coordinator
  23609. if (this.collisionCoordinator) {
  23610. this.collisionCoordinator.onMeshAdded(newMesh);
  23611. }
  23612. newMesh._resyncLightSources();
  23613. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23614. };
  23615. Scene.prototype.removeMesh = function (toRemove) {
  23616. var index = this.meshes.indexOf(toRemove);
  23617. if (index !== -1) {
  23618. // Remove from the scene if mesh found
  23619. this.meshes.splice(index, 1);
  23620. }
  23621. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23622. return index;
  23623. };
  23624. Scene.prototype.addTransformNode = function (newTransformNode) {
  23625. this.transformNodes.push(newTransformNode);
  23626. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23627. };
  23628. Scene.prototype.removeTransformNode = function (toRemove) {
  23629. var index = this.transformNodes.indexOf(toRemove);
  23630. if (index !== -1) {
  23631. // Remove from the scene if found
  23632. this.transformNodes.splice(index, 1);
  23633. }
  23634. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23635. return index;
  23636. };
  23637. Scene.prototype.removeSkeleton = function (toRemove) {
  23638. var index = this.skeletons.indexOf(toRemove);
  23639. if (index !== -1) {
  23640. // Remove from the scene if found
  23641. this.skeletons.splice(index, 1);
  23642. }
  23643. return index;
  23644. };
  23645. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23646. var index = this.morphTargetManagers.indexOf(toRemove);
  23647. if (index !== -1) {
  23648. // Remove from the scene if found
  23649. this.morphTargetManagers.splice(index, 1);
  23650. }
  23651. return index;
  23652. };
  23653. Scene.prototype.removeLight = function (toRemove) {
  23654. var index = this.lights.indexOf(toRemove);
  23655. if (index !== -1) {
  23656. // Remove from meshes
  23657. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23658. var mesh = _a[_i];
  23659. mesh._removeLightSource(toRemove);
  23660. }
  23661. // Remove from the scene if mesh found
  23662. this.lights.splice(index, 1);
  23663. this.sortLightsByPriority();
  23664. }
  23665. this.onLightRemovedObservable.notifyObservers(toRemove);
  23666. return index;
  23667. };
  23668. Scene.prototype.removeCamera = function (toRemove) {
  23669. var index = this.cameras.indexOf(toRemove);
  23670. if (index !== -1) {
  23671. // Remove from the scene if mesh found
  23672. this.cameras.splice(index, 1);
  23673. }
  23674. // Remove from activeCameras
  23675. var index2 = this.activeCameras.indexOf(toRemove);
  23676. if (index2 !== -1) {
  23677. // Remove from the scene if mesh found
  23678. this.activeCameras.splice(index2, 1);
  23679. }
  23680. // Reset the activeCamera
  23681. if (this.activeCamera === toRemove) {
  23682. if (this.cameras.length > 0) {
  23683. this.activeCamera = this.cameras[0];
  23684. }
  23685. else {
  23686. this.activeCamera = null;
  23687. }
  23688. }
  23689. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23690. return index;
  23691. };
  23692. Scene.prototype.removeParticleSystem = function (toRemove) {
  23693. var index = this.particleSystems.indexOf(toRemove);
  23694. if (index !== -1) {
  23695. this.particleSystems.splice(index, 1);
  23696. }
  23697. return index;
  23698. };
  23699. ;
  23700. Scene.prototype.removeAnimation = function (toRemove) {
  23701. var index = this.animations.indexOf(toRemove);
  23702. if (index !== -1) {
  23703. this.animations.splice(index, 1);
  23704. }
  23705. return index;
  23706. };
  23707. ;
  23708. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23709. var index = this.multiMaterials.indexOf(toRemove);
  23710. if (index !== -1) {
  23711. this.multiMaterials.splice(index, 1);
  23712. }
  23713. return index;
  23714. };
  23715. ;
  23716. Scene.prototype.removeMaterial = function (toRemove) {
  23717. var index = this.materials.indexOf(toRemove);
  23718. if (index !== -1) {
  23719. this.materials.splice(index, 1);
  23720. }
  23721. return index;
  23722. };
  23723. ;
  23724. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23725. var index = this.lensFlareSystems.indexOf(toRemove);
  23726. if (index !== -1) {
  23727. this.lensFlareSystems.splice(index, 1);
  23728. }
  23729. return index;
  23730. };
  23731. ;
  23732. Scene.prototype.removeActionManager = function (toRemove) {
  23733. var index = this._actionManagers.indexOf(toRemove);
  23734. if (index !== -1) {
  23735. this._actionManagers.splice(index, 1);
  23736. }
  23737. return index;
  23738. };
  23739. ;
  23740. Scene.prototype.addLight = function (newLight) {
  23741. this.lights.push(newLight);
  23742. this.sortLightsByPriority();
  23743. // Add light to all meshes (To support if the light is removed and then readded)
  23744. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23745. var mesh = _a[_i];
  23746. if (mesh._lightSources.indexOf(newLight) === -1) {
  23747. mesh._lightSources.push(newLight);
  23748. mesh._resyncLightSources();
  23749. }
  23750. }
  23751. this.onNewLightAddedObservable.notifyObservers(newLight);
  23752. };
  23753. Scene.prototype.sortLightsByPriority = function () {
  23754. if (this.requireLightSorting) {
  23755. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23756. }
  23757. };
  23758. Scene.prototype.addCamera = function (newCamera) {
  23759. this.cameras.push(newCamera);
  23760. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23761. };
  23762. Scene.prototype.addSkeleton = function (newSkeleton) {
  23763. this.skeletons.push(newSkeleton);
  23764. };
  23765. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23766. this.particleSystems.push(newParticleSystem);
  23767. };
  23768. Scene.prototype.addAnimation = function (newAnimation) {
  23769. this.animations.push(newAnimation);
  23770. };
  23771. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23772. this.multiMaterials.push(newMultiMaterial);
  23773. };
  23774. Scene.prototype.addMaterial = function (newMaterial) {
  23775. this.materials.push(newMaterial);
  23776. };
  23777. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23778. this.morphTargetManagers.push(newMorphTargetManager);
  23779. };
  23780. Scene.prototype.addGeometry = function (newGeometrie) {
  23781. this._geometries.push(newGeometrie);
  23782. };
  23783. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23784. this.lensFlareSystems.push(newLensFlareSystem);
  23785. };
  23786. Scene.prototype.addActionManager = function (newActionManager) {
  23787. this._actionManagers.push(newActionManager);
  23788. };
  23789. /**
  23790. * Switch active camera
  23791. * @param {Camera} newCamera - new active camera
  23792. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23793. */
  23794. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23795. if (attachControl === void 0) { attachControl = true; }
  23796. var canvas = this._engine.getRenderingCanvas();
  23797. if (!canvas) {
  23798. return;
  23799. }
  23800. if (this.activeCamera) {
  23801. this.activeCamera.detachControl(canvas);
  23802. }
  23803. this.activeCamera = newCamera;
  23804. if (attachControl) {
  23805. newCamera.attachControl(canvas);
  23806. }
  23807. };
  23808. /**
  23809. * sets the active camera of the scene using its ID
  23810. * @param {string} id - the camera's ID
  23811. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23812. * @see activeCamera
  23813. */
  23814. Scene.prototype.setActiveCameraByID = function (id) {
  23815. var camera = this.getCameraByID(id);
  23816. if (camera) {
  23817. this.activeCamera = camera;
  23818. return camera;
  23819. }
  23820. return null;
  23821. };
  23822. /**
  23823. * sets the active camera of the scene using its name
  23824. * @param {string} name - the camera's name
  23825. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23826. * @see activeCamera
  23827. */
  23828. Scene.prototype.setActiveCameraByName = function (name) {
  23829. var camera = this.getCameraByName(name);
  23830. if (camera) {
  23831. this.activeCamera = camera;
  23832. return camera;
  23833. }
  23834. return null;
  23835. };
  23836. /**
  23837. * get an animation group using its name
  23838. * @param {string} the material's name
  23839. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23840. */
  23841. Scene.prototype.getAnimationGroupByName = function (name) {
  23842. for (var index = 0; index < this.animationGroups.length; index++) {
  23843. if (this.animationGroups[index].name === name) {
  23844. return this.animationGroups[index];
  23845. }
  23846. }
  23847. return null;
  23848. };
  23849. /**
  23850. * get a material using its id
  23851. * @param {string} the material's ID
  23852. * @return {BABYLON.Material|null} the material or null if none found.
  23853. */
  23854. Scene.prototype.getMaterialByID = function (id) {
  23855. for (var index = 0; index < this.materials.length; index++) {
  23856. if (this.materials[index].id === id) {
  23857. return this.materials[index];
  23858. }
  23859. }
  23860. return null;
  23861. };
  23862. /**
  23863. * get a material using its name
  23864. * @param {string} the material's name
  23865. * @return {BABYLON.Material|null} the material or null if none found.
  23866. */
  23867. Scene.prototype.getMaterialByName = function (name) {
  23868. for (var index = 0; index < this.materials.length; index++) {
  23869. if (this.materials[index].name === name) {
  23870. return this.materials[index];
  23871. }
  23872. }
  23873. return null;
  23874. };
  23875. Scene.prototype.getLensFlareSystemByName = function (name) {
  23876. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23877. if (this.lensFlareSystems[index].name === name) {
  23878. return this.lensFlareSystems[index];
  23879. }
  23880. }
  23881. return null;
  23882. };
  23883. Scene.prototype.getLensFlareSystemByID = function (id) {
  23884. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23885. if (this.lensFlareSystems[index].id === id) {
  23886. return this.lensFlareSystems[index];
  23887. }
  23888. }
  23889. return null;
  23890. };
  23891. Scene.prototype.getCameraByID = function (id) {
  23892. for (var index = 0; index < this.cameras.length; index++) {
  23893. if (this.cameras[index].id === id) {
  23894. return this.cameras[index];
  23895. }
  23896. }
  23897. return null;
  23898. };
  23899. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23900. for (var index = 0; index < this.cameras.length; index++) {
  23901. if (this.cameras[index].uniqueId === uniqueId) {
  23902. return this.cameras[index];
  23903. }
  23904. }
  23905. return null;
  23906. };
  23907. /**
  23908. * get a camera using its name
  23909. * @param {string} the camera's name
  23910. * @return {BABYLON.Camera|null} the camera or null if none found.
  23911. */
  23912. Scene.prototype.getCameraByName = function (name) {
  23913. for (var index = 0; index < this.cameras.length; index++) {
  23914. if (this.cameras[index].name === name) {
  23915. return this.cameras[index];
  23916. }
  23917. }
  23918. return null;
  23919. };
  23920. /**
  23921. * get a bone using its id
  23922. * @param {string} the bone's id
  23923. * @return {BABYLON.Bone|null} the bone or null if not found
  23924. */
  23925. Scene.prototype.getBoneByID = function (id) {
  23926. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23927. var skeleton = this.skeletons[skeletonIndex];
  23928. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23929. if (skeleton.bones[boneIndex].id === id) {
  23930. return skeleton.bones[boneIndex];
  23931. }
  23932. }
  23933. }
  23934. return null;
  23935. };
  23936. /**
  23937. * get a bone using its id
  23938. * @param {string} the bone's name
  23939. * @return {BABYLON.Bone|null} the bone or null if not found
  23940. */
  23941. Scene.prototype.getBoneByName = function (name) {
  23942. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23943. var skeleton = this.skeletons[skeletonIndex];
  23944. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23945. if (skeleton.bones[boneIndex].name === name) {
  23946. return skeleton.bones[boneIndex];
  23947. }
  23948. }
  23949. }
  23950. return null;
  23951. };
  23952. /**
  23953. * get a light node using its name
  23954. * @param {string} the light's name
  23955. * @return {BABYLON.Light|null} the light or null if none found.
  23956. */
  23957. Scene.prototype.getLightByName = function (name) {
  23958. for (var index = 0; index < this.lights.length; index++) {
  23959. if (this.lights[index].name === name) {
  23960. return this.lights[index];
  23961. }
  23962. }
  23963. return null;
  23964. };
  23965. /**
  23966. * get a light node using its ID
  23967. * @param {string} the light's id
  23968. * @return {BABYLON.Light|null} the light or null if none found.
  23969. */
  23970. Scene.prototype.getLightByID = function (id) {
  23971. for (var index = 0; index < this.lights.length; index++) {
  23972. if (this.lights[index].id === id) {
  23973. return this.lights[index];
  23974. }
  23975. }
  23976. return null;
  23977. };
  23978. /**
  23979. * get a light node using its scene-generated unique ID
  23980. * @param {number} the light's unique id
  23981. * @return {BABYLON.Light|null} the light or null if none found.
  23982. */
  23983. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23984. for (var index = 0; index < this.lights.length; index++) {
  23985. if (this.lights[index].uniqueId === uniqueId) {
  23986. return this.lights[index];
  23987. }
  23988. }
  23989. return null;
  23990. };
  23991. /**
  23992. * get a particle system by id
  23993. * @param id {number} the particle system id
  23994. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23995. */
  23996. Scene.prototype.getParticleSystemByID = function (id) {
  23997. for (var index = 0; index < this.particleSystems.length; index++) {
  23998. if (this.particleSystems[index].id === id) {
  23999. return this.particleSystems[index];
  24000. }
  24001. }
  24002. return null;
  24003. };
  24004. /**
  24005. * get a geometry using its ID
  24006. * @param {string} the geometry's id
  24007. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  24008. */
  24009. Scene.prototype.getGeometryByID = function (id) {
  24010. for (var index = 0; index < this._geometries.length; index++) {
  24011. if (this._geometries[index].id === id) {
  24012. return this._geometries[index];
  24013. }
  24014. }
  24015. return null;
  24016. };
  24017. /**
  24018. * add a new geometry to this scene.
  24019. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  24020. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  24021. * @return {boolean} was the geometry added or not
  24022. */
  24023. Scene.prototype.pushGeometry = function (geometry, force) {
  24024. if (!force && this.getGeometryByID(geometry.id)) {
  24025. return false;
  24026. }
  24027. this._geometries.push(geometry);
  24028. //notify the collision coordinator
  24029. if (this.collisionCoordinator) {
  24030. this.collisionCoordinator.onGeometryAdded(geometry);
  24031. }
  24032. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  24033. return true;
  24034. };
  24035. /**
  24036. * Removes an existing geometry
  24037. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  24038. * @return {boolean} was the geometry removed or not
  24039. */
  24040. Scene.prototype.removeGeometry = function (geometry) {
  24041. var index = this._geometries.indexOf(geometry);
  24042. if (index > -1) {
  24043. this._geometries.splice(index, 1);
  24044. //notify the collision coordinator
  24045. if (this.collisionCoordinator) {
  24046. this.collisionCoordinator.onGeometryDeleted(geometry);
  24047. }
  24048. this.onGeometryRemovedObservable.notifyObservers(geometry);
  24049. return true;
  24050. }
  24051. return false;
  24052. };
  24053. Scene.prototype.getGeometries = function () {
  24054. return this._geometries;
  24055. };
  24056. /**
  24057. * Get the first added mesh found of a given ID
  24058. * @param {string} id - the id to search for
  24059. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24060. */
  24061. Scene.prototype.getMeshByID = function (id) {
  24062. for (var index = 0; index < this.meshes.length; index++) {
  24063. if (this.meshes[index].id === id) {
  24064. return this.meshes[index];
  24065. }
  24066. }
  24067. return null;
  24068. };
  24069. Scene.prototype.getMeshesByID = function (id) {
  24070. return this.meshes.filter(function (m) {
  24071. return m.id === id;
  24072. });
  24073. };
  24074. /**
  24075. * Get the first added transform node found of a given ID
  24076. * @param {string} id - the id to search for
  24077. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  24078. */
  24079. Scene.prototype.getTransformNodeByID = function (id) {
  24080. for (var index = 0; index < this.transformNodes.length; index++) {
  24081. if (this.transformNodes[index].id === id) {
  24082. return this.transformNodes[index];
  24083. }
  24084. }
  24085. return null;
  24086. };
  24087. Scene.prototype.getTransformNodesByID = function (id) {
  24088. return this.transformNodes.filter(function (m) {
  24089. return m.id === id;
  24090. });
  24091. };
  24092. /**
  24093. * Get a mesh with its auto-generated unique id
  24094. * @param {number} uniqueId - the unique id to search for
  24095. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24096. */
  24097. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  24098. for (var index = 0; index < this.meshes.length; index++) {
  24099. if (this.meshes[index].uniqueId === uniqueId) {
  24100. return this.meshes[index];
  24101. }
  24102. }
  24103. return null;
  24104. };
  24105. /**
  24106. * Get a the last added mesh found of a given ID
  24107. * @param {string} id - the id to search for
  24108. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24109. */
  24110. Scene.prototype.getLastMeshByID = function (id) {
  24111. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24112. if (this.meshes[index].id === id) {
  24113. return this.meshes[index];
  24114. }
  24115. }
  24116. return null;
  24117. };
  24118. /**
  24119. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  24120. * @param {string} id - the id to search for
  24121. * @return {BABYLON.Node|null} the node found or null if not found at all.
  24122. */
  24123. Scene.prototype.getLastEntryByID = function (id) {
  24124. var index;
  24125. for (index = this.meshes.length - 1; index >= 0; index--) {
  24126. if (this.meshes[index].id === id) {
  24127. return this.meshes[index];
  24128. }
  24129. }
  24130. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24131. if (this.transformNodes[index].id === id) {
  24132. return this.transformNodes[index];
  24133. }
  24134. }
  24135. for (index = this.cameras.length - 1; index >= 0; index--) {
  24136. if (this.cameras[index].id === id) {
  24137. return this.cameras[index];
  24138. }
  24139. }
  24140. for (index = this.lights.length - 1; index >= 0; index--) {
  24141. if (this.lights[index].id === id) {
  24142. return this.lights[index];
  24143. }
  24144. }
  24145. return null;
  24146. };
  24147. Scene.prototype.getNodeByID = function (id) {
  24148. var mesh = this.getMeshByID(id);
  24149. if (mesh) {
  24150. return mesh;
  24151. }
  24152. var light = this.getLightByID(id);
  24153. if (light) {
  24154. return light;
  24155. }
  24156. var camera = this.getCameraByID(id);
  24157. if (camera) {
  24158. return camera;
  24159. }
  24160. var bone = this.getBoneByID(id);
  24161. return bone;
  24162. };
  24163. Scene.prototype.getNodeByName = function (name) {
  24164. var mesh = this.getMeshByName(name);
  24165. if (mesh) {
  24166. return mesh;
  24167. }
  24168. var light = this.getLightByName(name);
  24169. if (light) {
  24170. return light;
  24171. }
  24172. var camera = this.getCameraByName(name);
  24173. if (camera) {
  24174. return camera;
  24175. }
  24176. var bone = this.getBoneByName(name);
  24177. return bone;
  24178. };
  24179. Scene.prototype.getMeshByName = function (name) {
  24180. for (var index = 0; index < this.meshes.length; index++) {
  24181. if (this.meshes[index].name === name) {
  24182. return this.meshes[index];
  24183. }
  24184. }
  24185. return null;
  24186. };
  24187. Scene.prototype.getTransformNodeByName = function (name) {
  24188. for (var index = 0; index < this.transformNodes.length; index++) {
  24189. if (this.transformNodes[index].name === name) {
  24190. return this.transformNodes[index];
  24191. }
  24192. }
  24193. return null;
  24194. };
  24195. Scene.prototype.getSoundByName = function (name) {
  24196. var index;
  24197. if (BABYLON.AudioEngine) {
  24198. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24199. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24200. return this.mainSoundTrack.soundCollection[index];
  24201. }
  24202. }
  24203. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24204. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24205. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24206. return this.soundTracks[sdIndex].soundCollection[index];
  24207. }
  24208. }
  24209. }
  24210. }
  24211. return null;
  24212. };
  24213. Scene.prototype.getLastSkeletonByID = function (id) {
  24214. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24215. if (this.skeletons[index].id === id) {
  24216. return this.skeletons[index];
  24217. }
  24218. }
  24219. return null;
  24220. };
  24221. Scene.prototype.getSkeletonById = function (id) {
  24222. for (var index = 0; index < this.skeletons.length; index++) {
  24223. if (this.skeletons[index].id === id) {
  24224. return this.skeletons[index];
  24225. }
  24226. }
  24227. return null;
  24228. };
  24229. Scene.prototype.getSkeletonByName = function (name) {
  24230. for (var index = 0; index < this.skeletons.length; index++) {
  24231. if (this.skeletons[index].name === name) {
  24232. return this.skeletons[index];
  24233. }
  24234. }
  24235. return null;
  24236. };
  24237. Scene.prototype.getMorphTargetManagerById = function (id) {
  24238. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24239. if (this.morphTargetManagers[index].uniqueId === id) {
  24240. return this.morphTargetManagers[index];
  24241. }
  24242. }
  24243. return null;
  24244. };
  24245. Scene.prototype.isActiveMesh = function (mesh) {
  24246. return (this._activeMeshes.indexOf(mesh) !== -1);
  24247. };
  24248. /**
  24249. * Return a the first highlight layer of the scene with a given name.
  24250. * @param name The name of the highlight layer to look for.
  24251. * @return The highlight layer if found otherwise null.
  24252. */
  24253. Scene.prototype.getHighlightLayerByName = function (name) {
  24254. for (var index = 0; index < this.effectLayers.length; index++) {
  24255. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24256. return this.effectLayers[index];
  24257. }
  24258. }
  24259. return null;
  24260. };
  24261. /**
  24262. * Return a the first highlight layer of the scene with a given name.
  24263. * @param name The name of the highlight layer to look for.
  24264. * @return The highlight layer if found otherwise null.
  24265. */
  24266. Scene.prototype.getGlowLayerByName = function (name) {
  24267. for (var index = 0; index < this.effectLayers.length; index++) {
  24268. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24269. return this.effectLayers[index];
  24270. }
  24271. }
  24272. return null;
  24273. };
  24274. Object.defineProperty(Scene.prototype, "uid", {
  24275. /**
  24276. * Return a unique id as a string which can serve as an identifier for the scene
  24277. */
  24278. get: function () {
  24279. if (!this._uid) {
  24280. this._uid = BABYLON.Tools.RandomId();
  24281. }
  24282. return this._uid;
  24283. },
  24284. enumerable: true,
  24285. configurable: true
  24286. });
  24287. /**
  24288. * Add an externaly attached data from its key.
  24289. * This method call will fail and return false, if such key already exists.
  24290. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24291. * @param key the unique key that identifies the data
  24292. * @param data the data object to associate to the key for this Engine instance
  24293. * @return true if no such key were already present and the data was added successfully, false otherwise
  24294. */
  24295. Scene.prototype.addExternalData = function (key, data) {
  24296. if (!this._externalData) {
  24297. this._externalData = new BABYLON.StringDictionary();
  24298. }
  24299. return this._externalData.add(key, data);
  24300. };
  24301. /**
  24302. * Get an externaly attached data from its key
  24303. * @param key the unique key that identifies the data
  24304. * @return the associated data, if present (can be null), or undefined if not present
  24305. */
  24306. Scene.prototype.getExternalData = function (key) {
  24307. if (!this._externalData) {
  24308. return null;
  24309. }
  24310. return this._externalData.get(key);
  24311. };
  24312. /**
  24313. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24314. * @param key the unique key that identifies the data
  24315. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24316. * @return the associated data, can be null if the factory returned null.
  24317. */
  24318. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24319. if (!this._externalData) {
  24320. this._externalData = new BABYLON.StringDictionary();
  24321. }
  24322. return this._externalData.getOrAddWithFactory(key, factory);
  24323. };
  24324. /**
  24325. * Remove an externaly attached data from the Engine instance
  24326. * @param key the unique key that identifies the data
  24327. * @return true if the data was successfully removed, false if it doesn't exist
  24328. */
  24329. Scene.prototype.removeExternalData = function (key) {
  24330. return this._externalData.remove(key);
  24331. };
  24332. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24333. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24334. if (mesh.showSubMeshesBoundingBox) {
  24335. var boundingInfo = subMesh.getBoundingInfo();
  24336. if (boundingInfo !== null && boundingInfo !== undefined) {
  24337. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24338. }
  24339. }
  24340. var material = subMesh.getMaterial();
  24341. if (material !== null && material !== undefined) {
  24342. // Render targets
  24343. if (material.getRenderTargetTextures !== undefined) {
  24344. if (this._processedMaterials.indexOf(material) === -1) {
  24345. this._processedMaterials.push(material);
  24346. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24347. }
  24348. }
  24349. // Dispatch
  24350. this._activeIndices.addCount(subMesh.indexCount, false);
  24351. this._renderingManager.dispatch(subMesh, mesh, material);
  24352. }
  24353. }
  24354. };
  24355. /**
  24356. * Clear the processed materials smart array preventing retention point in material dispose.
  24357. */
  24358. Scene.prototype.freeProcessedMaterials = function () {
  24359. this._processedMaterials.dispose();
  24360. };
  24361. /**
  24362. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24363. */
  24364. Scene.prototype.freeActiveMeshes = function () {
  24365. this._activeMeshes.dispose();
  24366. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24367. this.activeCamera._activeMeshes.dispose();
  24368. }
  24369. if (this.activeCameras) {
  24370. for (var i = 0; i < this.activeCameras.length; i++) {
  24371. var activeCamera = this.activeCameras[i];
  24372. if (activeCamera && activeCamera._activeMeshes) {
  24373. activeCamera._activeMeshes.dispose();
  24374. }
  24375. }
  24376. }
  24377. };
  24378. /**
  24379. * Clear the info related to rendering groups preventing retention points during dispose.
  24380. */
  24381. Scene.prototype.freeRenderingGroups = function () {
  24382. if (this._renderingManager) {
  24383. this._renderingManager.freeRenderingGroups();
  24384. }
  24385. if (this.textures) {
  24386. for (var i = 0; i < this.textures.length; i++) {
  24387. var texture = this.textures[i];
  24388. if (texture && texture.renderList) {
  24389. texture.freeRenderingGroups();
  24390. }
  24391. }
  24392. }
  24393. };
  24394. Scene.prototype._isInIntermediateRendering = function () {
  24395. return this._intermediateRendering;
  24396. };
  24397. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24398. this._activeMeshCandidateProvider = provider;
  24399. };
  24400. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24401. return this._activeMeshCandidateProvider;
  24402. };
  24403. /**
  24404. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24405. */
  24406. Scene.prototype.freezeActiveMeshes = function () {
  24407. if (!this.activeCamera) {
  24408. return this;
  24409. }
  24410. if (!this._frustumPlanes) {
  24411. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24412. }
  24413. this._evaluateActiveMeshes();
  24414. this._activeMeshesFrozen = true;
  24415. return this;
  24416. };
  24417. /**
  24418. * Use this function to restart evaluating active meshes on every frame
  24419. */
  24420. Scene.prototype.unfreezeActiveMeshes = function () {
  24421. this._activeMeshesFrozen = false;
  24422. return this;
  24423. };
  24424. Scene.prototype._evaluateActiveMeshes = function () {
  24425. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24426. return;
  24427. }
  24428. if (!this.activeCamera) {
  24429. return;
  24430. }
  24431. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24432. this.activeCamera._activeMeshes.reset();
  24433. this._activeMeshes.reset();
  24434. this._renderingManager.reset();
  24435. this._processedMaterials.reset();
  24436. this._activeParticleSystems.reset();
  24437. this._activeSkeletons.reset();
  24438. this._softwareSkinnedMeshes.reset();
  24439. if (this._boundingBoxRenderer) {
  24440. this._boundingBoxRenderer.reset();
  24441. }
  24442. // Meshes
  24443. var meshes;
  24444. var len;
  24445. var checkIsEnabled = true;
  24446. // Determine mesh candidates
  24447. if (this._activeMeshCandidateProvider !== undefined) {
  24448. // Use _activeMeshCandidateProvider
  24449. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24450. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24451. if (meshes !== undefined) {
  24452. len = meshes.length;
  24453. }
  24454. else {
  24455. len = 0;
  24456. }
  24457. }
  24458. else if (this._selectionOctree !== undefined) {
  24459. // Octree
  24460. var selection = this._selectionOctree.select(this._frustumPlanes);
  24461. meshes = selection.data;
  24462. len = selection.length;
  24463. }
  24464. else {
  24465. // Full scene traversal
  24466. len = this.meshes.length;
  24467. meshes = this.meshes;
  24468. }
  24469. // Check each mesh
  24470. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24471. mesh = meshes[meshIndex];
  24472. if (mesh.isBlocked) {
  24473. continue;
  24474. }
  24475. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24476. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24477. continue;
  24478. }
  24479. mesh.computeWorldMatrix();
  24480. // Intersections
  24481. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24482. this._meshesForIntersections.pushNoDuplicate(mesh);
  24483. }
  24484. // Switch to current LOD
  24485. meshLOD = mesh.getLOD(this.activeCamera);
  24486. if (meshLOD === undefined || meshLOD === null) {
  24487. continue;
  24488. }
  24489. mesh._preActivate();
  24490. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24491. this._activeMeshes.push(mesh);
  24492. this.activeCamera._activeMeshes.push(mesh);
  24493. mesh._activate(this._renderId);
  24494. if (meshLOD !== mesh) {
  24495. meshLOD._activate(this._renderId);
  24496. }
  24497. this._activeMesh(mesh, meshLOD);
  24498. }
  24499. }
  24500. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24501. // Particle systems
  24502. if (this.particlesEnabled) {
  24503. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24504. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24505. var particleSystem = this.particleSystems[particleIndex];
  24506. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24507. continue;
  24508. }
  24509. var emitter = particleSystem.emitter;
  24510. if (!emitter.position || emitter.isEnabled()) {
  24511. this._activeParticleSystems.push(particleSystem);
  24512. particleSystem.animate();
  24513. this._renderingManager.dispatchParticles(particleSystem);
  24514. }
  24515. }
  24516. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24517. }
  24518. };
  24519. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24520. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24521. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24522. mesh.skeleton.prepare();
  24523. }
  24524. if (!mesh.computeBonesUsingShaders) {
  24525. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24526. }
  24527. }
  24528. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24529. var boundingInfo = sourceMesh.getBoundingInfo();
  24530. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24531. }
  24532. if (mesh !== undefined && mesh !== null
  24533. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24534. // Submeshes Octrees
  24535. var len;
  24536. var subMeshes;
  24537. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24538. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24539. len = intersections.length;
  24540. subMeshes = intersections.data;
  24541. }
  24542. else {
  24543. subMeshes = mesh.subMeshes;
  24544. len = subMeshes.length;
  24545. }
  24546. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24547. subMesh = subMeshes[subIndex];
  24548. this._evaluateSubMesh(subMesh, mesh);
  24549. }
  24550. }
  24551. };
  24552. Scene.prototype.updateTransformMatrix = function (force) {
  24553. if (!this.activeCamera) {
  24554. return;
  24555. }
  24556. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24557. };
  24558. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24559. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24560. };
  24561. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24562. if (camera && camera._skipRendering) {
  24563. return;
  24564. }
  24565. var engine = this._engine;
  24566. this.activeCamera = camera;
  24567. if (!this.activeCamera)
  24568. throw new Error("Active camera not set");
  24569. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24570. // Viewport
  24571. engine.setViewport(this.activeCamera.viewport);
  24572. // Camera
  24573. this.resetCachedMaterial();
  24574. this._renderId++;
  24575. this.updateTransformMatrix();
  24576. if (camera._alternateCamera) {
  24577. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24578. this._alternateRendering = true;
  24579. }
  24580. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24581. // Meshes
  24582. this._evaluateActiveMeshes();
  24583. // Software skinning
  24584. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24585. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24586. mesh.applySkeleton(mesh.skeleton);
  24587. }
  24588. // Render targets
  24589. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24590. var needsRestoreFrameBuffer = false;
  24591. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24592. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24593. }
  24594. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24595. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24596. }
  24597. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24598. this._intermediateRendering = true;
  24599. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24600. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24601. var renderTarget = this._renderTargets.data[renderIndex];
  24602. if (renderTarget._shouldRender()) {
  24603. this._renderId++;
  24604. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24605. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24606. }
  24607. }
  24608. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24609. this._intermediateRendering = false;
  24610. this._renderId++;
  24611. needsRestoreFrameBuffer = true; // Restore back buffer
  24612. }
  24613. // Render EffecttLayer Texture
  24614. var stencilState = this._engine.getStencilBuffer();
  24615. var renderEffects = false;
  24616. var needStencil = false;
  24617. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24618. this._intermediateRendering = true;
  24619. for (var i = 0; i < this.effectLayers.length; i++) {
  24620. var effectLayer = this.effectLayers[i];
  24621. if (effectLayer.shouldRender() &&
  24622. (!effectLayer.camera ||
  24623. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24624. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24625. renderEffects = true;
  24626. needStencil = needStencil || effectLayer.needStencil();
  24627. var renderTarget = effectLayer._mainTexture;
  24628. if (renderTarget._shouldRender()) {
  24629. this._renderId++;
  24630. renderTarget.render(false, false);
  24631. needsRestoreFrameBuffer = true;
  24632. }
  24633. }
  24634. }
  24635. this._intermediateRendering = false;
  24636. this._renderId++;
  24637. }
  24638. if (needsRestoreFrameBuffer) {
  24639. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24640. }
  24641. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24642. // Prepare Frame
  24643. this.postProcessManager._prepareFrame();
  24644. // Backgrounds
  24645. var layerIndex;
  24646. var layer;
  24647. if (this.layers.length) {
  24648. engine.setDepthBuffer(false);
  24649. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24650. layer = this.layers[layerIndex];
  24651. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24652. layer.render();
  24653. }
  24654. }
  24655. engine.setDepthBuffer(true);
  24656. }
  24657. // Activate effect Layer stencil
  24658. if (needStencil) {
  24659. this._engine.setStencilBuffer(true);
  24660. }
  24661. // Render
  24662. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24663. this._renderingManager.render(null, null, true, true);
  24664. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24665. // Restore effect Layer stencil
  24666. if (needStencil) {
  24667. this._engine.setStencilBuffer(stencilState);
  24668. }
  24669. // Bounding boxes
  24670. if (this._boundingBoxRenderer) {
  24671. this._boundingBoxRenderer.render();
  24672. }
  24673. // Lens flares
  24674. if (this.lensFlaresEnabled) {
  24675. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24676. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24677. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24678. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24679. lensFlareSystem.render();
  24680. }
  24681. }
  24682. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24683. }
  24684. // Foregrounds
  24685. if (this.layers.length) {
  24686. engine.setDepthBuffer(false);
  24687. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24688. layer = this.layers[layerIndex];
  24689. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24690. layer.render();
  24691. }
  24692. }
  24693. engine.setDepthBuffer(true);
  24694. }
  24695. // Effect Layer
  24696. if (renderEffects) {
  24697. engine.setDepthBuffer(false);
  24698. for (var i = 0; i < this.effectLayers.length; i++) {
  24699. if (this.effectLayers[i].shouldRender()) {
  24700. this.effectLayers[i].render();
  24701. }
  24702. }
  24703. engine.setDepthBuffer(true);
  24704. }
  24705. // Finalize frame
  24706. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24707. // Reset some special arrays
  24708. this._renderTargets.reset();
  24709. this._alternateRendering = false;
  24710. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24711. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24712. };
  24713. Scene.prototype._processSubCameras = function (camera) {
  24714. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24715. this._renderForCamera(camera);
  24716. return;
  24717. }
  24718. // rig cameras
  24719. for (var index = 0; index < camera._rigCameras.length; index++) {
  24720. this._renderForCamera(camera._rigCameras[index], camera);
  24721. }
  24722. this.activeCamera = camera;
  24723. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24724. };
  24725. Scene.prototype._checkIntersections = function () {
  24726. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24727. var sourceMesh = this._meshesForIntersections.data[index];
  24728. if (!sourceMesh.actionManager) {
  24729. continue;
  24730. }
  24731. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24732. var action = sourceMesh.actionManager.actions[actionIndex];
  24733. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24734. var parameters = action.getTriggerParameter();
  24735. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24736. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24737. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24738. if (areIntersecting && currentIntersectionInProgress === -1) {
  24739. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24740. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24741. sourceMesh._intersectionsInProgress.push(otherMesh);
  24742. }
  24743. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24744. sourceMesh._intersectionsInProgress.push(otherMesh);
  24745. }
  24746. }
  24747. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24748. //They intersected, and now they don't.
  24749. //is this trigger an exit trigger? execute an event.
  24750. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24751. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24752. }
  24753. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24754. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24755. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24756. }
  24757. }
  24758. }
  24759. }
  24760. }
  24761. };
  24762. Scene.prototype.render = function () {
  24763. if (this.isDisposed) {
  24764. return;
  24765. }
  24766. this._activeParticles.fetchNewFrame();
  24767. this._totalVertices.fetchNewFrame();
  24768. this._activeIndices.fetchNewFrame();
  24769. this._activeBones.fetchNewFrame();
  24770. this._meshesForIntersections.reset();
  24771. this.resetCachedMaterial();
  24772. this.onBeforeAnimationsObservable.notifyObservers(this);
  24773. // Actions
  24774. if (this.actionManager) {
  24775. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24776. }
  24777. //Simplification Queue
  24778. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24779. this.simplificationQueue.executeNext();
  24780. }
  24781. if (this._engine.isDeterministicLockStep()) {
  24782. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24783. var defaultFPS = (60.0 / 1000.0);
  24784. var defaultFrameTime = 1000 / 60; // frame time in MS
  24785. if (this._physicsEngine) {
  24786. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24787. }
  24788. var stepsTaken = 0;
  24789. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24790. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24791. internalSteps = Math.min(internalSteps, maxSubSteps);
  24792. do {
  24793. this.onBeforeStepObservable.notifyObservers(this);
  24794. // Animations
  24795. this._animationRatio = defaultFrameTime * defaultFPS;
  24796. this._animate();
  24797. this.onAfterAnimationsObservable.notifyObservers(this);
  24798. // Physics
  24799. if (this._physicsEngine) {
  24800. this.onBeforePhysicsObservable.notifyObservers(this);
  24801. this._physicsEngine._step(defaultFrameTime / 1000);
  24802. this.onAfterPhysicsObservable.notifyObservers(this);
  24803. }
  24804. this.onAfterStepObservable.notifyObservers(this);
  24805. this._currentStepId++;
  24806. stepsTaken++;
  24807. deltaTime -= defaultFrameTime;
  24808. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24809. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24810. }
  24811. else {
  24812. // Animations
  24813. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24814. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24815. this._animate();
  24816. this.onAfterAnimationsObservable.notifyObservers(this);
  24817. // Physics
  24818. if (this._physicsEngine) {
  24819. this.onBeforePhysicsObservable.notifyObservers(this);
  24820. this._physicsEngine._step(deltaTime / 1000.0);
  24821. this.onAfterPhysicsObservable.notifyObservers(this);
  24822. }
  24823. }
  24824. // update gamepad manager
  24825. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24826. this._gamepadManager._checkGamepadsStatus();
  24827. }
  24828. // Update Cameras
  24829. if (this.activeCameras.length > 0) {
  24830. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24831. var camera = this.activeCameras[cameraIndex];
  24832. camera.update();
  24833. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24834. // rig cameras
  24835. for (var index = 0; index < camera._rigCameras.length; index++) {
  24836. camera._rigCameras[index].update();
  24837. }
  24838. }
  24839. }
  24840. }
  24841. else if (this.activeCamera) {
  24842. this.activeCamera.update();
  24843. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24844. // rig cameras
  24845. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24846. this.activeCamera._rigCameras[index].update();
  24847. }
  24848. }
  24849. }
  24850. // Before render
  24851. this.onBeforeRenderObservable.notifyObservers(this);
  24852. // Customs render targets
  24853. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24854. var engine = this.getEngine();
  24855. var currentActiveCamera = this.activeCamera;
  24856. if (this.renderTargetsEnabled) {
  24857. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24858. this._intermediateRendering = true;
  24859. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24860. var renderTarget = this.customRenderTargets[customIndex];
  24861. if (renderTarget._shouldRender()) {
  24862. this._renderId++;
  24863. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24864. if (!this.activeCamera)
  24865. throw new Error("Active camera not set");
  24866. // Viewport
  24867. engine.setViewport(this.activeCamera.viewport);
  24868. // Camera
  24869. this.updateTransformMatrix();
  24870. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24871. }
  24872. }
  24873. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24874. this._intermediateRendering = false;
  24875. this._renderId++;
  24876. }
  24877. // Restore back buffer
  24878. if (this.customRenderTargets.length > 0) {
  24879. engine.restoreDefaultFramebuffer();
  24880. }
  24881. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24882. this.activeCamera = currentActiveCamera;
  24883. // Procedural textures
  24884. if (this.proceduralTexturesEnabled) {
  24885. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24886. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24887. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24888. if (proceduralTexture._shouldRender()) {
  24889. proceduralTexture.render();
  24890. }
  24891. }
  24892. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24893. }
  24894. // Clear
  24895. if (this.autoClearDepthAndStencil || this.autoClear) {
  24896. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24897. }
  24898. // Shadows
  24899. if (this.shadowsEnabled) {
  24900. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24901. var light = this.lights[lightIndex];
  24902. var shadowGenerator = light.getShadowGenerator();
  24903. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24904. var shadowMap = (shadowGenerator.getShadowMap());
  24905. if (this.textures.indexOf(shadowMap) !== -1) {
  24906. this._renderTargets.push(shadowMap);
  24907. }
  24908. }
  24909. }
  24910. }
  24911. // Depth renderer
  24912. for (var key in this._depthRenderer) {
  24913. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24914. }
  24915. // Geometry renderer
  24916. if (this._geometryBufferRenderer) {
  24917. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24918. }
  24919. // RenderPipeline
  24920. if (this._postProcessRenderPipelineManager) {
  24921. this._postProcessRenderPipelineManager.update();
  24922. }
  24923. // Multi-cameras?
  24924. if (this.activeCameras.length > 0) {
  24925. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24926. if (cameraIndex > 0) {
  24927. this._engine.clear(null, false, true, true);
  24928. }
  24929. this._processSubCameras(this.activeCameras[cameraIndex]);
  24930. }
  24931. }
  24932. else {
  24933. if (!this.activeCamera) {
  24934. throw new Error("No camera defined");
  24935. }
  24936. this._processSubCameras(this.activeCamera);
  24937. }
  24938. // Intersection checks
  24939. this._checkIntersections();
  24940. // Update the audio listener attached to the camera
  24941. if (BABYLON.AudioEngine) {
  24942. this._updateAudioParameters();
  24943. }
  24944. // After render
  24945. if (this.afterRender) {
  24946. this.afterRender();
  24947. }
  24948. this.onAfterRenderObservable.notifyObservers(this);
  24949. // Cleaning
  24950. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24951. var data = this._toBeDisposed.data[index];
  24952. if (data) {
  24953. data.dispose();
  24954. }
  24955. this._toBeDisposed[index] = null;
  24956. }
  24957. this._toBeDisposed.reset();
  24958. if (this.dumpNextRenderTargets) {
  24959. this.dumpNextRenderTargets = false;
  24960. }
  24961. this._activeBones.addCount(0, true);
  24962. this._activeIndices.addCount(0, true);
  24963. this._activeParticles.addCount(0, true);
  24964. };
  24965. Scene.prototype._updateAudioParameters = function () {
  24966. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24967. return;
  24968. }
  24969. var listeningCamera;
  24970. var audioEngine = BABYLON.Engine.audioEngine;
  24971. if (this.activeCameras.length > 0) {
  24972. listeningCamera = this.activeCameras[0];
  24973. }
  24974. else {
  24975. listeningCamera = this.activeCamera;
  24976. }
  24977. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24978. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24979. // for VR cameras
  24980. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24981. listeningCamera = listeningCamera.rigCameras[0];
  24982. }
  24983. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24984. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24985. cameraDirection.normalize();
  24986. // To avoid some errors on GearVR
  24987. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24988. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24989. }
  24990. var i;
  24991. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24992. var sound = this.mainSoundTrack.soundCollection[i];
  24993. if (sound.useCustomAttenuation) {
  24994. sound.updateDistanceFromListener();
  24995. }
  24996. }
  24997. for (i = 0; i < this.soundTracks.length; i++) {
  24998. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24999. sound = this.soundTracks[i].soundCollection[j];
  25000. if (sound.useCustomAttenuation) {
  25001. sound.updateDistanceFromListener();
  25002. }
  25003. }
  25004. }
  25005. }
  25006. };
  25007. Object.defineProperty(Scene.prototype, "audioEnabled", {
  25008. // Audio
  25009. get: function () {
  25010. return this._audioEnabled;
  25011. },
  25012. set: function (value) {
  25013. this._audioEnabled = value;
  25014. if (BABYLON.AudioEngine) {
  25015. if (this._audioEnabled) {
  25016. this._enableAudio();
  25017. }
  25018. else {
  25019. this._disableAudio();
  25020. }
  25021. }
  25022. },
  25023. enumerable: true,
  25024. configurable: true
  25025. });
  25026. Scene.prototype._disableAudio = function () {
  25027. var i;
  25028. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25029. this.mainSoundTrack.soundCollection[i].pause();
  25030. }
  25031. for (i = 0; i < this.soundTracks.length; i++) {
  25032. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25033. this.soundTracks[i].soundCollection[j].pause();
  25034. }
  25035. }
  25036. };
  25037. Scene.prototype._enableAudio = function () {
  25038. var i;
  25039. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25040. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  25041. this.mainSoundTrack.soundCollection[i].play();
  25042. }
  25043. }
  25044. for (i = 0; i < this.soundTracks.length; i++) {
  25045. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25046. if (this.soundTracks[i].soundCollection[j].isPaused) {
  25047. this.soundTracks[i].soundCollection[j].play();
  25048. }
  25049. }
  25050. }
  25051. };
  25052. Object.defineProperty(Scene.prototype, "headphone", {
  25053. get: function () {
  25054. return this._headphone;
  25055. },
  25056. set: function (value) {
  25057. this._headphone = value;
  25058. if (BABYLON.AudioEngine) {
  25059. if (this._headphone) {
  25060. this._switchAudioModeForHeadphones();
  25061. }
  25062. else {
  25063. this._switchAudioModeForNormalSpeakers();
  25064. }
  25065. }
  25066. },
  25067. enumerable: true,
  25068. configurable: true
  25069. });
  25070. Scene.prototype._switchAudioModeForHeadphones = function () {
  25071. this.mainSoundTrack.switchPanningModelToHRTF();
  25072. for (var i = 0; i < this.soundTracks.length; i++) {
  25073. this.soundTracks[i].switchPanningModelToHRTF();
  25074. }
  25075. };
  25076. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  25077. this.mainSoundTrack.switchPanningModelToEqualPower();
  25078. for (var i = 0; i < this.soundTracks.length; i++) {
  25079. this.soundTracks[i].switchPanningModelToEqualPower();
  25080. }
  25081. };
  25082. /**
  25083. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  25084. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  25085. * @returns the created depth renderer
  25086. */
  25087. Scene.prototype.enableDepthRenderer = function (camera) {
  25088. camera = camera || this.activeCamera;
  25089. if (!camera) {
  25090. throw "No camera available to enable depth renderer";
  25091. }
  25092. if (!this._depthRenderer[camera.id]) {
  25093. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  25094. }
  25095. return this._depthRenderer[camera.id];
  25096. };
  25097. /**
  25098. * Disables a depth renderer for a given camera
  25099. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  25100. */
  25101. Scene.prototype.disableDepthRenderer = function (camera) {
  25102. camera = camera || this.activeCamera;
  25103. if (!camera || !this._depthRenderer[camera.id]) {
  25104. return;
  25105. }
  25106. this._depthRenderer[camera.id].dispose();
  25107. delete this._depthRenderer[camera.id];
  25108. };
  25109. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25110. if (ratio === void 0) { ratio = 1; }
  25111. if (this._geometryBufferRenderer) {
  25112. return this._geometryBufferRenderer;
  25113. }
  25114. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25115. if (!this._geometryBufferRenderer.isSupported) {
  25116. this._geometryBufferRenderer = null;
  25117. }
  25118. return this._geometryBufferRenderer;
  25119. };
  25120. Scene.prototype.disableGeometryBufferRenderer = function () {
  25121. if (!this._geometryBufferRenderer) {
  25122. return;
  25123. }
  25124. this._geometryBufferRenderer.dispose();
  25125. this._geometryBufferRenderer = null;
  25126. };
  25127. Scene.prototype.freezeMaterials = function () {
  25128. for (var i = 0; i < this.materials.length; i++) {
  25129. this.materials[i].freeze();
  25130. }
  25131. };
  25132. Scene.prototype.unfreezeMaterials = function () {
  25133. for (var i = 0; i < this.materials.length; i++) {
  25134. this.materials[i].unfreeze();
  25135. }
  25136. };
  25137. Scene.prototype.dispose = function () {
  25138. this.beforeRender = null;
  25139. this.afterRender = null;
  25140. this.skeletons = [];
  25141. this.morphTargetManagers = [];
  25142. this.importedMeshesFiles = new Array();
  25143. this.stopAllAnimations();
  25144. this.resetCachedMaterial();
  25145. for (var key in this._depthRenderer) {
  25146. this._depthRenderer[key].dispose();
  25147. }
  25148. if (this._gamepadManager) {
  25149. this._gamepadManager.dispose();
  25150. this._gamepadManager = null;
  25151. }
  25152. // Smart arrays
  25153. if (this.activeCamera) {
  25154. this.activeCamera._activeMeshes.dispose();
  25155. this.activeCamera = null;
  25156. }
  25157. this._activeMeshes.dispose();
  25158. this._renderingManager.dispose();
  25159. this._processedMaterials.dispose();
  25160. this._activeParticleSystems.dispose();
  25161. this._activeSkeletons.dispose();
  25162. this._softwareSkinnedMeshes.dispose();
  25163. this._renderTargets.dispose();
  25164. this._registeredForLateAnimationBindings.dispose();
  25165. if (this._boundingBoxRenderer) {
  25166. this._boundingBoxRenderer.dispose();
  25167. }
  25168. this._meshesForIntersections.dispose();
  25169. this._toBeDisposed.dispose();
  25170. // Abort active requests
  25171. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25172. var request = _a[_i];
  25173. request.abort();
  25174. }
  25175. // Debug layer
  25176. if (this._debugLayer) {
  25177. this._debugLayer.hide();
  25178. }
  25179. // Events
  25180. this.onDisposeObservable.notifyObservers(this);
  25181. this.onDisposeObservable.clear();
  25182. this.onBeforeRenderObservable.clear();
  25183. this.onAfterRenderObservable.clear();
  25184. this.OnBeforeRenderTargetsRenderObservable.clear();
  25185. this.OnAfterRenderTargetsRenderObservable.clear();
  25186. this.onAfterStepObservable.clear();
  25187. this.onBeforeStepObservable.clear();
  25188. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25189. this.onAfterActiveMeshesEvaluationObservable.clear();
  25190. this.onBeforeParticlesRenderingObservable.clear();
  25191. this.onAfterParticlesRenderingObservable.clear();
  25192. this.onBeforeSpritesRenderingObservable.clear();
  25193. this.onAfterSpritesRenderingObservable.clear();
  25194. this.onBeforeDrawPhaseObservable.clear();
  25195. this.onAfterDrawPhaseObservable.clear();
  25196. this.onBeforePhysicsObservable.clear();
  25197. this.onAfterPhysicsObservable.clear();
  25198. this.onBeforeAnimationsObservable.clear();
  25199. this.onAfterAnimationsObservable.clear();
  25200. this.onDataLoadedObservable.clear();
  25201. this.detachControl();
  25202. // Release sounds & sounds tracks
  25203. if (BABYLON.AudioEngine) {
  25204. this.disposeSounds();
  25205. }
  25206. // VR Helper
  25207. if (this.VRHelper) {
  25208. this.VRHelper.dispose();
  25209. }
  25210. // Detach cameras
  25211. var canvas = this._engine.getRenderingCanvas();
  25212. if (canvas) {
  25213. var index;
  25214. for (index = 0; index < this.cameras.length; index++) {
  25215. this.cameras[index].detachControl(canvas);
  25216. }
  25217. }
  25218. // Release animation groups
  25219. while (this.animationGroups.length) {
  25220. this.animationGroups[0].dispose();
  25221. }
  25222. // Release lights
  25223. while (this.lights.length) {
  25224. this.lights[0].dispose();
  25225. }
  25226. // Release meshes
  25227. while (this.meshes.length) {
  25228. this.meshes[0].dispose(true);
  25229. }
  25230. while (this.transformNodes.length) {
  25231. this.removeTransformNode(this.transformNodes[0]);
  25232. }
  25233. // Release cameras
  25234. while (this.cameras.length) {
  25235. this.cameras[0].dispose();
  25236. }
  25237. // Release materials
  25238. if (this.defaultMaterial) {
  25239. this.defaultMaterial.dispose();
  25240. }
  25241. while (this.multiMaterials.length) {
  25242. this.multiMaterials[0].dispose();
  25243. }
  25244. while (this.materials.length) {
  25245. this.materials[0].dispose();
  25246. }
  25247. // Release particles
  25248. while (this.particleSystems.length) {
  25249. this.particleSystems[0].dispose();
  25250. }
  25251. // Release sprites
  25252. while (this.spriteManagers.length) {
  25253. this.spriteManagers[0].dispose();
  25254. }
  25255. // Release postProcesses
  25256. while (this.postProcesses.length) {
  25257. this.postProcesses[0].dispose();
  25258. }
  25259. // Release layers
  25260. while (this.layers.length) {
  25261. this.layers[0].dispose();
  25262. }
  25263. while (this.effectLayers.length) {
  25264. this.effectLayers[0].dispose();
  25265. }
  25266. // Release textures
  25267. while (this.textures.length) {
  25268. this.textures[0].dispose();
  25269. }
  25270. // Release UBO
  25271. this._sceneUbo.dispose();
  25272. if (this._alternateSceneUbo) {
  25273. this._alternateSceneUbo.dispose();
  25274. }
  25275. // Post-processes
  25276. this.postProcessManager.dispose();
  25277. if (this._postProcessRenderPipelineManager) {
  25278. this._postProcessRenderPipelineManager.dispose();
  25279. }
  25280. // Physics
  25281. if (this._physicsEngine) {
  25282. this.disablePhysicsEngine();
  25283. }
  25284. // Remove from engine
  25285. index = this._engine.scenes.indexOf(this);
  25286. if (index > -1) {
  25287. this._engine.scenes.splice(index, 1);
  25288. }
  25289. this._engine.wipeCaches(true);
  25290. this._isDisposed = true;
  25291. };
  25292. Object.defineProperty(Scene.prototype, "isDisposed", {
  25293. get: function () {
  25294. return this._isDisposed;
  25295. },
  25296. enumerable: true,
  25297. configurable: true
  25298. });
  25299. // Release sounds & sounds tracks
  25300. Scene.prototype.disposeSounds = function () {
  25301. if (!this._mainSoundTrack) {
  25302. return;
  25303. }
  25304. this.mainSoundTrack.dispose();
  25305. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25306. this.soundTracks[scIndex].dispose();
  25307. }
  25308. };
  25309. // Octrees
  25310. /**
  25311. * Get the world extend vectors with an optional filter
  25312. *
  25313. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25314. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25315. */
  25316. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25317. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25318. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25319. filterPredicate = filterPredicate || (function () { return true; });
  25320. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25321. mesh.computeWorldMatrix(true);
  25322. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25323. return;
  25324. }
  25325. var boundingInfo = mesh.getBoundingInfo();
  25326. var minBox = boundingInfo.boundingBox.minimumWorld;
  25327. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25328. BABYLON.Tools.CheckExtends(minBox, min, max);
  25329. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25330. });
  25331. return {
  25332. min: min,
  25333. max: max
  25334. };
  25335. };
  25336. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25337. if (maxCapacity === void 0) { maxCapacity = 64; }
  25338. if (maxDepth === void 0) { maxDepth = 2; }
  25339. if (!this._selectionOctree) {
  25340. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25341. }
  25342. var worldExtends = this.getWorldExtends();
  25343. // Update octree
  25344. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25345. return this._selectionOctree;
  25346. };
  25347. // Picking
  25348. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25349. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25350. var result = BABYLON.Ray.Zero();
  25351. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25352. return result;
  25353. };
  25354. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25355. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25356. var engine = this._engine;
  25357. if (!camera) {
  25358. if (!this.activeCamera)
  25359. throw new Error("Active camera not set");
  25360. camera = this.activeCamera;
  25361. }
  25362. var cameraViewport = camera.viewport;
  25363. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25364. // Moving coordinates to local viewport world
  25365. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25366. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25367. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25368. return this;
  25369. };
  25370. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25371. var result = BABYLON.Ray.Zero();
  25372. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25373. return result;
  25374. };
  25375. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25376. if (!BABYLON.PickingInfo) {
  25377. return this;
  25378. }
  25379. var engine = this._engine;
  25380. if (!camera) {
  25381. if (!this.activeCamera)
  25382. throw new Error("Active camera not set");
  25383. camera = this.activeCamera;
  25384. }
  25385. var cameraViewport = camera.viewport;
  25386. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25387. var identity = BABYLON.Matrix.Identity();
  25388. // Moving coordinates to local viewport world
  25389. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25390. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25391. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25392. return this;
  25393. };
  25394. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25395. if (!BABYLON.PickingInfo) {
  25396. return null;
  25397. }
  25398. var pickingInfo = null;
  25399. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25400. var mesh = this.meshes[meshIndex];
  25401. if (predicate) {
  25402. if (!predicate(mesh)) {
  25403. continue;
  25404. }
  25405. }
  25406. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25407. continue;
  25408. }
  25409. var world = mesh.getWorldMatrix();
  25410. var ray = rayFunction(world);
  25411. var result = mesh.intersects(ray, fastCheck);
  25412. if (!result || !result.hit)
  25413. continue;
  25414. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25415. continue;
  25416. pickingInfo = result;
  25417. if (fastCheck) {
  25418. break;
  25419. }
  25420. }
  25421. return pickingInfo || new BABYLON.PickingInfo();
  25422. };
  25423. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25424. if (!BABYLON.PickingInfo) {
  25425. return null;
  25426. }
  25427. var pickingInfos = new Array();
  25428. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25429. var mesh = this.meshes[meshIndex];
  25430. if (predicate) {
  25431. if (!predicate(mesh)) {
  25432. continue;
  25433. }
  25434. }
  25435. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25436. continue;
  25437. }
  25438. var world = mesh.getWorldMatrix();
  25439. var ray = rayFunction(world);
  25440. var result = mesh.intersects(ray, false);
  25441. if (!result || !result.hit)
  25442. continue;
  25443. pickingInfos.push(result);
  25444. }
  25445. return pickingInfos;
  25446. };
  25447. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25448. if (!BABYLON.PickingInfo) {
  25449. return null;
  25450. }
  25451. var pickingInfo = null;
  25452. if (!camera) {
  25453. if (!this.activeCamera) {
  25454. return null;
  25455. }
  25456. camera = this.activeCamera;
  25457. }
  25458. if (this.spriteManagers.length > 0) {
  25459. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25460. var spriteManager = this.spriteManagers[spriteIndex];
  25461. if (!spriteManager.isPickable) {
  25462. continue;
  25463. }
  25464. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25465. if (!result || !result.hit)
  25466. continue;
  25467. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25468. continue;
  25469. pickingInfo = result;
  25470. if (fastCheck) {
  25471. break;
  25472. }
  25473. }
  25474. }
  25475. return pickingInfo || new BABYLON.PickingInfo();
  25476. };
  25477. /** Launch a ray to try to pick a mesh in the scene
  25478. * @param x position on screen
  25479. * @param y position on screen
  25480. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  25481. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25482. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25483. */
  25484. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25485. var _this = this;
  25486. if (!BABYLON.PickingInfo) {
  25487. return null;
  25488. }
  25489. return this._internalPick(function (world) {
  25490. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25491. return _this._tempPickingRay;
  25492. }, predicate, fastCheck);
  25493. };
  25494. /** Launch a ray to try to pick a sprite in the scene
  25495. * @param x position on screen
  25496. * @param y position on screen
  25497. * @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
  25498. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25499. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25500. */
  25501. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25502. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25503. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25504. };
  25505. /** Use the given ray to pick a mesh in the scene
  25506. * @param ray The ray to use to pick meshes
  25507. * @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
  25508. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25509. */
  25510. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25511. var _this = this;
  25512. return this._internalPick(function (world) {
  25513. if (!_this._pickWithRayInverseMatrix) {
  25514. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25515. }
  25516. world.invertToRef(_this._pickWithRayInverseMatrix);
  25517. if (!_this._cachedRayForTransform) {
  25518. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25519. }
  25520. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25521. return _this._cachedRayForTransform;
  25522. }, predicate, fastCheck);
  25523. };
  25524. /**
  25525. * Launch a ray to try to pick a mesh in the scene
  25526. * @param x X position on screen
  25527. * @param y Y position on screen
  25528. * @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
  25529. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25530. */
  25531. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25532. var _this = this;
  25533. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25534. };
  25535. /**
  25536. * Launch a ray to try to pick a mesh in the scene
  25537. * @param ray Ray to use
  25538. * @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
  25539. */
  25540. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25541. var _this = this;
  25542. return this._internalMultiPick(function (world) {
  25543. if (!_this._pickWithRayInverseMatrix) {
  25544. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25545. }
  25546. world.invertToRef(_this._pickWithRayInverseMatrix);
  25547. if (!_this._cachedRayForTransform) {
  25548. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25549. }
  25550. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25551. return _this._cachedRayForTransform;
  25552. }, predicate);
  25553. };
  25554. Scene.prototype.setPointerOverMesh = function (mesh) {
  25555. if (this._pointerOverMesh === mesh) {
  25556. return;
  25557. }
  25558. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25559. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25560. }
  25561. this._pointerOverMesh = mesh;
  25562. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25563. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25564. }
  25565. };
  25566. Scene.prototype.getPointerOverMesh = function () {
  25567. return this._pointerOverMesh;
  25568. };
  25569. Scene.prototype.setPointerOverSprite = function (sprite) {
  25570. if (this._pointerOverSprite === sprite) {
  25571. return;
  25572. }
  25573. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25574. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25575. }
  25576. this._pointerOverSprite = sprite;
  25577. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25578. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25579. }
  25580. };
  25581. Scene.prototype.getPointerOverSprite = function () {
  25582. return this._pointerOverSprite;
  25583. };
  25584. // Physics
  25585. Scene.prototype.getPhysicsEngine = function () {
  25586. return this._physicsEngine;
  25587. };
  25588. /**
  25589. * Enables physics to the current scene
  25590. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25591. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25592. * @return {boolean} was the physics engine initialized
  25593. */
  25594. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25595. if (gravity === void 0) { gravity = null; }
  25596. if (this._physicsEngine) {
  25597. return true;
  25598. }
  25599. try {
  25600. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25601. return true;
  25602. }
  25603. catch (e) {
  25604. BABYLON.Tools.Error(e.message);
  25605. return false;
  25606. }
  25607. };
  25608. Scene.prototype.disablePhysicsEngine = function () {
  25609. if (!this._physicsEngine) {
  25610. return;
  25611. }
  25612. this._physicsEngine.dispose();
  25613. this._physicsEngine = null;
  25614. };
  25615. Scene.prototype.isPhysicsEnabled = function () {
  25616. return this._physicsEngine !== undefined;
  25617. };
  25618. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25619. var mesh = compound.parts[0].mesh;
  25620. if (mesh.physicsImpostor) {
  25621. mesh.physicsImpostor.dispose();
  25622. mesh.physicsImpostor = null;
  25623. }
  25624. };
  25625. // Misc.
  25626. Scene.prototype._rebuildGeometries = function () {
  25627. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25628. var geometry = _a[_i];
  25629. geometry._rebuild();
  25630. }
  25631. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25632. var mesh = _c[_b];
  25633. mesh._rebuild();
  25634. }
  25635. if (this.postProcessManager) {
  25636. this.postProcessManager._rebuild();
  25637. }
  25638. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25639. var layer = _e[_d];
  25640. layer._rebuild();
  25641. }
  25642. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25643. var effectLayer = _g[_f];
  25644. effectLayer._rebuild();
  25645. }
  25646. if (this._boundingBoxRenderer) {
  25647. this._boundingBoxRenderer._rebuild();
  25648. }
  25649. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25650. var system = _j[_h];
  25651. system.rebuild();
  25652. }
  25653. if (this._postProcessRenderPipelineManager) {
  25654. this._postProcessRenderPipelineManager._rebuild();
  25655. }
  25656. };
  25657. Scene.prototype._rebuildTextures = function () {
  25658. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25659. var texture = _a[_i];
  25660. texture._rebuild();
  25661. }
  25662. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25663. };
  25664. /**
  25665. * Creates a default light for the scene.
  25666. * @param replace Whether to replace the existing lights in the scene.
  25667. */
  25668. Scene.prototype.createDefaultLight = function (replace) {
  25669. if (replace === void 0) { replace = false; }
  25670. // Dispose existing light in replace mode.
  25671. if (replace) {
  25672. if (this.lights) {
  25673. for (var i = 0; i < this.lights.length; i++) {
  25674. this.lights[i].dispose();
  25675. }
  25676. }
  25677. }
  25678. // Light
  25679. if (this.lights.length === 0) {
  25680. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25681. }
  25682. };
  25683. /**
  25684. * Creates a default camera for the scene.
  25685. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25686. * @param replace Whether to replace the existing active camera in the scene.
  25687. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25688. */
  25689. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25690. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25691. if (replace === void 0) { replace = false; }
  25692. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25693. // Dispose existing camera in replace mode.
  25694. if (replace) {
  25695. if (this.activeCamera) {
  25696. this.activeCamera.dispose();
  25697. this.activeCamera = null;
  25698. }
  25699. }
  25700. // Camera
  25701. if (!this.activeCamera) {
  25702. var worldExtends = this.getWorldExtends();
  25703. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25704. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25705. var camera;
  25706. var radius = worldSize.length() * 1.5;
  25707. // empty scene scenario!
  25708. if (!isFinite(radius)) {
  25709. radius = 1;
  25710. worldCenter.copyFromFloats(0, 0, 0);
  25711. }
  25712. if (createArcRotateCamera) {
  25713. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25714. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25715. arcRotateCamera.wheelPrecision = 100 / radius;
  25716. camera = arcRotateCamera;
  25717. }
  25718. else {
  25719. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25720. freeCamera.setTarget(worldCenter);
  25721. camera = freeCamera;
  25722. }
  25723. camera.minZ = radius * 0.01;
  25724. camera.maxZ = radius * 1000;
  25725. camera.speed = radius * 0.2;
  25726. this.activeCamera = camera;
  25727. var canvas = this.getEngine().getRenderingCanvas();
  25728. if (attachCameraControls && canvas) {
  25729. camera.attachControl(canvas);
  25730. }
  25731. }
  25732. };
  25733. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25734. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25735. if (replace === void 0) { replace = false; }
  25736. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25737. this.createDefaultLight(replace);
  25738. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25739. };
  25740. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25741. if (pbr === void 0) { pbr = false; }
  25742. if (scale === void 0) { scale = 1000; }
  25743. if (blur === void 0) { blur = 0; }
  25744. if (environmentTexture) {
  25745. this.environmentTexture = environmentTexture;
  25746. }
  25747. if (!this.environmentTexture) {
  25748. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25749. return null;
  25750. }
  25751. // Skybox
  25752. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25753. if (pbr) {
  25754. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25755. hdrSkyboxMaterial.backFaceCulling = false;
  25756. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25757. if (hdrSkyboxMaterial.reflectionTexture) {
  25758. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25759. }
  25760. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25761. hdrSkyboxMaterial.disableLighting = true;
  25762. hdrSkyboxMaterial.twoSidedLighting = true;
  25763. hdrSkybox.infiniteDistance = true;
  25764. hdrSkybox.material = hdrSkyboxMaterial;
  25765. }
  25766. else {
  25767. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25768. skyboxMaterial.backFaceCulling = false;
  25769. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25770. if (skyboxMaterial.reflectionTexture) {
  25771. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25772. }
  25773. skyboxMaterial.disableLighting = true;
  25774. hdrSkybox.infiniteDistance = true;
  25775. hdrSkybox.material = skyboxMaterial;
  25776. }
  25777. return hdrSkybox;
  25778. };
  25779. Scene.prototype.createDefaultEnvironment = function (options) {
  25780. if (BABYLON.EnvironmentHelper) {
  25781. return new BABYLON.EnvironmentHelper(options, this);
  25782. }
  25783. return null;
  25784. };
  25785. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25786. if (webVROptions === void 0) { webVROptions = {}; }
  25787. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25788. };
  25789. // Tags
  25790. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25791. if (tagsQuery === undefined) {
  25792. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25793. return list;
  25794. }
  25795. var listByTags = [];
  25796. forEach = forEach || (function (item) { return; });
  25797. for (var i in list) {
  25798. var item = list[i];
  25799. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25800. listByTags.push(item);
  25801. forEach(item);
  25802. }
  25803. }
  25804. return listByTags;
  25805. };
  25806. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25807. return this._getByTags(this.meshes, tagsQuery, forEach);
  25808. };
  25809. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25810. return this._getByTags(this.cameras, tagsQuery, forEach);
  25811. };
  25812. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25813. return this._getByTags(this.lights, tagsQuery, forEach);
  25814. };
  25815. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25816. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25817. };
  25818. /**
  25819. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25820. * This allowed control for front to back rendering or reversly depending of the special needs.
  25821. *
  25822. * @param renderingGroupId The rendering group id corresponding to its index
  25823. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25824. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25825. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25826. */
  25827. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25828. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25829. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25830. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25831. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25832. };
  25833. /**
  25834. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25835. *
  25836. * @param renderingGroupId The rendering group id corresponding to its index
  25837. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25838. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25839. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25840. */
  25841. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25842. if (depth === void 0) { depth = true; }
  25843. if (stencil === void 0) { stencil = true; }
  25844. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25845. };
  25846. /**
  25847. * Will flag all materials as dirty to trigger new shader compilation
  25848. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25849. */
  25850. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25851. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25852. var material = _a[_i];
  25853. if (predicate && !predicate(material)) {
  25854. continue;
  25855. }
  25856. material.markAsDirty(flag);
  25857. }
  25858. };
  25859. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25860. var _this = this;
  25861. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25862. this._activeRequests.push(request);
  25863. request.onCompleteObservable.add(function (request) {
  25864. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25865. });
  25866. return request;
  25867. };
  25868. /** @ignore */
  25869. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25870. var _this = this;
  25871. return new Promise(function (resolve, reject) {
  25872. _this._loadFile(url, function (data) {
  25873. resolve(data);
  25874. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25875. reject(exception);
  25876. });
  25877. });
  25878. };
  25879. // Statics
  25880. Scene._FOGMODE_NONE = 0;
  25881. Scene._FOGMODE_EXP = 1;
  25882. Scene._FOGMODE_EXP2 = 2;
  25883. Scene._FOGMODE_LINEAR = 3;
  25884. Scene._uniqueIdCounter = 0;
  25885. Scene.MinDeltaTime = 1.0;
  25886. Scene.MaxDeltaTime = 1000.0;
  25887. /** The distance in pixel that you have to move to prevent some events */
  25888. Scene.DragMovementThreshold = 10; // in pixels
  25889. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25890. Scene.LongPressDelay = 500; // in milliseconds
  25891. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25892. Scene.DoubleClickDelay = 300; // in milliseconds
  25893. /** If you need to check double click without raising a single click at first click, enable this flag */
  25894. Scene.ExclusiveDoubleClickMode = false;
  25895. return Scene;
  25896. }());
  25897. BABYLON.Scene = Scene;
  25898. })(BABYLON || (BABYLON = {}));
  25899. //# sourceMappingURL=babylon.scene.js.map
  25900. "use strict";
  25901. var BABYLON;
  25902. (function (BABYLON) {
  25903. /**
  25904. * Set of assets to keep when moving a scene into an asset container.
  25905. */
  25906. var KeepAssets = /** @class */ (function () {
  25907. function KeepAssets() {
  25908. /**
  25909. * Cameras to keep.
  25910. */
  25911. this.cameras = new Array();
  25912. /**
  25913. * Lights to keep.
  25914. */
  25915. this.lights = new Array();
  25916. /**
  25917. * Meshes to keep.
  25918. */
  25919. this.meshes = new Array();
  25920. /**
  25921. * Skeletons to keep.
  25922. */
  25923. this.skeletons = new Array();
  25924. /**
  25925. * ParticleSystems to keep.
  25926. */
  25927. this.particleSystems = new Array();
  25928. /**
  25929. * Animations to keep.
  25930. */
  25931. this.animations = new Array();
  25932. /**
  25933. * MultiMaterials to keep.
  25934. */
  25935. this.multiMaterials = new Array();
  25936. /**
  25937. * Materials to keep.
  25938. */
  25939. this.materials = new Array();
  25940. /**
  25941. * MorphTargetManagers to keep.
  25942. */
  25943. this.morphTargetManagers = new Array();
  25944. /**
  25945. * Geometries to keep.
  25946. */
  25947. this.geometries = new Array();
  25948. /**
  25949. * TransformNodes to keep.
  25950. */
  25951. this.transformNodes = new Array();
  25952. /**
  25953. * LensFlareSystems to keep.
  25954. */
  25955. this.lensFlareSystems = new Array();
  25956. /**
  25957. * ShadowGenerators to keep.
  25958. */
  25959. this.shadowGenerators = new Array();
  25960. /**
  25961. * ActionManagers to keep.
  25962. */
  25963. this.actionManagers = new Array();
  25964. /**
  25965. * Sounds to keep.
  25966. */
  25967. this.sounds = new Array();
  25968. }
  25969. return KeepAssets;
  25970. }());
  25971. BABYLON.KeepAssets = KeepAssets;
  25972. /**
  25973. * Container with a set of assets that can be added or removed from a scene.
  25974. */
  25975. var AssetContainer = /** @class */ (function () {
  25976. /**
  25977. * Instantiates an AssetContainer.
  25978. * @param scene The scene the AssetContainer belongs to.
  25979. */
  25980. function AssetContainer(scene) {
  25981. // Objects
  25982. /**
  25983. * Cameras populated in the container.
  25984. */
  25985. this.cameras = new Array();
  25986. /**
  25987. * Lights populated in the container.
  25988. */
  25989. this.lights = new Array();
  25990. /**
  25991. * Meshes populated in the container.
  25992. */
  25993. this.meshes = new Array();
  25994. /**
  25995. * Skeletons populated in the container.
  25996. */
  25997. this.skeletons = new Array();
  25998. /**
  25999. * ParticleSystems populated in the container.
  26000. */
  26001. this.particleSystems = new Array();
  26002. /**
  26003. * Animations populated in the container.
  26004. */
  26005. this.animations = new Array();
  26006. /**
  26007. * MultiMaterials populated in the container.
  26008. */
  26009. this.multiMaterials = new Array();
  26010. /**
  26011. * Materials populated in the container.
  26012. */
  26013. this.materials = new Array();
  26014. /**
  26015. * MorphTargetManagers populated in the container.
  26016. */
  26017. this.morphTargetManagers = new Array();
  26018. /**
  26019. * Geometries populated in the container.
  26020. */
  26021. this.geometries = new Array();
  26022. /**
  26023. * TransformNodes populated in the container.
  26024. */
  26025. this.transformNodes = new Array();
  26026. /**
  26027. * LensFlareSystems populated in the container.
  26028. */
  26029. this.lensFlareSystems = new Array();
  26030. /**
  26031. * ShadowGenerators populated in the container.
  26032. */
  26033. this.shadowGenerators = new Array();
  26034. /**
  26035. * ActionManagers populated in the container.
  26036. */
  26037. this.actionManagers = new Array();
  26038. /**
  26039. * Sounds populated in the container.
  26040. */
  26041. this.sounds = new Array();
  26042. this.scene = scene;
  26043. }
  26044. /**
  26045. * Adds all the assets from the container to the scene.
  26046. */
  26047. AssetContainer.prototype.addAllToScene = function () {
  26048. var _this = this;
  26049. this.cameras.forEach(function (o) {
  26050. _this.scene.addCamera(o);
  26051. });
  26052. this.lights.forEach(function (o) {
  26053. _this.scene.addLight(o);
  26054. });
  26055. this.meshes.forEach(function (o) {
  26056. _this.scene.addMesh(o);
  26057. });
  26058. this.skeletons.forEach(function (o) {
  26059. _this.scene.addSkeleton(o);
  26060. });
  26061. this.particleSystems.forEach(function (o) {
  26062. _this.scene.addParticleSystem(o);
  26063. });
  26064. this.animations.forEach(function (o) {
  26065. _this.scene.addAnimation(o);
  26066. });
  26067. this.multiMaterials.forEach(function (o) {
  26068. _this.scene.addMultiMaterial(o);
  26069. });
  26070. this.materials.forEach(function (o) {
  26071. _this.scene.addMaterial(o);
  26072. });
  26073. this.morphTargetManagers.forEach(function (o) {
  26074. _this.scene.addMorphTargetManager(o);
  26075. });
  26076. this.geometries.forEach(function (o) {
  26077. _this.scene.addGeometry(o);
  26078. });
  26079. this.transformNodes.forEach(function (o) {
  26080. _this.scene.addTransformNode(o);
  26081. });
  26082. this.lensFlareSystems.forEach(function (o) {
  26083. _this.scene.addLensFlareSystem(o);
  26084. });
  26085. this.actionManagers.forEach(function (o) {
  26086. _this.scene.addActionManager(o);
  26087. });
  26088. this.sounds.forEach(function (o) {
  26089. o.play();
  26090. o.autoplay = true;
  26091. _this.scene.mainSoundTrack.AddSound(o);
  26092. });
  26093. };
  26094. /**
  26095. * Removes all the assets in the container from the scene
  26096. */
  26097. AssetContainer.prototype.removeAllFromScene = function () {
  26098. var _this = this;
  26099. this.cameras.forEach(function (o) {
  26100. _this.scene.removeCamera(o);
  26101. });
  26102. this.lights.forEach(function (o) {
  26103. _this.scene.removeLight(o);
  26104. });
  26105. this.meshes.forEach(function (o) {
  26106. _this.scene.removeMesh(o);
  26107. });
  26108. this.skeletons.forEach(function (o) {
  26109. _this.scene.removeSkeleton(o);
  26110. });
  26111. this.particleSystems.forEach(function (o) {
  26112. _this.scene.removeParticleSystem(o);
  26113. });
  26114. this.animations.forEach(function (o) {
  26115. _this.scene.removeAnimation(o);
  26116. });
  26117. this.multiMaterials.forEach(function (o) {
  26118. _this.scene.removeMultiMaterial(o);
  26119. });
  26120. this.materials.forEach(function (o) {
  26121. _this.scene.removeMaterial(o);
  26122. });
  26123. this.morphTargetManagers.forEach(function (o) {
  26124. _this.scene.removeMorphTargetManager(o);
  26125. });
  26126. this.geometries.forEach(function (o) {
  26127. _this.scene.removeGeometry(o);
  26128. });
  26129. this.transformNodes.forEach(function (o) {
  26130. _this.scene.removeTransformNode(o);
  26131. });
  26132. this.lensFlareSystems.forEach(function (o) {
  26133. _this.scene.removeLensFlareSystem(o);
  26134. });
  26135. this.actionManagers.forEach(function (o) {
  26136. _this.scene.removeActionManager(o);
  26137. });
  26138. this.sounds.forEach(function (o) {
  26139. o.stop();
  26140. o.autoplay = false;
  26141. _this.scene.mainSoundTrack.RemoveSound(o);
  26142. });
  26143. };
  26144. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26145. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26146. var asset = sourceAssets_1[_i];
  26147. var move = true;
  26148. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26149. var keepAsset = keepAssets_1[_a];
  26150. if (asset === keepAsset) {
  26151. move = false;
  26152. break;
  26153. }
  26154. }
  26155. if (move) {
  26156. targetAssets.push(asset);
  26157. }
  26158. }
  26159. };
  26160. /**
  26161. * Removes all the assets contained in the scene and adds them to the container.
  26162. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26163. */
  26164. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26165. if (keepAssets === undefined) {
  26166. keepAssets = new KeepAssets();
  26167. }
  26168. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26169. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26170. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26171. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26172. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26173. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26174. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26175. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26176. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26177. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26178. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26179. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26180. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26181. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26182. this.removeAllFromScene();
  26183. };
  26184. return AssetContainer;
  26185. }());
  26186. BABYLON.AssetContainer = AssetContainer;
  26187. })(BABYLON || (BABYLON = {}));
  26188. //# sourceMappingURL=babylon.assetContainer.js.map
  26189. "use strict";
  26190. var BABYLON;
  26191. (function (BABYLON) {
  26192. var Buffer = /** @class */ (function () {
  26193. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  26194. if (instanced === void 0) { instanced = false; }
  26195. if (engine instanceof BABYLON.Mesh) {
  26196. this._engine = engine.getScene().getEngine();
  26197. }
  26198. else {
  26199. this._engine = engine;
  26200. }
  26201. this._updatable = updatable;
  26202. this._instanced = instanced;
  26203. this._data = data;
  26204. this._strideSize = stride;
  26205. if (!postponeInternalCreation) {
  26206. this.create();
  26207. }
  26208. }
  26209. /**
  26210. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  26211. * @param kind defines the vertex buffer kind (position, normal, etc.)
  26212. * @param offset defines offset in the buffer (0 by default)
  26213. * @param size defines the size in floats of attributes (position is 3 for instance)
  26214. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  26215. * @param instanced defines if the vertex buffer contains indexed data
  26216. * @returns the new vertex buffer
  26217. */
  26218. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  26219. // a lot of these parameters are ignored as they are overriden by the buffer
  26220. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  26221. };
  26222. // Properties
  26223. Buffer.prototype.isUpdatable = function () {
  26224. return this._updatable;
  26225. };
  26226. Buffer.prototype.getData = function () {
  26227. return this._data;
  26228. };
  26229. Buffer.prototype.getBuffer = function () {
  26230. return this._buffer;
  26231. };
  26232. Buffer.prototype.getStrideSize = function () {
  26233. return this._strideSize;
  26234. };
  26235. // public getIsInstanced(): boolean {
  26236. // return this._instanced;
  26237. // }
  26238. // public get instanceDivisor(): number {
  26239. // return this._instanceDivisor;
  26240. // }
  26241. // public set instanceDivisor(value: number) {
  26242. // this._instanceDivisor = value;
  26243. // if (value == 0) {
  26244. // this._instanced = false;
  26245. // } else {
  26246. // this._instanced = true;
  26247. // }
  26248. // }
  26249. // Methods
  26250. Buffer.prototype.create = function (data) {
  26251. if (data === void 0) { data = null; }
  26252. if (!data && this._buffer) {
  26253. return; // nothing to do
  26254. }
  26255. data = data || this._data;
  26256. if (!data) {
  26257. return;
  26258. }
  26259. if (!this._buffer) {
  26260. if (this._updatable) {
  26261. this._buffer = this._engine.createDynamicVertexBuffer(data);
  26262. this._data = data;
  26263. }
  26264. else {
  26265. this._buffer = this._engine.createVertexBuffer(data);
  26266. }
  26267. }
  26268. else if (this._updatable) {
  26269. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  26270. this._data = data;
  26271. }
  26272. };
  26273. Buffer.prototype._rebuild = function () {
  26274. this._buffer = null;
  26275. this.create(this._data);
  26276. };
  26277. Buffer.prototype.update = function (data) {
  26278. this.create(data);
  26279. };
  26280. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  26281. if (!this._buffer) {
  26282. return;
  26283. }
  26284. if (this._updatable) {
  26285. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  26286. this._data = null;
  26287. }
  26288. };
  26289. Buffer.prototype.dispose = function () {
  26290. if (!this._buffer) {
  26291. return;
  26292. }
  26293. if (this._engine._releaseBuffer(this._buffer)) {
  26294. this._buffer = null;
  26295. }
  26296. };
  26297. return Buffer;
  26298. }());
  26299. BABYLON.Buffer = Buffer;
  26300. })(BABYLON || (BABYLON = {}));
  26301. //# sourceMappingURL=babylon.buffer.js.map
  26302. "use strict";
  26303. var BABYLON;
  26304. (function (BABYLON) {
  26305. var VertexBuffer = /** @class */ (function () {
  26306. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26307. if (data instanceof BABYLON.Buffer) {
  26308. if (!stride) {
  26309. stride = data.getStrideSize();
  26310. }
  26311. this._buffer = data;
  26312. this._ownsBuffer = false;
  26313. }
  26314. else {
  26315. if (!stride) {
  26316. stride = VertexBuffer.DeduceStride(kind);
  26317. }
  26318. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26319. this._ownsBuffer = true;
  26320. }
  26321. this._stride = stride;
  26322. this._instanced = instanced !== undefined ? instanced : false;
  26323. this._instanceDivisor = instanced ? 1 : 0;
  26324. this._offset = offset ? offset : 0;
  26325. this._size = size ? size : stride;
  26326. this._kind = kind;
  26327. }
  26328. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26329. /**
  26330. * Gets or sets the instance divisor when in instanced mode
  26331. */
  26332. get: function () {
  26333. return this._instanceDivisor;
  26334. },
  26335. set: function (value) {
  26336. this._instanceDivisor = value;
  26337. if (value == 0) {
  26338. this._instanced = false;
  26339. }
  26340. else {
  26341. this._instanced = true;
  26342. }
  26343. },
  26344. enumerable: true,
  26345. configurable: true
  26346. });
  26347. VertexBuffer.prototype._rebuild = function () {
  26348. if (!this._buffer) {
  26349. return;
  26350. }
  26351. this._buffer._rebuild();
  26352. };
  26353. /**
  26354. * Returns the kind of the VertexBuffer (string).
  26355. */
  26356. VertexBuffer.prototype.getKind = function () {
  26357. return this._kind;
  26358. };
  26359. // Properties
  26360. /**
  26361. * Boolean : is the VertexBuffer updatable ?
  26362. */
  26363. VertexBuffer.prototype.isUpdatable = function () {
  26364. return this._buffer.isUpdatable();
  26365. };
  26366. /**
  26367. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26368. */
  26369. VertexBuffer.prototype.getData = function () {
  26370. return this._buffer.getData();
  26371. };
  26372. /**
  26373. * Returns the WebGLBuffer associated to the VertexBuffer.
  26374. */
  26375. VertexBuffer.prototype.getBuffer = function () {
  26376. return this._buffer.getBuffer();
  26377. };
  26378. /**
  26379. * Returns the stride of the VertexBuffer (integer).
  26380. */
  26381. VertexBuffer.prototype.getStrideSize = function () {
  26382. return this._stride;
  26383. };
  26384. /**
  26385. * Returns the offset (integer).
  26386. */
  26387. VertexBuffer.prototype.getOffset = function () {
  26388. return this._offset;
  26389. };
  26390. /**
  26391. * Returns the VertexBuffer total size (integer).
  26392. */
  26393. VertexBuffer.prototype.getSize = function () {
  26394. return this._size;
  26395. };
  26396. /**
  26397. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26398. */
  26399. VertexBuffer.prototype.getIsInstanced = function () {
  26400. return this._instanced;
  26401. };
  26402. /**
  26403. * Returns the instancing divisor, zero for non-instanced (integer).
  26404. */
  26405. VertexBuffer.prototype.getInstanceDivisor = function () {
  26406. return this._instanceDivisor;
  26407. };
  26408. // Methods
  26409. /**
  26410. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26411. * Returns the created WebGLBuffer.
  26412. */
  26413. VertexBuffer.prototype.create = function (data) {
  26414. return this._buffer.create(data);
  26415. };
  26416. /**
  26417. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26418. * This function will create a new buffer if the current one is not updatable
  26419. * Returns the updated WebGLBuffer.
  26420. */
  26421. VertexBuffer.prototype.update = function (data) {
  26422. return this._buffer.update(data);
  26423. };
  26424. /**
  26425. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26426. * Returns the directly updated WebGLBuffer.
  26427. */
  26428. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26429. return this._buffer.updateDirectly(data, offset);
  26430. };
  26431. /**
  26432. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26433. */
  26434. VertexBuffer.prototype.dispose = function () {
  26435. if (this._ownsBuffer) {
  26436. this._buffer.dispose();
  26437. }
  26438. };
  26439. Object.defineProperty(VertexBuffer, "PositionKind", {
  26440. get: function () {
  26441. return VertexBuffer._PositionKind;
  26442. },
  26443. enumerable: true,
  26444. configurable: true
  26445. });
  26446. Object.defineProperty(VertexBuffer, "NormalKind", {
  26447. get: function () {
  26448. return VertexBuffer._NormalKind;
  26449. },
  26450. enumerable: true,
  26451. configurable: true
  26452. });
  26453. Object.defineProperty(VertexBuffer, "TangentKind", {
  26454. get: function () {
  26455. return VertexBuffer._TangentKind;
  26456. },
  26457. enumerable: true,
  26458. configurable: true
  26459. });
  26460. Object.defineProperty(VertexBuffer, "UVKind", {
  26461. get: function () {
  26462. return VertexBuffer._UVKind;
  26463. },
  26464. enumerable: true,
  26465. configurable: true
  26466. });
  26467. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26468. get: function () {
  26469. return VertexBuffer._UV2Kind;
  26470. },
  26471. enumerable: true,
  26472. configurable: true
  26473. });
  26474. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26475. get: function () {
  26476. return VertexBuffer._UV3Kind;
  26477. },
  26478. enumerable: true,
  26479. configurable: true
  26480. });
  26481. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26482. get: function () {
  26483. return VertexBuffer._UV4Kind;
  26484. },
  26485. enumerable: true,
  26486. configurable: true
  26487. });
  26488. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26489. get: function () {
  26490. return VertexBuffer._UV5Kind;
  26491. },
  26492. enumerable: true,
  26493. configurable: true
  26494. });
  26495. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26496. get: function () {
  26497. return VertexBuffer._UV6Kind;
  26498. },
  26499. enumerable: true,
  26500. configurable: true
  26501. });
  26502. Object.defineProperty(VertexBuffer, "ColorKind", {
  26503. get: function () {
  26504. return VertexBuffer._ColorKind;
  26505. },
  26506. enumerable: true,
  26507. configurable: true
  26508. });
  26509. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26510. get: function () {
  26511. return VertexBuffer._MatricesIndicesKind;
  26512. },
  26513. enumerable: true,
  26514. configurable: true
  26515. });
  26516. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26517. get: function () {
  26518. return VertexBuffer._MatricesWeightsKind;
  26519. },
  26520. enumerable: true,
  26521. configurable: true
  26522. });
  26523. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26524. get: function () {
  26525. return VertexBuffer._MatricesIndicesExtraKind;
  26526. },
  26527. enumerable: true,
  26528. configurable: true
  26529. });
  26530. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26531. get: function () {
  26532. return VertexBuffer._MatricesWeightsExtraKind;
  26533. },
  26534. enumerable: true,
  26535. configurable: true
  26536. });
  26537. /**
  26538. * Deduces the stride given a kind.
  26539. * @param kind The kind string to deduce
  26540. * @returns The deduced stride
  26541. */
  26542. VertexBuffer.DeduceStride = function (kind) {
  26543. switch (kind) {
  26544. case VertexBuffer.UVKind:
  26545. case VertexBuffer.UV2Kind:
  26546. case VertexBuffer.UV3Kind:
  26547. case VertexBuffer.UV4Kind:
  26548. case VertexBuffer.UV5Kind:
  26549. case VertexBuffer.UV6Kind:
  26550. return 2;
  26551. case VertexBuffer.NormalKind:
  26552. case VertexBuffer.PositionKind:
  26553. return 3;
  26554. case VertexBuffer.ColorKind:
  26555. case VertexBuffer.MatricesIndicesKind:
  26556. case VertexBuffer.MatricesIndicesExtraKind:
  26557. case VertexBuffer.MatricesWeightsKind:
  26558. case VertexBuffer.MatricesWeightsExtraKind:
  26559. case VertexBuffer.TangentKind:
  26560. return 4;
  26561. default:
  26562. throw new Error("Invalid kind '" + kind + "'");
  26563. }
  26564. };
  26565. // Enums
  26566. VertexBuffer._PositionKind = "position";
  26567. VertexBuffer._NormalKind = "normal";
  26568. VertexBuffer._TangentKind = "tangent";
  26569. VertexBuffer._UVKind = "uv";
  26570. VertexBuffer._UV2Kind = "uv2";
  26571. VertexBuffer._UV3Kind = "uv3";
  26572. VertexBuffer._UV4Kind = "uv4";
  26573. VertexBuffer._UV5Kind = "uv5";
  26574. VertexBuffer._UV6Kind = "uv6";
  26575. VertexBuffer._ColorKind = "color";
  26576. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26577. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26578. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26579. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26580. return VertexBuffer;
  26581. }());
  26582. BABYLON.VertexBuffer = VertexBuffer;
  26583. })(BABYLON || (BABYLON = {}));
  26584. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26585. "use strict";
  26586. var BABYLON;
  26587. (function (BABYLON) {
  26588. /**
  26589. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26590. */
  26591. var DummyInternalTextureTracker = /** @class */ (function () {
  26592. function DummyInternalTextureTracker() {
  26593. /**
  26594. * Gets or set the previous tracker in the list
  26595. */
  26596. this.previous = null;
  26597. /**
  26598. * Gets or set the next tracker in the list
  26599. */
  26600. this.next = null;
  26601. }
  26602. return DummyInternalTextureTracker;
  26603. }());
  26604. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26605. })(BABYLON || (BABYLON = {}));
  26606. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26607. "use strict";
  26608. var BABYLON;
  26609. (function (BABYLON) {
  26610. /**
  26611. * Class used to store data associated with WebGL texture data for the engine
  26612. * This class should not be used directly
  26613. */
  26614. var InternalTexture = /** @class */ (function () {
  26615. /**
  26616. * Creates a new InternalTexture
  26617. * @param engine defines the engine to use
  26618. * @param dataSource defines the type of data that will be used
  26619. */
  26620. function InternalTexture(engine, dataSource) {
  26621. /**
  26622. * Observable called when the texture is loaded
  26623. */
  26624. this.onLoadedObservable = new BABYLON.Observable();
  26625. /**
  26626. * Gets or set the previous tracker in the list
  26627. */
  26628. this.previous = null;
  26629. /**
  26630. * Gets or set the next tracker in the list
  26631. */
  26632. this.next = null;
  26633. // Private
  26634. /** @ignore */
  26635. this._initialSlot = -1;
  26636. /** @ignore */
  26637. this._designatedSlot = -1;
  26638. /** @ignore */
  26639. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26640. /** @ignore */
  26641. this._comparisonFunction = 0;
  26642. /** @ignore */
  26643. this._references = 1;
  26644. this._engine = engine;
  26645. this._dataSource = dataSource;
  26646. this._webGLTexture = engine._createTexture();
  26647. }
  26648. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26649. /**
  26650. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26651. */
  26652. get: function () {
  26653. return this._dataSource;
  26654. },
  26655. enumerable: true,
  26656. configurable: true
  26657. });
  26658. /**
  26659. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26660. */
  26661. InternalTexture.prototype.incrementReferences = function () {
  26662. this._references++;
  26663. };
  26664. /**
  26665. * Change the size of the texture (not the size of the content)
  26666. * @param width defines the new width
  26667. * @param height defines the new height
  26668. * @param depth defines the new depth (1 by default)
  26669. */
  26670. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26671. if (depth === void 0) { depth = 1; }
  26672. this.width = width;
  26673. this.height = height;
  26674. this.depth = depth;
  26675. this.baseWidth = width;
  26676. this.baseHeight = height;
  26677. this.baseDepth = depth;
  26678. this._size = width * height * depth;
  26679. };
  26680. /** @ignore */
  26681. InternalTexture.prototype._rebuild = function () {
  26682. var _this = this;
  26683. var proxy;
  26684. this.isReady = false;
  26685. this._cachedCoordinatesMode = null;
  26686. this._cachedWrapU = null;
  26687. this._cachedWrapV = null;
  26688. this._cachedAnisotropicFilteringLevel = null;
  26689. switch (this._dataSource) {
  26690. case InternalTexture.DATASOURCE_TEMP:
  26691. return;
  26692. case InternalTexture.DATASOURCE_URL:
  26693. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26694. _this.isReady = true;
  26695. }, null, this._buffer, undefined, this.format);
  26696. proxy._swapAndDie(this);
  26697. return;
  26698. case InternalTexture.DATASOURCE_RAW:
  26699. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26700. proxy._swapAndDie(this);
  26701. this.isReady = true;
  26702. return;
  26703. case InternalTexture.DATASOURCE_RAW3D:
  26704. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26705. proxy._swapAndDie(this);
  26706. this.isReady = true;
  26707. return;
  26708. case InternalTexture.DATASOURCE_DYNAMIC:
  26709. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26710. proxy._swapAndDie(this);
  26711. // The engine will make sure to update content so no need to flag it as isReady = true
  26712. return;
  26713. case InternalTexture.DATASOURCE_RENDERTARGET:
  26714. var options = new BABYLON.RenderTargetCreationOptions();
  26715. options.generateDepthBuffer = this._generateDepthBuffer;
  26716. options.generateMipMaps = this.generateMipMaps;
  26717. options.generateStencilBuffer = this._generateStencilBuffer;
  26718. options.samplingMode = this.samplingMode;
  26719. options.type = this.type;
  26720. if (this.isCube) {
  26721. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26722. }
  26723. else {
  26724. var size = {
  26725. width: this.width,
  26726. height: this.height
  26727. };
  26728. proxy = this._engine.createRenderTargetTexture(size, options);
  26729. }
  26730. proxy._swapAndDie(this);
  26731. this.isReady = true;
  26732. return;
  26733. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26734. var depthTextureOptions = {
  26735. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26736. comparisonFunction: this._comparisonFunction,
  26737. generateStencil: this._generateStencilBuffer,
  26738. isCube: this.isCube
  26739. };
  26740. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26741. proxy._swapAndDie(this);
  26742. this.isReady = true;
  26743. return;
  26744. case InternalTexture.DATASOURCE_CUBE:
  26745. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26746. _this.isReady = true;
  26747. }, null, this.format, this._extension);
  26748. proxy._swapAndDie(this);
  26749. return;
  26750. case InternalTexture.DATASOURCE_CUBERAW:
  26751. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26752. proxy._swapAndDie(this);
  26753. this.isReady = true;
  26754. return;
  26755. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26756. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26757. if (proxy) {
  26758. proxy._swapAndDie(_this);
  26759. }
  26760. _this.isReady = true;
  26761. }, null, this.format, this._extension);
  26762. return;
  26763. }
  26764. };
  26765. InternalTexture.prototype._swapAndDie = function (target) {
  26766. target._webGLTexture = this._webGLTexture;
  26767. if (this._framebuffer) {
  26768. target._framebuffer = this._framebuffer;
  26769. }
  26770. if (this._depthStencilBuffer) {
  26771. target._depthStencilBuffer = this._depthStencilBuffer;
  26772. }
  26773. if (this._lodTextureHigh) {
  26774. if (target._lodTextureHigh) {
  26775. target._lodTextureHigh.dispose();
  26776. }
  26777. target._lodTextureHigh = this._lodTextureHigh;
  26778. }
  26779. if (this._lodTextureMid) {
  26780. if (target._lodTextureMid) {
  26781. target._lodTextureMid.dispose();
  26782. }
  26783. target._lodTextureMid = this._lodTextureMid;
  26784. }
  26785. if (this._lodTextureLow) {
  26786. if (target._lodTextureLow) {
  26787. target._lodTextureLow.dispose();
  26788. }
  26789. target._lodTextureLow = this._lodTextureLow;
  26790. }
  26791. var cache = this._engine.getLoadedTexturesCache();
  26792. var index = cache.indexOf(this);
  26793. if (index !== -1) {
  26794. cache.splice(index, 1);
  26795. }
  26796. };
  26797. /**
  26798. * Dispose the current allocated resources
  26799. */
  26800. InternalTexture.prototype.dispose = function () {
  26801. if (!this._webGLTexture) {
  26802. return;
  26803. }
  26804. this._references--;
  26805. if (this._references === 0) {
  26806. this._engine._releaseTexture(this);
  26807. this._webGLTexture = null;
  26808. this.previous = null;
  26809. this.next = null;
  26810. }
  26811. };
  26812. /**
  26813. * The source of the texture data is unknown
  26814. */
  26815. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26816. /**
  26817. * Texture data comes from an URL
  26818. */
  26819. InternalTexture.DATASOURCE_URL = 1;
  26820. /**
  26821. * Texture data is only used for temporary storage
  26822. */
  26823. InternalTexture.DATASOURCE_TEMP = 2;
  26824. /**
  26825. * Texture data comes from raw data (ArrayBuffer)
  26826. */
  26827. InternalTexture.DATASOURCE_RAW = 3;
  26828. /**
  26829. * Texture content is dynamic (video or dynamic texture)
  26830. */
  26831. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26832. /**
  26833. * Texture content is generated by rendering to it
  26834. */
  26835. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26836. /**
  26837. * Texture content is part of a multi render target process
  26838. */
  26839. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26840. /**
  26841. * Texture data comes from a cube data file
  26842. */
  26843. InternalTexture.DATASOURCE_CUBE = 7;
  26844. /**
  26845. * Texture data comes from a raw cube data
  26846. */
  26847. InternalTexture.DATASOURCE_CUBERAW = 8;
  26848. /**
  26849. * Texture data come from a prefiltered cube data file
  26850. */
  26851. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26852. /**
  26853. * Texture content is raw 3D data
  26854. */
  26855. InternalTexture.DATASOURCE_RAW3D = 10;
  26856. /**
  26857. * Texture content is a depth texture
  26858. */
  26859. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26860. return InternalTexture;
  26861. }());
  26862. BABYLON.InternalTexture = InternalTexture;
  26863. })(BABYLON || (BABYLON = {}));
  26864. //# sourceMappingURL=babylon.internalTexture.js.map
  26865. "use strict";
  26866. var BABYLON;
  26867. (function (BABYLON) {
  26868. var BaseTexture = /** @class */ (function () {
  26869. function BaseTexture(scene) {
  26870. this._hasAlpha = false;
  26871. this.getAlphaFromRGB = false;
  26872. this.level = 1;
  26873. this.coordinatesIndex = 0;
  26874. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26875. /**
  26876. * | Value | Type | Description |
  26877. * | ----- | ------------------ | ----------- |
  26878. * | 0 | CLAMP_ADDRESSMODE | |
  26879. * | 1 | WRAP_ADDRESSMODE | |
  26880. * | 2 | MIRROR_ADDRESSMODE | |
  26881. */
  26882. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26883. /**
  26884. * | Value | Type | Description |
  26885. * | ----- | ------------------ | ----------- |
  26886. * | 0 | CLAMP_ADDRESSMODE | |
  26887. * | 1 | WRAP_ADDRESSMODE | |
  26888. * | 2 | MIRROR_ADDRESSMODE | |
  26889. */
  26890. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26891. /**
  26892. * | Value | Type | Description |
  26893. * | ----- | ------------------ | ----------- |
  26894. * | 0 | CLAMP_ADDRESSMODE | |
  26895. * | 1 | WRAP_ADDRESSMODE | |
  26896. * | 2 | MIRROR_ADDRESSMODE | |
  26897. */
  26898. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26899. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26900. this.isCube = false;
  26901. this.is3D = false;
  26902. this.gammaSpace = true;
  26903. this.invertZ = false;
  26904. this.lodLevelInAlpha = false;
  26905. this.lodGenerationOffset = 0.0;
  26906. this.lodGenerationScale = 0.8;
  26907. this.isRenderTarget = false;
  26908. this.animations = new Array();
  26909. /**
  26910. * An event triggered when the texture is disposed.
  26911. * @type {BABYLON.Observable}
  26912. */
  26913. this.onDisposeObservable = new BABYLON.Observable();
  26914. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26915. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26916. if (this._scene) {
  26917. this._scene.textures.push(this);
  26918. }
  26919. this._uid = null;
  26920. }
  26921. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26922. get: function () {
  26923. return this._hasAlpha;
  26924. },
  26925. set: function (value) {
  26926. if (this._hasAlpha === value) {
  26927. return;
  26928. }
  26929. this._hasAlpha = value;
  26930. if (this._scene) {
  26931. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26932. }
  26933. },
  26934. enumerable: true,
  26935. configurable: true
  26936. });
  26937. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26938. get: function () {
  26939. return this._coordinatesMode;
  26940. },
  26941. /**
  26942. * How a texture is mapped.
  26943. *
  26944. * | Value | Type | Description |
  26945. * | ----- | ----------------------------------- | ----------- |
  26946. * | 0 | EXPLICIT_MODE | |
  26947. * | 1 | SPHERICAL_MODE | |
  26948. * | 2 | PLANAR_MODE | |
  26949. * | 3 | CUBIC_MODE | |
  26950. * | 4 | PROJECTION_MODE | |
  26951. * | 5 | SKYBOX_MODE | |
  26952. * | 6 | INVCUBIC_MODE | |
  26953. * | 7 | EQUIRECTANGULAR_MODE | |
  26954. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26955. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26956. */
  26957. set: function (value) {
  26958. if (this._coordinatesMode === value) {
  26959. return;
  26960. }
  26961. this._coordinatesMode = value;
  26962. if (this._scene) {
  26963. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26964. }
  26965. },
  26966. enumerable: true,
  26967. configurable: true
  26968. });
  26969. Object.defineProperty(BaseTexture.prototype, "uid", {
  26970. get: function () {
  26971. if (!this._uid) {
  26972. this._uid = BABYLON.Tools.RandomId();
  26973. }
  26974. return this._uid;
  26975. },
  26976. enumerable: true,
  26977. configurable: true
  26978. });
  26979. BaseTexture.prototype.toString = function () {
  26980. return this.name;
  26981. };
  26982. BaseTexture.prototype.getClassName = function () {
  26983. return "BaseTexture";
  26984. };
  26985. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26986. set: function (callback) {
  26987. if (this._onDisposeObserver) {
  26988. this.onDisposeObservable.remove(this._onDisposeObserver);
  26989. }
  26990. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26991. },
  26992. enumerable: true,
  26993. configurable: true
  26994. });
  26995. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26996. get: function () {
  26997. return true;
  26998. },
  26999. enumerable: true,
  27000. configurable: true
  27001. });
  27002. BaseTexture.prototype.getScene = function () {
  27003. return this._scene;
  27004. };
  27005. BaseTexture.prototype.getTextureMatrix = function () {
  27006. return BABYLON.Matrix.IdentityReadOnly;
  27007. };
  27008. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  27009. return BABYLON.Matrix.IdentityReadOnly;
  27010. };
  27011. BaseTexture.prototype.getInternalTexture = function () {
  27012. return this._texture;
  27013. };
  27014. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  27015. return !this.isBlocking || this.isReady();
  27016. };
  27017. BaseTexture.prototype.isReady = function () {
  27018. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27019. this.delayLoad();
  27020. return false;
  27021. }
  27022. if (this._texture) {
  27023. return this._texture.isReady;
  27024. }
  27025. return false;
  27026. };
  27027. BaseTexture.prototype.getSize = function () {
  27028. if (this._texture && this._texture.width) {
  27029. return new BABYLON.Size(this._texture.width, this._texture.height);
  27030. }
  27031. if (this._texture && this._texture._size) {
  27032. return new BABYLON.Size(this._texture._size, this._texture._size);
  27033. }
  27034. return BABYLON.Size.Zero();
  27035. };
  27036. BaseTexture.prototype.getBaseSize = function () {
  27037. if (!this.isReady() || !this._texture)
  27038. return BABYLON.Size.Zero();
  27039. if (this._texture._size) {
  27040. return new BABYLON.Size(this._texture._size, this._texture._size);
  27041. }
  27042. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  27043. };
  27044. BaseTexture.prototype.scale = function (ratio) {
  27045. };
  27046. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  27047. get: function () {
  27048. return false;
  27049. },
  27050. enumerable: true,
  27051. configurable: true
  27052. });
  27053. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27054. if (!this._scene) {
  27055. return null;
  27056. }
  27057. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27058. for (var index = 0; index < texturesCache.length; index++) {
  27059. var texturesCacheEntry = texturesCache[index];
  27060. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  27061. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27062. texturesCacheEntry.incrementReferences();
  27063. return texturesCacheEntry;
  27064. }
  27065. }
  27066. }
  27067. return null;
  27068. };
  27069. BaseTexture.prototype._rebuild = function () {
  27070. };
  27071. BaseTexture.prototype.delayLoad = function () {
  27072. };
  27073. BaseTexture.prototype.clone = function () {
  27074. return null;
  27075. };
  27076. Object.defineProperty(BaseTexture.prototype, "textureType", {
  27077. get: function () {
  27078. if (!this._texture) {
  27079. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27080. }
  27081. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27082. },
  27083. enumerable: true,
  27084. configurable: true
  27085. });
  27086. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  27087. get: function () {
  27088. if (!this._texture) {
  27089. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27090. }
  27091. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27092. },
  27093. enumerable: true,
  27094. configurable: true
  27095. });
  27096. BaseTexture.prototype.readPixels = function (faceIndex) {
  27097. if (faceIndex === void 0) { faceIndex = 0; }
  27098. if (!this._texture) {
  27099. return null;
  27100. }
  27101. var size = this.getSize();
  27102. var scene = this.getScene();
  27103. if (!scene) {
  27104. return null;
  27105. }
  27106. var engine = scene.getEngine();
  27107. if (this._texture.isCube) {
  27108. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  27109. }
  27110. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  27111. };
  27112. BaseTexture.prototype.releaseInternalTexture = function () {
  27113. if (this._texture) {
  27114. this._texture.dispose();
  27115. this._texture = null;
  27116. }
  27117. };
  27118. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  27119. get: function () {
  27120. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  27121. return null;
  27122. }
  27123. if (!this._texture._sphericalPolynomial) {
  27124. this._texture._sphericalPolynomial =
  27125. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  27126. }
  27127. return this._texture._sphericalPolynomial;
  27128. },
  27129. set: function (value) {
  27130. if (this._texture) {
  27131. this._texture._sphericalPolynomial = value;
  27132. }
  27133. },
  27134. enumerable: true,
  27135. configurable: true
  27136. });
  27137. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  27138. get: function () {
  27139. if (this._texture) {
  27140. return this._texture._lodTextureHigh;
  27141. }
  27142. return null;
  27143. },
  27144. enumerable: true,
  27145. configurable: true
  27146. });
  27147. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  27148. get: function () {
  27149. if (this._texture) {
  27150. return this._texture._lodTextureMid;
  27151. }
  27152. return null;
  27153. },
  27154. enumerable: true,
  27155. configurable: true
  27156. });
  27157. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  27158. get: function () {
  27159. if (this._texture) {
  27160. return this._texture._lodTextureLow;
  27161. }
  27162. return null;
  27163. },
  27164. enumerable: true,
  27165. configurable: true
  27166. });
  27167. BaseTexture.prototype.dispose = function () {
  27168. if (!this._scene) {
  27169. return;
  27170. }
  27171. // Animations
  27172. this._scene.stopAnimation(this);
  27173. // Remove from scene
  27174. this._scene._removePendingData(this);
  27175. var index = this._scene.textures.indexOf(this);
  27176. if (index >= 0) {
  27177. this._scene.textures.splice(index, 1);
  27178. }
  27179. if (this._texture === undefined) {
  27180. return;
  27181. }
  27182. // Release
  27183. this.releaseInternalTexture();
  27184. // Callback
  27185. this.onDisposeObservable.notifyObservers(this);
  27186. this.onDisposeObservable.clear();
  27187. };
  27188. BaseTexture.prototype.serialize = function () {
  27189. if (!this.name) {
  27190. return null;
  27191. }
  27192. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27193. // Animations
  27194. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27195. return serializationObject;
  27196. };
  27197. BaseTexture.WhenAllReady = function (textures, callback) {
  27198. var numRemaining = textures.length;
  27199. if (numRemaining === 0) {
  27200. callback();
  27201. return;
  27202. }
  27203. var _loop_1 = function () {
  27204. texture = textures[i];
  27205. if (texture.isReady()) {
  27206. if (--numRemaining === 0) {
  27207. callback();
  27208. }
  27209. }
  27210. else {
  27211. onLoadObservable = texture.onLoadObservable;
  27212. var onLoadCallback_1 = function () {
  27213. onLoadObservable.removeCallback(onLoadCallback_1);
  27214. if (--numRemaining === 0) {
  27215. callback();
  27216. }
  27217. };
  27218. onLoadObservable.add(onLoadCallback_1);
  27219. }
  27220. };
  27221. var texture, onLoadObservable;
  27222. for (var i = 0; i < textures.length; i++) {
  27223. _loop_1();
  27224. }
  27225. };
  27226. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  27227. __decorate([
  27228. BABYLON.serialize()
  27229. ], BaseTexture.prototype, "name", void 0);
  27230. __decorate([
  27231. BABYLON.serialize("hasAlpha")
  27232. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27233. __decorate([
  27234. BABYLON.serialize()
  27235. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27236. __decorate([
  27237. BABYLON.serialize()
  27238. ], BaseTexture.prototype, "level", void 0);
  27239. __decorate([
  27240. BABYLON.serialize()
  27241. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27242. __decorate([
  27243. BABYLON.serialize("coordinatesMode")
  27244. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27245. __decorate([
  27246. BABYLON.serialize()
  27247. ], BaseTexture.prototype, "wrapU", void 0);
  27248. __decorate([
  27249. BABYLON.serialize()
  27250. ], BaseTexture.prototype, "wrapV", void 0);
  27251. __decorate([
  27252. BABYLON.serialize()
  27253. ], BaseTexture.prototype, "wrapR", void 0);
  27254. __decorate([
  27255. BABYLON.serialize()
  27256. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27257. __decorate([
  27258. BABYLON.serialize()
  27259. ], BaseTexture.prototype, "isCube", void 0);
  27260. __decorate([
  27261. BABYLON.serialize()
  27262. ], BaseTexture.prototype, "is3D", void 0);
  27263. __decorate([
  27264. BABYLON.serialize()
  27265. ], BaseTexture.prototype, "gammaSpace", void 0);
  27266. __decorate([
  27267. BABYLON.serialize()
  27268. ], BaseTexture.prototype, "invertZ", void 0);
  27269. __decorate([
  27270. BABYLON.serialize()
  27271. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  27272. __decorate([
  27273. BABYLON.serialize()
  27274. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  27275. __decorate([
  27276. BABYLON.serialize()
  27277. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  27278. __decorate([
  27279. BABYLON.serialize()
  27280. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27281. return BaseTexture;
  27282. }());
  27283. BABYLON.BaseTexture = BaseTexture;
  27284. })(BABYLON || (BABYLON = {}));
  27285. //# sourceMappingURL=babylon.baseTexture.js.map
  27286. "use strict";
  27287. var BABYLON;
  27288. (function (BABYLON) {
  27289. var Texture = /** @class */ (function (_super) {
  27290. __extends(Texture, _super);
  27291. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27292. if (noMipmap === void 0) { noMipmap = false; }
  27293. if (invertY === void 0) { invertY = true; }
  27294. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27295. if (onLoad === void 0) { onLoad = null; }
  27296. if (onError === void 0) { onError = null; }
  27297. if (buffer === void 0) { buffer = null; }
  27298. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27299. var _this = _super.call(this, scene) || this;
  27300. _this.uOffset = 0;
  27301. _this.vOffset = 0;
  27302. _this.uScale = 1.0;
  27303. _this.vScale = 1.0;
  27304. _this.uAng = 0;
  27305. _this.vAng = 0;
  27306. _this.wAng = 0;
  27307. _this._isBlocking = true;
  27308. _this.name = url || "";
  27309. _this.url = url;
  27310. _this._noMipmap = noMipmap;
  27311. _this._invertY = invertY;
  27312. _this._samplingMode = samplingMode;
  27313. _this._buffer = buffer;
  27314. _this._deleteBuffer = deleteBuffer;
  27315. if (format) {
  27316. _this._format = format;
  27317. }
  27318. scene = _this.getScene();
  27319. if (!scene) {
  27320. return _this;
  27321. }
  27322. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27323. var load = function () {
  27324. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27325. _this.onLoadObservable.notifyObservers(_this);
  27326. }
  27327. if (onLoad) {
  27328. onLoad();
  27329. }
  27330. if (!_this.isBlocking && scene) {
  27331. scene.resetCachedMaterial();
  27332. }
  27333. };
  27334. if (!_this.url) {
  27335. _this._delayedOnLoad = load;
  27336. _this._delayedOnError = onError;
  27337. return _this;
  27338. }
  27339. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27340. if (!_this._texture) {
  27341. if (!scene.useDelayedTextureLoading) {
  27342. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27343. if (deleteBuffer) {
  27344. delete _this._buffer;
  27345. }
  27346. }
  27347. else {
  27348. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27349. _this._delayedOnLoad = load;
  27350. _this._delayedOnError = onError;
  27351. }
  27352. }
  27353. else {
  27354. if (_this._texture.isReady) {
  27355. BABYLON.Tools.SetImmediate(function () { return load(); });
  27356. }
  27357. else {
  27358. _this._texture.onLoadedObservable.add(load);
  27359. }
  27360. }
  27361. return _this;
  27362. }
  27363. Object.defineProperty(Texture.prototype, "noMipmap", {
  27364. get: function () {
  27365. return this._noMipmap;
  27366. },
  27367. enumerable: true,
  27368. configurable: true
  27369. });
  27370. Object.defineProperty(Texture.prototype, "isBlocking", {
  27371. get: function () {
  27372. return this._isBlocking;
  27373. },
  27374. set: function (value) {
  27375. this._isBlocking = value;
  27376. },
  27377. enumerable: true,
  27378. configurable: true
  27379. });
  27380. Object.defineProperty(Texture.prototype, "samplingMode", {
  27381. get: function () {
  27382. return this._samplingMode;
  27383. },
  27384. enumerable: true,
  27385. configurable: true
  27386. });
  27387. Texture.prototype.updateURL = function (url) {
  27388. this.url = url;
  27389. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27390. this.delayLoad();
  27391. };
  27392. Texture.prototype.delayLoad = function () {
  27393. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27394. return;
  27395. }
  27396. var scene = this.getScene();
  27397. if (!scene) {
  27398. return;
  27399. }
  27400. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27401. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27402. if (!this._texture) {
  27403. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27404. if (this._deleteBuffer) {
  27405. delete this._buffer;
  27406. }
  27407. }
  27408. else {
  27409. if (this._delayedOnLoad) {
  27410. if (this._texture.isReady) {
  27411. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27412. }
  27413. else {
  27414. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27415. }
  27416. }
  27417. }
  27418. this._delayedOnLoad = null;
  27419. this._delayedOnError = null;
  27420. };
  27421. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27422. if (!this._texture) {
  27423. return;
  27424. }
  27425. var scene = this.getScene();
  27426. if (!scene) {
  27427. return;
  27428. }
  27429. this._samplingMode = samplingMode;
  27430. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27431. };
  27432. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27433. x *= this.uScale;
  27434. y *= this.vScale;
  27435. x -= 0.5 * this.uScale;
  27436. y -= 0.5 * this.vScale;
  27437. z -= 0.5;
  27438. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27439. t.x += 0.5 * this.uScale + this.uOffset;
  27440. t.y += 0.5 * this.vScale + this.vOffset;
  27441. t.z += 0.5;
  27442. };
  27443. Texture.prototype.getTextureMatrix = function () {
  27444. var _this = this;
  27445. if (this.uOffset === this._cachedUOffset &&
  27446. this.vOffset === this._cachedVOffset &&
  27447. this.uScale === this._cachedUScale &&
  27448. this.vScale === this._cachedVScale &&
  27449. this.uAng === this._cachedUAng &&
  27450. this.vAng === this._cachedVAng &&
  27451. this.wAng === this._cachedWAng) {
  27452. return this._cachedTextureMatrix;
  27453. }
  27454. this._cachedUOffset = this.uOffset;
  27455. this._cachedVOffset = this.vOffset;
  27456. this._cachedUScale = this.uScale;
  27457. this._cachedVScale = this.vScale;
  27458. this._cachedUAng = this.uAng;
  27459. this._cachedVAng = this.vAng;
  27460. this._cachedWAng = this.wAng;
  27461. if (!this._cachedTextureMatrix) {
  27462. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27463. this._rowGenerationMatrix = new BABYLON.Matrix();
  27464. this._t0 = BABYLON.Vector3.Zero();
  27465. this._t1 = BABYLON.Vector3.Zero();
  27466. this._t2 = BABYLON.Vector3.Zero();
  27467. }
  27468. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27469. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27470. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27471. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27472. this._t1.subtractInPlace(this._t0);
  27473. this._t2.subtractInPlace(this._t0);
  27474. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27475. this._cachedTextureMatrix.m[0] = this._t1.x;
  27476. this._cachedTextureMatrix.m[1] = this._t1.y;
  27477. this._cachedTextureMatrix.m[2] = this._t1.z;
  27478. this._cachedTextureMatrix.m[4] = this._t2.x;
  27479. this._cachedTextureMatrix.m[5] = this._t2.y;
  27480. this._cachedTextureMatrix.m[6] = this._t2.z;
  27481. this._cachedTextureMatrix.m[8] = this._t0.x;
  27482. this._cachedTextureMatrix.m[9] = this._t0.y;
  27483. this._cachedTextureMatrix.m[10] = this._t0.z;
  27484. var scene = this.getScene();
  27485. if (!scene) {
  27486. return this._cachedTextureMatrix;
  27487. }
  27488. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27489. return mat.hasTexture(_this);
  27490. });
  27491. return this._cachedTextureMatrix;
  27492. };
  27493. Texture.prototype.getReflectionTextureMatrix = function () {
  27494. var _this = this;
  27495. var scene = this.getScene();
  27496. if (!scene) {
  27497. return this._cachedTextureMatrix;
  27498. }
  27499. if (this.uOffset === this._cachedUOffset &&
  27500. this.vOffset === this._cachedVOffset &&
  27501. this.uScale === this._cachedUScale &&
  27502. this.vScale === this._cachedVScale &&
  27503. this.coordinatesMode === this._cachedCoordinatesMode) {
  27504. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27505. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27506. return this._cachedTextureMatrix;
  27507. }
  27508. }
  27509. else {
  27510. return this._cachedTextureMatrix;
  27511. }
  27512. }
  27513. if (!this._cachedTextureMatrix) {
  27514. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27515. }
  27516. if (!this._projectionModeMatrix) {
  27517. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27518. }
  27519. this._cachedUOffset = this.uOffset;
  27520. this._cachedVOffset = this.vOffset;
  27521. this._cachedUScale = this.uScale;
  27522. this._cachedVScale = this.vScale;
  27523. this._cachedCoordinatesMode = this.coordinatesMode;
  27524. switch (this.coordinatesMode) {
  27525. case Texture.PLANAR_MODE:
  27526. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27527. this._cachedTextureMatrix[0] = this.uScale;
  27528. this._cachedTextureMatrix[5] = this.vScale;
  27529. this._cachedTextureMatrix[12] = this.uOffset;
  27530. this._cachedTextureMatrix[13] = this.vOffset;
  27531. break;
  27532. case Texture.PROJECTION_MODE:
  27533. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27534. this._projectionModeMatrix.m[0] = 0.5;
  27535. this._projectionModeMatrix.m[5] = -0.5;
  27536. this._projectionModeMatrix.m[10] = 0.0;
  27537. this._projectionModeMatrix.m[12] = 0.5;
  27538. this._projectionModeMatrix.m[13] = 0.5;
  27539. this._projectionModeMatrix.m[14] = 1.0;
  27540. this._projectionModeMatrix.m[15] = 1.0;
  27541. var projectionMatrix = scene.getProjectionMatrix();
  27542. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27543. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27544. break;
  27545. default:
  27546. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27547. break;
  27548. }
  27549. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27550. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27551. });
  27552. return this._cachedTextureMatrix;
  27553. };
  27554. Texture.prototype.clone = function () {
  27555. var _this = this;
  27556. return BABYLON.SerializationHelper.Clone(function () {
  27557. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27558. }, this);
  27559. };
  27560. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27561. get: function () {
  27562. if (!this._onLoadObservable) {
  27563. this._onLoadObservable = new BABYLON.Observable();
  27564. }
  27565. return this._onLoadObservable;
  27566. },
  27567. enumerable: true,
  27568. configurable: true
  27569. });
  27570. Texture.prototype.serialize = function () {
  27571. var serializationObject = _super.prototype.serialize.call(this);
  27572. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27573. serializationObject.base64String = this._buffer;
  27574. serializationObject.name = serializationObject.name.replace("data:", "");
  27575. }
  27576. return serializationObject;
  27577. };
  27578. Texture.prototype.getClassName = function () {
  27579. return "Texture";
  27580. };
  27581. Texture.prototype.dispose = function () {
  27582. _super.prototype.dispose.call(this);
  27583. if (this.onLoadObservable) {
  27584. this.onLoadObservable.clear();
  27585. this._onLoadObservable = null;
  27586. }
  27587. this._delayedOnLoad = null;
  27588. this._delayedOnError = null;
  27589. };
  27590. // Statics
  27591. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27592. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27593. if (onLoad === void 0) { onLoad = null; }
  27594. if (onError === void 0) { onError = null; }
  27595. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27596. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27597. };
  27598. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27599. if (parsedTexture.customType) {
  27600. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27601. // Update Sampling Mode
  27602. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27603. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27604. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27605. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27606. }
  27607. }
  27608. return parsedCustomTexture;
  27609. }
  27610. if (parsedTexture.isCube) {
  27611. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27612. }
  27613. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27614. return null;
  27615. }
  27616. var texture = BABYLON.SerializationHelper.Parse(function () {
  27617. var generateMipMaps = true;
  27618. if (parsedTexture.noMipmap) {
  27619. generateMipMaps = false;
  27620. }
  27621. if (parsedTexture.mirrorPlane) {
  27622. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27623. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27624. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27625. return mirrorTexture;
  27626. }
  27627. else if (parsedTexture.isRenderTarget) {
  27628. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27629. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27630. return renderTargetTexture;
  27631. }
  27632. else {
  27633. var texture;
  27634. if (parsedTexture.base64String) {
  27635. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27636. }
  27637. else {
  27638. var url = rootUrl + parsedTexture.name;
  27639. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27640. url = parsedTexture.url;
  27641. }
  27642. texture = new Texture(url, scene, !generateMipMaps);
  27643. }
  27644. return texture;
  27645. }
  27646. }, parsedTexture, scene);
  27647. // Update Sampling Mode
  27648. if (parsedTexture.samplingMode) {
  27649. var sampling = parsedTexture.samplingMode;
  27650. if (texture._samplingMode !== sampling) {
  27651. texture.updateSamplingMode(sampling);
  27652. }
  27653. }
  27654. // Animations
  27655. if (parsedTexture.animations) {
  27656. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27657. var parsedAnimation = parsedTexture.animations[animationIndex];
  27658. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27659. }
  27660. }
  27661. return texture;
  27662. };
  27663. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27664. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27665. if (noMipmap === void 0) { noMipmap = false; }
  27666. if (invertY === void 0) { invertY = true; }
  27667. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27668. if (onLoad === void 0) { onLoad = null; }
  27669. if (onError === void 0) { onError = null; }
  27670. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27671. if (name.substr(0, 5) !== "data:") {
  27672. name = "data:" + name;
  27673. }
  27674. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27675. };
  27676. // Constants
  27677. Texture.NEAREST_SAMPLINGMODE = 1;
  27678. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27679. Texture.BILINEAR_SAMPLINGMODE = 2;
  27680. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27681. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27682. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27683. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27684. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27685. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27686. Texture.NEAREST_LINEAR = 7;
  27687. Texture.NEAREST_NEAREST = 8;
  27688. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27689. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27690. Texture.LINEAR_LINEAR = 11;
  27691. Texture.LINEAR_NEAREST = 12;
  27692. Texture.EXPLICIT_MODE = 0;
  27693. Texture.SPHERICAL_MODE = 1;
  27694. Texture.PLANAR_MODE = 2;
  27695. Texture.CUBIC_MODE = 3;
  27696. Texture.PROJECTION_MODE = 4;
  27697. Texture.SKYBOX_MODE = 5;
  27698. Texture.INVCUBIC_MODE = 6;
  27699. Texture.EQUIRECTANGULAR_MODE = 7;
  27700. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27701. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27702. Texture.CLAMP_ADDRESSMODE = 0;
  27703. Texture.WRAP_ADDRESSMODE = 1;
  27704. Texture.MIRROR_ADDRESSMODE = 2;
  27705. /**
  27706. * 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
  27707. */
  27708. Texture.UseSerializedUrlIfAny = false;
  27709. __decorate([
  27710. BABYLON.serialize()
  27711. ], Texture.prototype, "url", void 0);
  27712. __decorate([
  27713. BABYLON.serialize()
  27714. ], Texture.prototype, "uOffset", void 0);
  27715. __decorate([
  27716. BABYLON.serialize()
  27717. ], Texture.prototype, "vOffset", void 0);
  27718. __decorate([
  27719. BABYLON.serialize()
  27720. ], Texture.prototype, "uScale", void 0);
  27721. __decorate([
  27722. BABYLON.serialize()
  27723. ], Texture.prototype, "vScale", void 0);
  27724. __decorate([
  27725. BABYLON.serialize()
  27726. ], Texture.prototype, "uAng", void 0);
  27727. __decorate([
  27728. BABYLON.serialize()
  27729. ], Texture.prototype, "vAng", void 0);
  27730. __decorate([
  27731. BABYLON.serialize()
  27732. ], Texture.prototype, "wAng", void 0);
  27733. __decorate([
  27734. BABYLON.serialize()
  27735. ], Texture.prototype, "isBlocking", null);
  27736. return Texture;
  27737. }(BABYLON.BaseTexture));
  27738. BABYLON.Texture = Texture;
  27739. })(BABYLON || (BABYLON = {}));
  27740. //# sourceMappingURL=babylon.texture.js.map
  27741. "use strict";
  27742. var BABYLON;
  27743. (function (BABYLON) {
  27744. var _InstancesBatch = /** @class */ (function () {
  27745. function _InstancesBatch() {
  27746. this.mustReturn = false;
  27747. this.visibleInstances = new Array();
  27748. this.renderSelf = new Array();
  27749. }
  27750. return _InstancesBatch;
  27751. }());
  27752. BABYLON._InstancesBatch = _InstancesBatch;
  27753. var Mesh = /** @class */ (function (_super) {
  27754. __extends(Mesh, _super);
  27755. /**
  27756. * @constructor
  27757. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27758. * @param {Scene} scene The scene to add this mesh to.
  27759. * @param {Node} parent The parent of this mesh, if it has one
  27760. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27761. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27762. * When false, achieved by calling a clone(), also passing False.
  27763. * This will make creation of children, recursive.
  27764. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27765. */
  27766. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27767. if (scene === void 0) { scene = null; }
  27768. if (parent === void 0) { parent = null; }
  27769. if (source === void 0) { source = null; }
  27770. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27771. var _this = _super.call(this, name, scene) || this;
  27772. // Events
  27773. /**
  27774. * An event triggered before rendering the mesh
  27775. * @type {BABYLON.Observable}
  27776. */
  27777. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27778. /**
  27779. * An event triggered after rendering the mesh
  27780. * @type {BABYLON.Observable}
  27781. */
  27782. _this.onAfterRenderObservable = new BABYLON.Observable();
  27783. /**
  27784. * An event triggered before drawing the mesh
  27785. * @type {BABYLON.Observable}
  27786. */
  27787. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27788. // Members
  27789. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27790. _this.instances = new Array();
  27791. _this._LODLevels = new Array();
  27792. _this._visibleInstances = {};
  27793. _this._renderIdForInstances = new Array();
  27794. _this._batchCache = new _InstancesBatch();
  27795. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27796. // Use by builder only to know what orientation were the mesh build in.
  27797. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27798. _this.overrideMaterialSideOrientation = null;
  27799. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27800. // Will be used to save a source mesh reference, If any
  27801. _this._source = null;
  27802. scene = _this.getScene();
  27803. if (source) {
  27804. // Source mesh
  27805. _this._source = source;
  27806. // Geometry
  27807. if (source._geometry) {
  27808. source._geometry.applyToMesh(_this);
  27809. }
  27810. // Deep copy
  27811. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  27812. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  27813. // Metadata
  27814. if (source.metadata && source.metadata.clone) {
  27815. _this.metadata = source.metadata.clone();
  27816. }
  27817. else {
  27818. _this.metadata = source.metadata;
  27819. }
  27820. // Tags
  27821. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27822. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27823. }
  27824. // Parent
  27825. _this.parent = source.parent;
  27826. // Pivot
  27827. _this.setPivotMatrix(source.getPivotMatrix());
  27828. _this.id = name + "." + source.id;
  27829. // Material
  27830. _this.material = source.material;
  27831. var index;
  27832. if (!doNotCloneChildren) {
  27833. // Children
  27834. var directDescendants = source.getDescendants(true);
  27835. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27836. var child = directDescendants[index_1];
  27837. if (child.clone) {
  27838. child.clone(name + "." + child.name, _this);
  27839. }
  27840. }
  27841. }
  27842. // Physics clone
  27843. var physicsEngine = _this.getScene().getPhysicsEngine();
  27844. if (clonePhysicsImpostor && physicsEngine) {
  27845. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27846. if (impostor) {
  27847. _this.physicsImpostor = impostor.clone(_this);
  27848. }
  27849. }
  27850. // Particles
  27851. for (index = 0; index < scene.particleSystems.length; index++) {
  27852. var system = scene.particleSystems[index];
  27853. if (system.emitter === source) {
  27854. system.clone(system.name, _this);
  27855. }
  27856. }
  27857. _this.computeWorldMatrix(true);
  27858. }
  27859. // Parent
  27860. if (parent !== null) {
  27861. _this.parent = parent;
  27862. }
  27863. return _this;
  27864. }
  27865. Object.defineProperty(Mesh, "FRONTSIDE", {
  27866. /**
  27867. * Mesh side orientation : usually the external or front surface
  27868. */
  27869. get: function () {
  27870. return Mesh._FRONTSIDE;
  27871. },
  27872. enumerable: true,
  27873. configurable: true
  27874. });
  27875. Object.defineProperty(Mesh, "BACKSIDE", {
  27876. /**
  27877. * Mesh side orientation : usually the internal or back surface
  27878. */
  27879. get: function () {
  27880. return Mesh._BACKSIDE;
  27881. },
  27882. enumerable: true,
  27883. configurable: true
  27884. });
  27885. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27886. /**
  27887. * Mesh side orientation : both internal and external or front and back surfaces
  27888. */
  27889. get: function () {
  27890. return Mesh._DOUBLESIDE;
  27891. },
  27892. enumerable: true,
  27893. configurable: true
  27894. });
  27895. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27896. /**
  27897. * Mesh side orientation : by default, `FRONTSIDE`
  27898. */
  27899. get: function () {
  27900. return Mesh._DEFAULTSIDE;
  27901. },
  27902. enumerable: true,
  27903. configurable: true
  27904. });
  27905. Object.defineProperty(Mesh, "NO_CAP", {
  27906. /**
  27907. * Mesh cap setting : no cap
  27908. */
  27909. get: function () {
  27910. return Mesh._NO_CAP;
  27911. },
  27912. enumerable: true,
  27913. configurable: true
  27914. });
  27915. Object.defineProperty(Mesh, "CAP_START", {
  27916. /**
  27917. * Mesh cap setting : one cap at the beginning of the mesh
  27918. */
  27919. get: function () {
  27920. return Mesh._CAP_START;
  27921. },
  27922. enumerable: true,
  27923. configurable: true
  27924. });
  27925. Object.defineProperty(Mesh, "CAP_END", {
  27926. /**
  27927. * Mesh cap setting : one cap at the end of the mesh
  27928. */
  27929. get: function () {
  27930. return Mesh._CAP_END;
  27931. },
  27932. enumerable: true,
  27933. configurable: true
  27934. });
  27935. Object.defineProperty(Mesh, "CAP_ALL", {
  27936. /**
  27937. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27938. */
  27939. get: function () {
  27940. return Mesh._CAP_ALL;
  27941. },
  27942. enumerable: true,
  27943. configurable: true
  27944. });
  27945. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27946. set: function (callback) {
  27947. if (this._onBeforeDrawObserver) {
  27948. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27949. }
  27950. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27951. },
  27952. enumerable: true,
  27953. configurable: true
  27954. });
  27955. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27956. get: function () {
  27957. return this._morphTargetManager;
  27958. },
  27959. set: function (value) {
  27960. if (this._morphTargetManager === value) {
  27961. return;
  27962. }
  27963. this._morphTargetManager = value;
  27964. this._syncGeometryWithMorphTargetManager();
  27965. },
  27966. enumerable: true,
  27967. configurable: true
  27968. });
  27969. Object.defineProperty(Mesh.prototype, "source", {
  27970. get: function () {
  27971. return this._source;
  27972. },
  27973. enumerable: true,
  27974. configurable: true
  27975. });
  27976. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27977. get: function () {
  27978. return this._unIndexed;
  27979. },
  27980. set: function (value) {
  27981. if (this._unIndexed !== value) {
  27982. this._unIndexed = value;
  27983. this._markSubMeshesAsAttributesDirty();
  27984. }
  27985. },
  27986. enumerable: true,
  27987. configurable: true
  27988. });
  27989. // Methods
  27990. /**
  27991. * Returns the string "Mesh".
  27992. */
  27993. Mesh.prototype.getClassName = function () {
  27994. return "Mesh";
  27995. };
  27996. /**
  27997. * Returns a string.
  27998. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27999. */
  28000. Mesh.prototype.toString = function (fullDetails) {
  28001. var ret = _super.prototype.toString.call(this, fullDetails);
  28002. ret += ", n vertices: " + this.getTotalVertices();
  28003. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  28004. if (this.animations) {
  28005. for (var i = 0; i < this.animations.length; i++) {
  28006. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  28007. }
  28008. }
  28009. if (fullDetails) {
  28010. if (this._geometry) {
  28011. var ib = this.getIndices();
  28012. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28013. if (vb && ib) {
  28014. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  28015. }
  28016. }
  28017. else {
  28018. ret += ", flat shading: UNKNOWN";
  28019. }
  28020. }
  28021. return ret;
  28022. };
  28023. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  28024. /**
  28025. * True if the mesh has some Levels Of Details (LOD).
  28026. * Returns a boolean.
  28027. */
  28028. get: function () {
  28029. return this._LODLevels.length > 0;
  28030. },
  28031. enumerable: true,
  28032. configurable: true
  28033. });
  28034. /**
  28035. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  28036. * @returns an array of {BABYLON.MeshLODLevel}
  28037. */
  28038. Mesh.prototype.getLODLevels = function () {
  28039. return this._LODLevels;
  28040. };
  28041. Mesh.prototype._sortLODLevels = function () {
  28042. this._LODLevels.sort(function (a, b) {
  28043. if (a.distance < b.distance) {
  28044. return 1;
  28045. }
  28046. if (a.distance > b.distance) {
  28047. return -1;
  28048. }
  28049. return 0;
  28050. });
  28051. };
  28052. /**
  28053. * Add a mesh as LOD level triggered at the given distance.
  28054. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28055. * @param {number} distance The distance from the center of the object to show this level
  28056. * @param {Mesh} mesh The mesh to be added as LOD level
  28057. * @return {Mesh} This mesh (for chaining)
  28058. */
  28059. Mesh.prototype.addLODLevel = function (distance, mesh) {
  28060. if (mesh && mesh._masterMesh) {
  28061. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  28062. return this;
  28063. }
  28064. var level = new BABYLON.MeshLODLevel(distance, mesh);
  28065. this._LODLevels.push(level);
  28066. if (mesh) {
  28067. mesh._masterMesh = this;
  28068. }
  28069. this._sortLODLevels();
  28070. return this;
  28071. };
  28072. /**
  28073. * Returns the LOD level mesh at the passed distance or null if not found.
  28074. * It is related to the method `addLODLevel(distance, mesh)`.
  28075. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28076. * Returns an object Mesh or `null`.
  28077. */
  28078. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  28079. for (var index = 0; index < this._LODLevels.length; index++) {
  28080. var level = this._LODLevels[index];
  28081. if (level.distance === distance) {
  28082. return level.mesh;
  28083. }
  28084. }
  28085. return null;
  28086. };
  28087. /**
  28088. * Remove a mesh from the LOD array
  28089. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28090. * @param {Mesh} mesh The mesh to be removed.
  28091. * @return {Mesh} This mesh (for chaining)
  28092. */
  28093. Mesh.prototype.removeLODLevel = function (mesh) {
  28094. for (var index = 0; index < this._LODLevels.length; index++) {
  28095. if (this._LODLevels[index].mesh === mesh) {
  28096. this._LODLevels.splice(index, 1);
  28097. if (mesh) {
  28098. mesh._masterMesh = null;
  28099. }
  28100. }
  28101. }
  28102. this._sortLODLevels();
  28103. return this;
  28104. };
  28105. /**
  28106. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  28107. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28108. */
  28109. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  28110. if (!this._LODLevels || this._LODLevels.length === 0) {
  28111. return this;
  28112. }
  28113. var bSphere;
  28114. if (boundingSphere) {
  28115. bSphere = boundingSphere;
  28116. }
  28117. else {
  28118. var boundingInfo = this.getBoundingInfo();
  28119. bSphere = boundingInfo.boundingSphere;
  28120. }
  28121. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  28122. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  28123. if (this.onLODLevelSelection) {
  28124. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  28125. }
  28126. return this;
  28127. }
  28128. for (var index = 0; index < this._LODLevels.length; index++) {
  28129. var level = this._LODLevels[index];
  28130. if (level.distance < distanceToCamera) {
  28131. if (level.mesh) {
  28132. level.mesh._preActivate();
  28133. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  28134. }
  28135. if (this.onLODLevelSelection) {
  28136. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  28137. }
  28138. return level.mesh;
  28139. }
  28140. }
  28141. if (this.onLODLevelSelection) {
  28142. this.onLODLevelSelection(distanceToCamera, this, this);
  28143. }
  28144. return this;
  28145. };
  28146. Object.defineProperty(Mesh.prototype, "geometry", {
  28147. /**
  28148. * Returns the mesh internal Geometry object.
  28149. */
  28150. get: function () {
  28151. return this._geometry;
  28152. },
  28153. enumerable: true,
  28154. configurable: true
  28155. });
  28156. /**
  28157. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  28158. */
  28159. Mesh.prototype.getTotalVertices = function () {
  28160. if (this._geometry === null || this._geometry === undefined) {
  28161. return 0;
  28162. }
  28163. return this._geometry.getTotalVertices();
  28164. };
  28165. /**
  28166. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  28167. * 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.
  28168. * You can force the copy with forceCopy === true
  28169. * Returns null if the mesh has no geometry or no vertex buffer.
  28170. * Possible `kind` values :
  28171. * - BABYLON.VertexBuffer.PositionKind
  28172. * - BABYLON.VertexBuffer.UVKind
  28173. * - BABYLON.VertexBuffer.UV2Kind
  28174. * - BABYLON.VertexBuffer.UV3Kind
  28175. * - BABYLON.VertexBuffer.UV4Kind
  28176. * - BABYLON.VertexBuffer.UV5Kind
  28177. * - BABYLON.VertexBuffer.UV6Kind
  28178. * - BABYLON.VertexBuffer.ColorKind
  28179. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28180. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28181. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28182. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28183. */
  28184. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28185. if (!this._geometry) {
  28186. return null;
  28187. }
  28188. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  28189. };
  28190. /**
  28191. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  28192. * Returns `null` if the mesh has no geometry.
  28193. * Possible `kind` values :
  28194. * - BABYLON.VertexBuffer.PositionKind
  28195. * - BABYLON.VertexBuffer.UVKind
  28196. * - BABYLON.VertexBuffer.UV2Kind
  28197. * - BABYLON.VertexBuffer.UV3Kind
  28198. * - BABYLON.VertexBuffer.UV4Kind
  28199. * - BABYLON.VertexBuffer.UV5Kind
  28200. * - BABYLON.VertexBuffer.UV6Kind
  28201. * - BABYLON.VertexBuffer.ColorKind
  28202. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28203. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28204. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28205. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28206. */
  28207. Mesh.prototype.getVertexBuffer = function (kind) {
  28208. if (!this._geometry) {
  28209. return null;
  28210. }
  28211. return this._geometry.getVertexBuffer(kind);
  28212. };
  28213. /**
  28214. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  28215. * Possible `kind` values :
  28216. * - BABYLON.VertexBuffer.PositionKind
  28217. * - BABYLON.VertexBuffer.UVKind
  28218. * - BABYLON.VertexBuffer.UV2Kind
  28219. * - BABYLON.VertexBuffer.UV3Kind
  28220. * - BABYLON.VertexBuffer.UV4Kind
  28221. * - BABYLON.VertexBuffer.UV5Kind
  28222. * - BABYLON.VertexBuffer.UV6Kind
  28223. * - BABYLON.VertexBuffer.ColorKind
  28224. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28225. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28226. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28227. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28228. */
  28229. Mesh.prototype.isVerticesDataPresent = function (kind) {
  28230. if (!this._geometry) {
  28231. if (this._delayInfo) {
  28232. return this._delayInfo.indexOf(kind) !== -1;
  28233. }
  28234. return false;
  28235. }
  28236. return this._geometry.isVerticesDataPresent(kind);
  28237. };
  28238. /**
  28239. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  28240. * Possible `kind` values :
  28241. * - BABYLON.VertexBuffer.PositionKind
  28242. * - BABYLON.VertexBuffer.UVKind
  28243. * - BABYLON.VertexBuffer.UV2Kind
  28244. * - BABYLON.VertexBuffer.UV3Kind
  28245. * - BABYLON.VertexBuffer.UV4Kind
  28246. * - BABYLON.VertexBuffer.UV5Kind
  28247. * - BABYLON.VertexBuffer.UV6Kind
  28248. * - BABYLON.VertexBuffer.ColorKind
  28249. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28250. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28251. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28252. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28253. */
  28254. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  28255. if (!this._geometry) {
  28256. if (this._delayInfo) {
  28257. return this._delayInfo.indexOf(kind) !== -1;
  28258. }
  28259. return false;
  28260. }
  28261. return this._geometry.isVertexBufferUpdatable(kind);
  28262. };
  28263. /**
  28264. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  28265. * Possible `kind` values :
  28266. * - BABYLON.VertexBuffer.PositionKind
  28267. * - BABYLON.VertexBuffer.UVKind
  28268. * - BABYLON.VertexBuffer.UV2Kind
  28269. * - BABYLON.VertexBuffer.UV3Kind
  28270. * - BABYLON.VertexBuffer.UV4Kind
  28271. * - BABYLON.VertexBuffer.UV5Kind
  28272. * - BABYLON.VertexBuffer.UV6Kind
  28273. * - BABYLON.VertexBuffer.ColorKind
  28274. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28275. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28276. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28277. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28278. */
  28279. Mesh.prototype.getVerticesDataKinds = function () {
  28280. if (!this._geometry) {
  28281. var result = new Array();
  28282. if (this._delayInfo) {
  28283. this._delayInfo.forEach(function (kind, index, array) {
  28284. result.push(kind);
  28285. });
  28286. }
  28287. return result;
  28288. }
  28289. return this._geometry.getVerticesDataKinds();
  28290. };
  28291. /**
  28292. * Returns a positive integer : the total number of indices in this mesh geometry.
  28293. * Returns zero if the mesh has no geometry.
  28294. */
  28295. Mesh.prototype.getTotalIndices = function () {
  28296. if (!this._geometry) {
  28297. return 0;
  28298. }
  28299. return this._geometry.getTotalIndices();
  28300. };
  28301. /**
  28302. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  28303. * 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.
  28304. * Returns an empty array if the mesh has no geometry.
  28305. */
  28306. Mesh.prototype.getIndices = function (copyWhenShared) {
  28307. if (!this._geometry) {
  28308. return [];
  28309. }
  28310. return this._geometry.getIndices(copyWhenShared);
  28311. };
  28312. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28313. get: function () {
  28314. return this._masterMesh !== null && this._masterMesh !== undefined;
  28315. },
  28316. enumerable: true,
  28317. configurable: true
  28318. });
  28319. /**
  28320. * Determine if the current mesh is ready to be rendered
  28321. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28322. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28323. * @returns true if all associated assets are ready (material, textures, shaders)
  28324. */
  28325. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28326. if (completeCheck === void 0) { completeCheck = false; }
  28327. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28328. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28329. return false;
  28330. }
  28331. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28332. return false;
  28333. }
  28334. if (!this.subMeshes || this.subMeshes.length === 0) {
  28335. return true;
  28336. }
  28337. if (!completeCheck) {
  28338. return true;
  28339. }
  28340. var engine = this.getEngine();
  28341. var scene = this.getScene();
  28342. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28343. this.computeWorldMatrix();
  28344. var mat = this.material || scene.defaultMaterial;
  28345. if (mat) {
  28346. if (mat.storeEffectOnSubMeshes) {
  28347. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28348. var subMesh = _a[_i];
  28349. var effectiveMaterial = subMesh.getMaterial();
  28350. if (effectiveMaterial) {
  28351. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28352. return false;
  28353. }
  28354. }
  28355. }
  28356. }
  28357. else {
  28358. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28359. return false;
  28360. }
  28361. }
  28362. }
  28363. // Shadows
  28364. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28365. var light = _c[_b];
  28366. var generator = light.getShadowGenerator();
  28367. if (generator) {
  28368. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28369. var subMesh = _e[_d];
  28370. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28371. return false;
  28372. }
  28373. }
  28374. }
  28375. }
  28376. // LOD
  28377. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28378. var lod = _g[_f];
  28379. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28380. return false;
  28381. }
  28382. }
  28383. return true;
  28384. };
  28385. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28386. /**
  28387. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28388. * This property is pertinent only for updatable parametric shapes.
  28389. */
  28390. get: function () {
  28391. return this._areNormalsFrozen;
  28392. },
  28393. enumerable: true,
  28394. configurable: true
  28395. });
  28396. /**
  28397. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28398. * It has no effect at all on other shapes.
  28399. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28400. * Returns the Mesh.
  28401. */
  28402. Mesh.prototype.freezeNormals = function () {
  28403. this._areNormalsFrozen = true;
  28404. return this;
  28405. };
  28406. /**
  28407. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28408. * It has no effect at all on other shapes.
  28409. * It reactivates the mesh normals computation if it was previously frozen.
  28410. * Returns the Mesh.
  28411. */
  28412. Mesh.prototype.unfreezeNormals = function () {
  28413. this._areNormalsFrozen = false;
  28414. return this;
  28415. };
  28416. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28417. /**
  28418. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28419. */
  28420. set: function (count) {
  28421. this._overridenInstanceCount = count;
  28422. },
  28423. enumerable: true,
  28424. configurable: true
  28425. });
  28426. // Methods
  28427. Mesh.prototype._preActivate = function () {
  28428. var sceneRenderId = this.getScene().getRenderId();
  28429. if (this._preActivateId === sceneRenderId) {
  28430. return this;
  28431. }
  28432. this._preActivateId = sceneRenderId;
  28433. this._visibleInstances = null;
  28434. return this;
  28435. };
  28436. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28437. if (this._visibleInstances) {
  28438. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28439. }
  28440. return this;
  28441. };
  28442. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28443. if (!this._visibleInstances) {
  28444. this._visibleInstances = {};
  28445. this._visibleInstances.defaultRenderId = renderId;
  28446. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28447. }
  28448. if (!this._visibleInstances[renderId]) {
  28449. this._visibleInstances[renderId] = new Array();
  28450. }
  28451. this._visibleInstances[renderId].push(instance);
  28452. return this;
  28453. };
  28454. /**
  28455. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28456. * This means the mesh underlying bounding box and sphere are recomputed.
  28457. * Returns the Mesh.
  28458. */
  28459. Mesh.prototype.refreshBoundingInfo = function () {
  28460. return this._refreshBoundingInfo(false);
  28461. };
  28462. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28463. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28464. return this;
  28465. }
  28466. var data = this._getPositionData(applySkeleton);
  28467. if (data) {
  28468. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28469. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28470. }
  28471. if (this.subMeshes) {
  28472. for (var index = 0; index < this.subMeshes.length; index++) {
  28473. this.subMeshes[index].refreshBoundingInfo();
  28474. }
  28475. }
  28476. this._updateBoundingInfo();
  28477. return this;
  28478. };
  28479. Mesh.prototype._getPositionData = function (applySkeleton) {
  28480. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28481. if (data && applySkeleton && this.skeleton) {
  28482. data = BABYLON.Tools.Slice(data);
  28483. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28484. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28485. if (matricesWeightsData && matricesIndicesData) {
  28486. var needExtras = this.numBoneInfluencers > 4;
  28487. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28488. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28489. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28490. var tempVector = BABYLON.Tmp.Vector3[0];
  28491. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28492. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28493. var matWeightIdx = 0;
  28494. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28495. finalMatrix.reset();
  28496. var inf;
  28497. var weight;
  28498. for (inf = 0; inf < 4; inf++) {
  28499. weight = matricesWeightsData[matWeightIdx + inf];
  28500. if (weight <= 0)
  28501. break;
  28502. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28503. finalMatrix.addToSelf(tempMatrix);
  28504. }
  28505. if (needExtras) {
  28506. for (inf = 0; inf < 4; inf++) {
  28507. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28508. if (weight <= 0)
  28509. break;
  28510. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28511. finalMatrix.addToSelf(tempMatrix);
  28512. }
  28513. }
  28514. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28515. tempVector.toArray(data, index);
  28516. }
  28517. }
  28518. }
  28519. return data;
  28520. };
  28521. Mesh.prototype._createGlobalSubMesh = function (force) {
  28522. var totalVertices = this.getTotalVertices();
  28523. if (!totalVertices || !this.getIndices()) {
  28524. return null;
  28525. }
  28526. // Check if we need to recreate the submeshes
  28527. if (this.subMeshes && this.subMeshes.length > 0) {
  28528. var ib = this.getIndices();
  28529. if (!ib) {
  28530. return null;
  28531. }
  28532. var totalIndices = ib.length;
  28533. var needToRecreate = false;
  28534. if (force) {
  28535. needToRecreate = true;
  28536. }
  28537. else {
  28538. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28539. var submesh = _a[_i];
  28540. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28541. needToRecreate = true;
  28542. break;
  28543. }
  28544. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28545. needToRecreate = true;
  28546. break;
  28547. }
  28548. }
  28549. }
  28550. if (!needToRecreate) {
  28551. return this.subMeshes[0];
  28552. }
  28553. }
  28554. this.releaseSubMeshes();
  28555. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28556. };
  28557. Mesh.prototype.subdivide = function (count) {
  28558. if (count < 1) {
  28559. return;
  28560. }
  28561. var totalIndices = this.getTotalIndices();
  28562. var subdivisionSize = (totalIndices / count) | 0;
  28563. var offset = 0;
  28564. // Ensure that subdivisionSize is a multiple of 3
  28565. while (subdivisionSize % 3 !== 0) {
  28566. subdivisionSize++;
  28567. }
  28568. this.releaseSubMeshes();
  28569. for (var index = 0; index < count; index++) {
  28570. if (offset >= totalIndices) {
  28571. break;
  28572. }
  28573. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28574. offset += subdivisionSize;
  28575. }
  28576. this.synchronizeInstances();
  28577. };
  28578. /**
  28579. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28580. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28581. * The `data` are either a numeric array either a Float32Array.
  28582. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28583. * 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).
  28584. * Note that a new underlying VertexBuffer object is created each call.
  28585. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28586. *
  28587. * Possible `kind` values :
  28588. * - BABYLON.VertexBuffer.PositionKind
  28589. * - BABYLON.VertexBuffer.UVKind
  28590. * - BABYLON.VertexBuffer.UV2Kind
  28591. * - BABYLON.VertexBuffer.UV3Kind
  28592. * - BABYLON.VertexBuffer.UV4Kind
  28593. * - BABYLON.VertexBuffer.UV5Kind
  28594. * - BABYLON.VertexBuffer.UV6Kind
  28595. * - BABYLON.VertexBuffer.ColorKind
  28596. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28597. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28598. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28599. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28600. *
  28601. * Returns the Mesh.
  28602. */
  28603. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28604. if (updatable === void 0) { updatable = false; }
  28605. if (!this._geometry) {
  28606. var vertexData = new BABYLON.VertexData();
  28607. vertexData.set(data, kind);
  28608. var scene = this.getScene();
  28609. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28610. }
  28611. else {
  28612. this._geometry.setVerticesData(kind, data, updatable, stride);
  28613. }
  28614. return this;
  28615. };
  28616. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28617. if (updatable === void 0) { updatable = true; }
  28618. var vb = this.getVertexBuffer(kind);
  28619. if (!vb || vb.isUpdatable() === updatable) {
  28620. return;
  28621. }
  28622. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28623. };
  28624. /**
  28625. * Sets the mesh VertexBuffer.
  28626. * Returns the Mesh.
  28627. */
  28628. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28629. if (!this._geometry) {
  28630. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28631. }
  28632. this._geometry.setVerticesBuffer(buffer);
  28633. return this;
  28634. };
  28635. /**
  28636. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28637. * If the mesh has no geometry, it is simply returned as it is.
  28638. * The `data` are either a numeric array either a Float32Array.
  28639. * No new underlying VertexBuffer object is created.
  28640. * 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.
  28641. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28642. *
  28643. * Possible `kind` values :
  28644. * - BABYLON.VertexBuffer.PositionKind
  28645. * - BABYLON.VertexBuffer.UVKind
  28646. * - BABYLON.VertexBuffer.UV2Kind
  28647. * - BABYLON.VertexBuffer.UV3Kind
  28648. * - BABYLON.VertexBuffer.UV4Kind
  28649. * - BABYLON.VertexBuffer.UV5Kind
  28650. * - BABYLON.VertexBuffer.UV6Kind
  28651. * - BABYLON.VertexBuffer.ColorKind
  28652. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28653. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28654. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28655. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28656. *
  28657. * Returns the Mesh.
  28658. */
  28659. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28660. if (!this._geometry) {
  28661. return this;
  28662. }
  28663. if (!makeItUnique) {
  28664. this._geometry.updateVerticesData(kind, data, updateExtends);
  28665. }
  28666. else {
  28667. this.makeGeometryUnique();
  28668. this.updateVerticesData(kind, data, updateExtends, false);
  28669. }
  28670. return this;
  28671. };
  28672. /**
  28673. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28674. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28675. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28676. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28677. * Returns the Mesh.
  28678. */
  28679. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28680. if (computeNormals === void 0) { computeNormals = true; }
  28681. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28682. if (!positions) {
  28683. return this;
  28684. }
  28685. positionFunction(positions);
  28686. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28687. if (computeNormals) {
  28688. var indices = this.getIndices();
  28689. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28690. if (!normals) {
  28691. return this;
  28692. }
  28693. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28694. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28695. }
  28696. return this;
  28697. };
  28698. /**
  28699. * Creates a un-shared specific occurence of the geometry for the mesh.
  28700. * Returns the Mesh.
  28701. */
  28702. Mesh.prototype.makeGeometryUnique = function () {
  28703. if (!this._geometry) {
  28704. return this;
  28705. }
  28706. var oldGeometry = this._geometry;
  28707. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28708. oldGeometry.releaseForMesh(this, true);
  28709. geometry.applyToMesh(this);
  28710. return this;
  28711. };
  28712. /**
  28713. * Sets the mesh indices.
  28714. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28715. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28716. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28717. * This method creates a new index buffer each call.
  28718. * Returns the Mesh.
  28719. */
  28720. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28721. if (totalVertices === void 0) { totalVertices = null; }
  28722. if (updatable === void 0) { updatable = false; }
  28723. if (!this._geometry) {
  28724. var vertexData = new BABYLON.VertexData();
  28725. vertexData.indices = indices;
  28726. var scene = this.getScene();
  28727. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28728. }
  28729. else {
  28730. this._geometry.setIndices(indices, totalVertices, updatable);
  28731. }
  28732. return this;
  28733. };
  28734. /**
  28735. * Update the current index buffer
  28736. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28737. * Returns the Mesh.
  28738. */
  28739. Mesh.prototype.updateIndices = function (indices, offset) {
  28740. if (!this._geometry) {
  28741. return this;
  28742. }
  28743. this._geometry.updateIndices(indices, offset);
  28744. return this;
  28745. };
  28746. /**
  28747. * Invert the geometry to move from a right handed system to a left handed one.
  28748. * Returns the Mesh.
  28749. */
  28750. Mesh.prototype.toLeftHanded = function () {
  28751. if (!this._geometry) {
  28752. return this;
  28753. }
  28754. this._geometry.toLeftHanded();
  28755. return this;
  28756. };
  28757. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28758. if (!this._geometry) {
  28759. return this;
  28760. }
  28761. var engine = this.getScene().getEngine();
  28762. // Wireframe
  28763. var indexToBind;
  28764. if (this._unIndexed) {
  28765. indexToBind = null;
  28766. }
  28767. else {
  28768. switch (fillMode) {
  28769. case BABYLON.Material.PointFillMode:
  28770. indexToBind = null;
  28771. break;
  28772. case BABYLON.Material.WireFrameFillMode:
  28773. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28774. break;
  28775. default:
  28776. case BABYLON.Material.TriangleFillMode:
  28777. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28778. break;
  28779. }
  28780. }
  28781. // VBOs
  28782. this._geometry._bind(effect, indexToBind);
  28783. return this;
  28784. };
  28785. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28786. if (alternate === void 0) { alternate = false; }
  28787. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28788. return this;
  28789. }
  28790. this.onBeforeDrawObservable.notifyObservers(this);
  28791. var scene = this.getScene();
  28792. var engine = scene.getEngine();
  28793. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28794. // or triangles as points
  28795. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28796. }
  28797. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28798. // Triangles as wireframe
  28799. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28800. }
  28801. else {
  28802. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28803. }
  28804. if (scene._isAlternateRenderingEnabled && !alternate) {
  28805. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28806. if (!effect || !scene.activeCamera) {
  28807. return this;
  28808. }
  28809. scene._switchToAlternateCameraConfiguration(true);
  28810. this._effectiveMaterial.bindView(effect);
  28811. this._effectiveMaterial.bindViewProjection(effect);
  28812. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28813. this._draw(subMesh, fillMode, instancesCount, true);
  28814. engine.setViewport(scene.activeCamera.viewport);
  28815. scene._switchToAlternateCameraConfiguration(false);
  28816. this._effectiveMaterial.bindView(effect);
  28817. this._effectiveMaterial.bindViewProjection(effect);
  28818. }
  28819. return this;
  28820. };
  28821. /**
  28822. * Registers for this mesh a javascript function called just before the rendering process.
  28823. * This function is passed the current mesh.
  28824. * Return the Mesh.
  28825. */
  28826. Mesh.prototype.registerBeforeRender = function (func) {
  28827. this.onBeforeRenderObservable.add(func);
  28828. return this;
  28829. };
  28830. /**
  28831. * Disposes a previously registered javascript function called before the rendering.
  28832. * This function is passed the current mesh.
  28833. * Returns the Mesh.
  28834. */
  28835. Mesh.prototype.unregisterBeforeRender = function (func) {
  28836. this.onBeforeRenderObservable.removeCallback(func);
  28837. return this;
  28838. };
  28839. /**
  28840. * Registers for this mesh a javascript function called just after the rendering is complete.
  28841. * This function is passed the current mesh.
  28842. * Returns the Mesh.
  28843. */
  28844. Mesh.prototype.registerAfterRender = function (func) {
  28845. this.onAfterRenderObservable.add(func);
  28846. return this;
  28847. };
  28848. /**
  28849. * Disposes a previously registered javascript function called after the rendering.
  28850. * This function is passed the current mesh.
  28851. * Return the Mesh.
  28852. */
  28853. Mesh.prototype.unregisterAfterRender = function (func) {
  28854. this.onAfterRenderObservable.removeCallback(func);
  28855. return this;
  28856. };
  28857. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28858. var scene = this.getScene();
  28859. this._batchCache.mustReturn = false;
  28860. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28861. this._batchCache.visibleInstances[subMeshId] = null;
  28862. if (this._visibleInstances) {
  28863. var currentRenderId = scene.getRenderId();
  28864. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28865. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28866. var selfRenderId = this._renderId;
  28867. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28868. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28869. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28870. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28871. }
  28872. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28873. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28874. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28875. this._batchCache.mustReturn = true;
  28876. return this._batchCache;
  28877. }
  28878. if (currentRenderId !== selfRenderId) {
  28879. this._batchCache.renderSelf[subMeshId] = false;
  28880. }
  28881. }
  28882. this._renderIdForInstances[subMeshId] = currentRenderId;
  28883. }
  28884. return this._batchCache;
  28885. };
  28886. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28887. var visibleInstances = batch.visibleInstances[subMesh._id];
  28888. if (!visibleInstances) {
  28889. return this;
  28890. }
  28891. var matricesCount = visibleInstances.length + 1;
  28892. var bufferSize = matricesCount * 16 * 4;
  28893. var currentInstancesBufferSize = this._instancesBufferSize;
  28894. var instancesBuffer = this._instancesBuffer;
  28895. while (this._instancesBufferSize < bufferSize) {
  28896. this._instancesBufferSize *= 2;
  28897. }
  28898. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28899. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28900. }
  28901. var offset = 0;
  28902. var instancesCount = 0;
  28903. var world = this.getWorldMatrix();
  28904. if (batch.renderSelf[subMesh._id]) {
  28905. world.copyToArray(this._instancesData, offset);
  28906. offset += 16;
  28907. instancesCount++;
  28908. }
  28909. if (visibleInstances) {
  28910. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28911. var instance = visibleInstances[instanceIndex];
  28912. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28913. offset += 16;
  28914. instancesCount++;
  28915. }
  28916. }
  28917. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28918. if (instancesBuffer) {
  28919. instancesBuffer.dispose();
  28920. }
  28921. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28922. this._instancesBuffer = instancesBuffer;
  28923. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28924. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28925. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28926. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28927. }
  28928. else {
  28929. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28930. }
  28931. this._bind(subMesh, effect, fillMode);
  28932. this._draw(subMesh, fillMode, instancesCount);
  28933. engine.unbindInstanceAttributes();
  28934. return this;
  28935. };
  28936. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28937. var scene = this.getScene();
  28938. var engine = scene.getEngine();
  28939. if (hardwareInstancedRendering) {
  28940. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28941. }
  28942. else {
  28943. if (batch.renderSelf[subMesh._id]) {
  28944. // Draw
  28945. if (onBeforeDraw) {
  28946. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28947. }
  28948. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28949. }
  28950. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28951. if (visibleInstancesForSubMesh) {
  28952. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28953. var instance = visibleInstancesForSubMesh[instanceIndex];
  28954. // World
  28955. var world = instance.getWorldMatrix();
  28956. if (onBeforeDraw) {
  28957. onBeforeDraw(true, world, effectiveMaterial);
  28958. }
  28959. // Draw
  28960. this._draw(subMesh, fillMode);
  28961. }
  28962. }
  28963. }
  28964. return this;
  28965. };
  28966. /**
  28967. * Triggers the draw call for the mesh.
  28968. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28969. * Returns the Mesh.
  28970. */
  28971. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28972. this.checkOcclusionQuery();
  28973. if (this._isOccluded) {
  28974. return this;
  28975. }
  28976. var scene = this.getScene();
  28977. // Managing instances
  28978. var batch = this._getInstancesRenderList(subMesh._id);
  28979. if (batch.mustReturn) {
  28980. return this;
  28981. }
  28982. // Checking geometry state
  28983. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28984. return this;
  28985. }
  28986. this.onBeforeRenderObservable.notifyObservers(this);
  28987. var engine = scene.getEngine();
  28988. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28989. // Material
  28990. var material = subMesh.getMaterial();
  28991. if (!material) {
  28992. return this;
  28993. }
  28994. this._effectiveMaterial = material;
  28995. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28996. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28997. return this;
  28998. }
  28999. }
  29000. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  29001. return this;
  29002. }
  29003. // Alpha mode
  29004. if (enableAlphaMode) {
  29005. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  29006. }
  29007. // Outline - step 1
  29008. var savedDepthWrite = engine.getDepthWrite();
  29009. if (this.renderOutline) {
  29010. engine.setDepthWrite(false);
  29011. scene.getOutlineRenderer().render(subMesh, batch);
  29012. engine.setDepthWrite(savedDepthWrite);
  29013. }
  29014. var effect;
  29015. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29016. effect = subMesh.effect;
  29017. }
  29018. else {
  29019. effect = this._effectiveMaterial.getEffect();
  29020. }
  29021. if (!effect) {
  29022. return this;
  29023. }
  29024. var sideOrientation = this.overrideMaterialSideOrientation;
  29025. if (sideOrientation == null) {
  29026. sideOrientation = this._effectiveMaterial.sideOrientation;
  29027. if (this._getWorldMatrixDeterminant() < 0) {
  29028. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  29029. }
  29030. }
  29031. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  29032. if (this._effectiveMaterial.forceDepthWrite) {
  29033. engine.setDepthWrite(true);
  29034. }
  29035. // Bind
  29036. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  29037. if (!hardwareInstancedRendering) {
  29038. this._bind(subMesh, effect, fillMode);
  29039. }
  29040. var world = this.getWorldMatrix();
  29041. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29042. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  29043. }
  29044. else {
  29045. this._effectiveMaterial.bind(world, this);
  29046. }
  29047. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  29048. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  29049. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29050. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  29051. }
  29052. // Draw
  29053. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29054. // Unbind
  29055. this._effectiveMaterial.unbind();
  29056. // Outline - step 2
  29057. if (this.renderOutline && savedDepthWrite) {
  29058. engine.setDepthWrite(true);
  29059. engine.setColorWrite(false);
  29060. scene.getOutlineRenderer().render(subMesh, batch);
  29061. engine.setColorWrite(true);
  29062. }
  29063. // Overlay
  29064. if (this.renderOverlay) {
  29065. var currentMode = engine.getAlphaMode();
  29066. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29067. scene.getOutlineRenderer().render(subMesh, batch, true);
  29068. engine.setAlphaMode(currentMode);
  29069. }
  29070. this.onAfterRenderObservable.notifyObservers(this);
  29071. return this;
  29072. };
  29073. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  29074. if (isInstance && effectiveMaterial) {
  29075. effectiveMaterial.bindOnlyWorldMatrix(world);
  29076. }
  29077. };
  29078. /**
  29079. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  29080. */
  29081. Mesh.prototype.getEmittedParticleSystems = function () {
  29082. var results = new Array();
  29083. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29084. var particleSystem = this.getScene().particleSystems[index];
  29085. if (particleSystem.emitter === this) {
  29086. results.push(particleSystem);
  29087. }
  29088. }
  29089. return results;
  29090. };
  29091. /**
  29092. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  29093. */
  29094. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  29095. var results = new Array();
  29096. var descendants = this.getDescendants();
  29097. descendants.push(this);
  29098. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29099. var particleSystem = this.getScene().particleSystems[index];
  29100. var emitter = particleSystem.emitter;
  29101. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  29102. results.push(particleSystem);
  29103. }
  29104. }
  29105. return results;
  29106. };
  29107. Mesh.prototype._checkDelayState = function () {
  29108. var scene = this.getScene();
  29109. if (this._geometry) {
  29110. this._geometry.load(scene);
  29111. }
  29112. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29113. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29114. this._queueLoad(scene);
  29115. }
  29116. return this;
  29117. };
  29118. Mesh.prototype._queueLoad = function (scene) {
  29119. var _this = this;
  29120. scene._addPendingData(this);
  29121. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  29122. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29123. if (data instanceof ArrayBuffer) {
  29124. _this._delayLoadingFunction(data, _this);
  29125. }
  29126. else {
  29127. _this._delayLoadingFunction(JSON.parse(data), _this);
  29128. }
  29129. _this.instances.forEach(function (instance) {
  29130. instance._syncSubMeshes();
  29131. });
  29132. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29133. scene._removePendingData(_this);
  29134. }, function () { }, scene.database, getBinaryData);
  29135. return this;
  29136. };
  29137. /**
  29138. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  29139. */
  29140. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  29141. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29142. return false;
  29143. }
  29144. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  29145. return false;
  29146. }
  29147. this._checkDelayState();
  29148. return true;
  29149. };
  29150. /**
  29151. * Sets the mesh material by the material or multiMaterial `id` property.
  29152. * The material `id` is a string identifying the material or the multiMaterial.
  29153. * This method returns the Mesh.
  29154. */
  29155. Mesh.prototype.setMaterialByID = function (id) {
  29156. var materials = this.getScene().materials;
  29157. var index;
  29158. for (index = materials.length - 1; index > -1; index--) {
  29159. if (materials[index].id === id) {
  29160. this.material = materials[index];
  29161. return this;
  29162. }
  29163. }
  29164. // Multi
  29165. var multiMaterials = this.getScene().multiMaterials;
  29166. for (index = multiMaterials.length - 1; index > -1; index--) {
  29167. if (multiMaterials[index].id === id) {
  29168. this.material = multiMaterials[index];
  29169. return this;
  29170. }
  29171. }
  29172. return this;
  29173. };
  29174. /**
  29175. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  29176. */
  29177. Mesh.prototype.getAnimatables = function () {
  29178. var results = new Array();
  29179. if (this.material) {
  29180. results.push(this.material);
  29181. }
  29182. if (this.skeleton) {
  29183. results.push(this.skeleton);
  29184. }
  29185. return results;
  29186. };
  29187. /**
  29188. * Modifies the mesh geometry according to the passed transformation matrix.
  29189. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  29190. * The mesh normals are modified accordingly the same transformation.
  29191. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  29192. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29193. * Returns the Mesh.
  29194. */
  29195. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  29196. // Position
  29197. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29198. return this;
  29199. }
  29200. var submeshes = this.subMeshes.splice(0);
  29201. this._resetPointsArrayCache();
  29202. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29203. var temp = new Array();
  29204. var index;
  29205. for (index = 0; index < data.length; index += 3) {
  29206. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  29207. }
  29208. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  29209. // Normals
  29210. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29211. return this;
  29212. }
  29213. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29214. temp = [];
  29215. for (index = 0; index < data.length; index += 3) {
  29216. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  29217. }
  29218. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  29219. // flip faces?
  29220. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  29221. this.flipFaces();
  29222. }
  29223. // Restore submeshes
  29224. this.releaseSubMeshes();
  29225. this.subMeshes = submeshes;
  29226. return this;
  29227. };
  29228. /**
  29229. * Modifies the mesh geometry according to its own current World Matrix.
  29230. * The mesh World Matrix is then reset.
  29231. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  29232. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  29233. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29234. * Returns the Mesh.
  29235. */
  29236. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  29237. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  29238. this.scaling.copyFromFloats(1, 1, 1);
  29239. this.position.copyFromFloats(0, 0, 0);
  29240. this.rotation.copyFromFloats(0, 0, 0);
  29241. //only if quaternion is already set
  29242. if (this.rotationQuaternion) {
  29243. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  29244. }
  29245. this._worldMatrix = BABYLON.Matrix.Identity();
  29246. return this;
  29247. };
  29248. Object.defineProperty(Mesh.prototype, "_positions", {
  29249. // Cache
  29250. get: function () {
  29251. if (this._geometry) {
  29252. return this._geometry._positions;
  29253. }
  29254. return null;
  29255. },
  29256. enumerable: true,
  29257. configurable: true
  29258. });
  29259. Mesh.prototype._resetPointsArrayCache = function () {
  29260. if (this._geometry) {
  29261. this._geometry._resetPointsArrayCache();
  29262. }
  29263. return this;
  29264. };
  29265. Mesh.prototype._generatePointsArray = function () {
  29266. if (this._geometry) {
  29267. return this._geometry._generatePointsArray();
  29268. }
  29269. return false;
  29270. };
  29271. /**
  29272. * Returns a new Mesh object generated from the current mesh properties.
  29273. * This method must not get confused with createInstance().
  29274. * The parameter `name` is a string, the name given to the new mesh.
  29275. * The optional parameter `newParent` can be any Node object (default `null`).
  29276. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  29277. * 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.
  29278. */
  29279. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  29280. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29281. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  29282. };
  29283. /**
  29284. * Releases resources associated with this mesh.
  29285. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  29286. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  29287. */
  29288. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  29289. var _this = this;
  29290. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  29291. this.morphTargetManager = null;
  29292. if (this._geometry) {
  29293. this._geometry.releaseForMesh(this, true);
  29294. }
  29295. // Sources
  29296. var meshes = this.getScene().meshes;
  29297. meshes.forEach(function (abstractMesh) {
  29298. var mesh = abstractMesh;
  29299. if (mesh._source && mesh._source === _this) {
  29300. mesh._source = null;
  29301. }
  29302. });
  29303. this._source = null;
  29304. // Instances
  29305. if (this._instancesBuffer) {
  29306. this._instancesBuffer.dispose();
  29307. this._instancesBuffer = null;
  29308. }
  29309. while (this.instances.length) {
  29310. this.instances[0].dispose();
  29311. }
  29312. // Effect layers.
  29313. var effectLayers = this.getScene().effectLayers;
  29314. for (var i = 0; i < effectLayers.length; i++) {
  29315. var effectLayer = effectLayers[i];
  29316. if (effectLayer) {
  29317. effectLayer._disposeMesh(this);
  29318. }
  29319. }
  29320. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29321. };
  29322. /**
  29323. * Modifies the mesh geometry according to a displacement map.
  29324. * 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.
  29325. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29326. * This method returns nothing.
  29327. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29328. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29329. * 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.
  29330. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29331. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29332. *
  29333. * Returns the Mesh.
  29334. */
  29335. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29336. var _this = this;
  29337. var scene = this.getScene();
  29338. var onload = function (img) {
  29339. // Getting height map data
  29340. var canvas = document.createElement("canvas");
  29341. var context = canvas.getContext("2d");
  29342. var heightMapWidth = img.width;
  29343. var heightMapHeight = img.height;
  29344. canvas.width = heightMapWidth;
  29345. canvas.height = heightMapHeight;
  29346. context.drawImage(img, 0, 0);
  29347. // Create VertexData from map data
  29348. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29349. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29350. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29351. //execute success callback, if set
  29352. if (onSuccess) {
  29353. onSuccess(_this);
  29354. }
  29355. };
  29356. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29357. return this;
  29358. };
  29359. /**
  29360. * Modifies the mesh geometry according to a displacementMap buffer.
  29361. * 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.
  29362. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29363. * This method returns nothing.
  29364. * 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.
  29365. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29366. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29367. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29368. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29369. *
  29370. * Returns the Mesh.
  29371. */
  29372. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29373. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29374. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29375. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29376. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29377. return this;
  29378. }
  29379. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29380. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29381. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29382. var position = BABYLON.Vector3.Zero();
  29383. var normal = BABYLON.Vector3.Zero();
  29384. var uv = BABYLON.Vector2.Zero();
  29385. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29386. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29387. for (var index = 0; index < positions.length; index += 3) {
  29388. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29389. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29390. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29391. // Compute height
  29392. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29393. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29394. var pos = (u + v * heightMapWidth) * 4;
  29395. var r = buffer[pos] / 255.0;
  29396. var g = buffer[pos + 1] / 255.0;
  29397. var b = buffer[pos + 2] / 255.0;
  29398. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29399. normal.normalize();
  29400. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29401. position = position.add(normal);
  29402. position.toArray(positions, index);
  29403. }
  29404. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29405. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29406. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29407. return this;
  29408. };
  29409. /**
  29410. * Modify the mesh to get a flat shading rendering.
  29411. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29412. * This method returns the Mesh.
  29413. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29414. */
  29415. Mesh.prototype.convertToFlatShadedMesh = function () {
  29416. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29417. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29418. var kinds = this.getVerticesDataKinds();
  29419. var vbs = {};
  29420. var data = {};
  29421. var newdata = {};
  29422. var updatableNormals = false;
  29423. var kindIndex;
  29424. var kind;
  29425. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29426. kind = kinds[kindIndex];
  29427. var vertexBuffer = this.getVertexBuffer(kind);
  29428. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29429. updatableNormals = vertexBuffer.isUpdatable();
  29430. kinds.splice(kindIndex, 1);
  29431. kindIndex--;
  29432. continue;
  29433. }
  29434. vbs[kind] = vertexBuffer;
  29435. data[kind] = vbs[kind].getData();
  29436. newdata[kind] = [];
  29437. }
  29438. // Save previous submeshes
  29439. var previousSubmeshes = this.subMeshes.slice(0);
  29440. var indices = this.getIndices();
  29441. var totalIndices = this.getTotalIndices();
  29442. // Generating unique vertices per face
  29443. var index;
  29444. for (index = 0; index < totalIndices; index++) {
  29445. var vertexIndex = indices[index];
  29446. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29447. kind = kinds[kindIndex];
  29448. var stride = vbs[kind].getStrideSize();
  29449. for (var offset = 0; offset < stride; offset++) {
  29450. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29451. }
  29452. }
  29453. }
  29454. // Updating faces & normal
  29455. var normals = [];
  29456. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29457. for (index = 0; index < totalIndices; index += 3) {
  29458. indices[index] = index;
  29459. indices[index + 1] = index + 1;
  29460. indices[index + 2] = index + 2;
  29461. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29462. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29463. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29464. var p1p2 = p1.subtract(p2);
  29465. var p3p2 = p3.subtract(p2);
  29466. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29467. // Store same normals for every vertex
  29468. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29469. normals.push(normal.x);
  29470. normals.push(normal.y);
  29471. normals.push(normal.z);
  29472. }
  29473. }
  29474. this.setIndices(indices);
  29475. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29476. // Updating vertex buffers
  29477. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29478. kind = kinds[kindIndex];
  29479. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29480. }
  29481. // Updating submeshes
  29482. this.releaseSubMeshes();
  29483. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29484. var previousOne = previousSubmeshes[submeshIndex];
  29485. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29486. }
  29487. this.synchronizeInstances();
  29488. return this;
  29489. };
  29490. /**
  29491. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29492. * In other words, more vertices, no more indices and a single bigger VBO.
  29493. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29494. * Returns the Mesh.
  29495. */
  29496. Mesh.prototype.convertToUnIndexedMesh = function () {
  29497. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29498. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29499. var kinds = this.getVerticesDataKinds();
  29500. var vbs = {};
  29501. var data = {};
  29502. var newdata = {};
  29503. var kindIndex;
  29504. var kind;
  29505. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29506. kind = kinds[kindIndex];
  29507. var vertexBuffer = this.getVertexBuffer(kind);
  29508. vbs[kind] = vertexBuffer;
  29509. data[kind] = vbs[kind].getData();
  29510. newdata[kind] = [];
  29511. }
  29512. // Save previous submeshes
  29513. var previousSubmeshes = this.subMeshes.slice(0);
  29514. var indices = this.getIndices();
  29515. var totalIndices = this.getTotalIndices();
  29516. // Generating unique vertices per face
  29517. var index;
  29518. for (index = 0; index < totalIndices; index++) {
  29519. var vertexIndex = indices[index];
  29520. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29521. kind = kinds[kindIndex];
  29522. var stride = vbs[kind].getStrideSize();
  29523. for (var offset = 0; offset < stride; offset++) {
  29524. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29525. }
  29526. }
  29527. }
  29528. // Updating indices
  29529. for (index = 0; index < totalIndices; index += 3) {
  29530. indices[index] = index;
  29531. indices[index + 1] = index + 1;
  29532. indices[index + 2] = index + 2;
  29533. }
  29534. this.setIndices(indices);
  29535. // Updating vertex buffers
  29536. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29537. kind = kinds[kindIndex];
  29538. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29539. }
  29540. // Updating submeshes
  29541. this.releaseSubMeshes();
  29542. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29543. var previousOne = previousSubmeshes[submeshIndex];
  29544. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29545. }
  29546. this._unIndexed = true;
  29547. this.synchronizeInstances();
  29548. return this;
  29549. };
  29550. /**
  29551. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29552. * This method returns the Mesh.
  29553. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29554. */
  29555. Mesh.prototype.flipFaces = function (flipNormals) {
  29556. if (flipNormals === void 0) { flipNormals = false; }
  29557. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29558. var i;
  29559. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29560. for (i = 0; i < vertex_data.normals.length; i++) {
  29561. vertex_data.normals[i] *= -1;
  29562. }
  29563. }
  29564. if (vertex_data.indices) {
  29565. var temp;
  29566. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29567. // reassign indices
  29568. temp = vertex_data.indices[i + 1];
  29569. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29570. vertex_data.indices[i + 2] = temp;
  29571. }
  29572. }
  29573. vertex_data.applyToMesh(this);
  29574. return this;
  29575. };
  29576. // Instances
  29577. /**
  29578. * Creates a new InstancedMesh object from the mesh model.
  29579. * An instance shares the same properties and the same material than its model.
  29580. * Only these properties of each instance can then be set individually :
  29581. * - position
  29582. * - rotation
  29583. * - rotationQuaternion
  29584. * - setPivotMatrix
  29585. * - scaling
  29586. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29587. * Warning : this method is not supported for Line mesh and LineSystem
  29588. */
  29589. Mesh.prototype.createInstance = function (name) {
  29590. return new BABYLON.InstancedMesh(name, this);
  29591. };
  29592. /**
  29593. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29594. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29595. * This method returns the Mesh.
  29596. */
  29597. Mesh.prototype.synchronizeInstances = function () {
  29598. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29599. var instance = this.instances[instanceIndex];
  29600. instance._syncSubMeshes();
  29601. }
  29602. return this;
  29603. };
  29604. /**
  29605. * Simplify the mesh according to the given array of settings.
  29606. * Function will return immediately and will simplify async. It returns the Mesh.
  29607. * @param settings a collection of simplification settings.
  29608. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29609. * @param type the type of simplification to run.
  29610. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29611. */
  29612. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29613. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29614. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29615. this.getScene().simplificationQueue.addTask({
  29616. settings: settings,
  29617. parallelProcessing: parallelProcessing,
  29618. mesh: this,
  29619. simplificationType: simplificationType,
  29620. successCallback: successCallback
  29621. });
  29622. return this;
  29623. };
  29624. /**
  29625. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29626. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29627. * This should be used together with the simplification to avoid disappearing triangles.
  29628. * Returns the Mesh.
  29629. * @param successCallback an optional success callback to be called after the optimization finished.
  29630. */
  29631. Mesh.prototype.optimizeIndices = function (successCallback) {
  29632. var _this = this;
  29633. var indices = this.getIndices();
  29634. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29635. if (!positions || !indices) {
  29636. return this;
  29637. }
  29638. var vectorPositions = new Array();
  29639. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29640. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29641. }
  29642. var dupes = new Array();
  29643. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29644. var realPos = vectorPositions.length - 1 - iteration;
  29645. var testedPosition = vectorPositions[realPos];
  29646. for (var j = 0; j < realPos; ++j) {
  29647. var againstPosition = vectorPositions[j];
  29648. if (testedPosition.equals(againstPosition)) {
  29649. dupes[realPos] = j;
  29650. break;
  29651. }
  29652. }
  29653. }, function () {
  29654. for (var i = 0; i < indices.length; ++i) {
  29655. indices[i] = dupes[indices[i]] || indices[i];
  29656. }
  29657. //indices are now reordered
  29658. var originalSubMeshes = _this.subMeshes.slice(0);
  29659. _this.setIndices(indices);
  29660. _this.subMeshes = originalSubMeshes;
  29661. if (successCallback) {
  29662. successCallback(_this);
  29663. }
  29664. });
  29665. return this;
  29666. };
  29667. Mesh.prototype.serialize = function (serializationObject) {
  29668. serializationObject.name = this.name;
  29669. serializationObject.id = this.id;
  29670. serializationObject.type = this.getClassName();
  29671. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29672. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29673. }
  29674. serializationObject.position = this.position.asArray();
  29675. if (this.rotationQuaternion) {
  29676. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29677. }
  29678. else if (this.rotation) {
  29679. serializationObject.rotation = this.rotation.asArray();
  29680. }
  29681. serializationObject.scaling = this.scaling.asArray();
  29682. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29683. serializationObject.isEnabled = this.isEnabled(false);
  29684. serializationObject.isVisible = this.isVisible;
  29685. serializationObject.infiniteDistance = this.infiniteDistance;
  29686. serializationObject.pickable = this.isPickable;
  29687. serializationObject.receiveShadows = this.receiveShadows;
  29688. serializationObject.billboardMode = this.billboardMode;
  29689. serializationObject.visibility = this.visibility;
  29690. serializationObject.checkCollisions = this.checkCollisions;
  29691. serializationObject.isBlocker = this.isBlocker;
  29692. // Parent
  29693. if (this.parent) {
  29694. serializationObject.parentId = this.parent.id;
  29695. }
  29696. // Geometry
  29697. serializationObject.isUnIndexed = this.isUnIndexed;
  29698. var geometry = this._geometry;
  29699. if (geometry) {
  29700. var geometryId = geometry.id;
  29701. serializationObject.geometryId = geometryId;
  29702. // SubMeshes
  29703. serializationObject.subMeshes = [];
  29704. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29705. var subMesh = this.subMeshes[subIndex];
  29706. serializationObject.subMeshes.push({
  29707. materialIndex: subMesh.materialIndex,
  29708. verticesStart: subMesh.verticesStart,
  29709. verticesCount: subMesh.verticesCount,
  29710. indexStart: subMesh.indexStart,
  29711. indexCount: subMesh.indexCount
  29712. });
  29713. }
  29714. }
  29715. // Material
  29716. if (this.material) {
  29717. serializationObject.materialId = this.material.id;
  29718. }
  29719. else {
  29720. this.material = null;
  29721. }
  29722. // Morph targets
  29723. if (this.morphTargetManager) {
  29724. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29725. }
  29726. // Skeleton
  29727. if (this.skeleton) {
  29728. serializationObject.skeletonId = this.skeleton.id;
  29729. }
  29730. // Physics
  29731. //TODO implement correct serialization for physics impostors.
  29732. var impostor = this.getPhysicsImpostor();
  29733. if (impostor) {
  29734. serializationObject.physicsMass = impostor.getParam("mass");
  29735. serializationObject.physicsFriction = impostor.getParam("friction");
  29736. serializationObject.physicsRestitution = impostor.getParam("mass");
  29737. serializationObject.physicsImpostor = impostor.type;
  29738. }
  29739. // Metadata
  29740. if (this.metadata) {
  29741. serializationObject.metadata = this.metadata;
  29742. }
  29743. // Instances
  29744. serializationObject.instances = [];
  29745. for (var index = 0; index < this.instances.length; index++) {
  29746. var instance = this.instances[index];
  29747. var serializationInstance = {
  29748. name: instance.name,
  29749. id: instance.id,
  29750. position: instance.position.asArray(),
  29751. scaling: instance.scaling.asArray()
  29752. };
  29753. if (instance.rotationQuaternion) {
  29754. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29755. }
  29756. else if (instance.rotation) {
  29757. serializationInstance.rotation = instance.rotation.asArray();
  29758. }
  29759. serializationObject.instances.push(serializationInstance);
  29760. // Animations
  29761. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29762. serializationInstance.ranges = instance.serializeAnimationRanges();
  29763. }
  29764. //
  29765. // Animations
  29766. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29767. serializationObject.ranges = this.serializeAnimationRanges();
  29768. // Layer mask
  29769. serializationObject.layerMask = this.layerMask;
  29770. // Alpha
  29771. serializationObject.alphaIndex = this.alphaIndex;
  29772. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29773. // Overlay
  29774. serializationObject.overlayAlpha = this.overlayAlpha;
  29775. serializationObject.overlayColor = this.overlayColor.asArray();
  29776. serializationObject.renderOverlay = this.renderOverlay;
  29777. // Fog
  29778. serializationObject.applyFog = this.applyFog;
  29779. // Action Manager
  29780. if (this.actionManager) {
  29781. serializationObject.actions = this.actionManager.serialize(this.name);
  29782. }
  29783. };
  29784. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29785. if (!this.geometry) {
  29786. return;
  29787. }
  29788. this._markSubMeshesAsAttributesDirty();
  29789. var morphTargetManager = this._morphTargetManager;
  29790. if (morphTargetManager && morphTargetManager.vertexCount) {
  29791. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29792. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29793. this.morphTargetManager = null;
  29794. return;
  29795. }
  29796. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29797. var morphTarget = morphTargetManager.getActiveTarget(index);
  29798. var positions = morphTarget.getPositions();
  29799. if (!positions) {
  29800. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29801. return;
  29802. }
  29803. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29804. var normals = morphTarget.getNormals();
  29805. if (normals) {
  29806. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29807. }
  29808. var tangents = morphTarget.getTangents();
  29809. if (tangents) {
  29810. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29811. }
  29812. }
  29813. }
  29814. else {
  29815. var index = 0;
  29816. // Positions
  29817. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29818. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29819. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29820. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29821. }
  29822. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29823. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29824. }
  29825. index++;
  29826. }
  29827. }
  29828. };
  29829. // Statics
  29830. /**
  29831. * Returns a new Mesh object parsed from the source provided.
  29832. * The parameter `parsedMesh` is the source.
  29833. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29834. */
  29835. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29836. var mesh;
  29837. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29838. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29839. }
  29840. else {
  29841. mesh = new Mesh(parsedMesh.name, scene);
  29842. }
  29843. mesh.id = parsedMesh.id;
  29844. if (BABYLON.Tags) {
  29845. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29846. }
  29847. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29848. if (parsedMesh.metadata !== undefined) {
  29849. mesh.metadata = parsedMesh.metadata;
  29850. }
  29851. if (parsedMesh.rotationQuaternion) {
  29852. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29853. }
  29854. else if (parsedMesh.rotation) {
  29855. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29856. }
  29857. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29858. if (parsedMesh.localMatrix) {
  29859. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29860. }
  29861. else if (parsedMesh.pivotMatrix) {
  29862. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29863. }
  29864. mesh.setEnabled(parsedMesh.isEnabled);
  29865. mesh.isVisible = parsedMesh.isVisible;
  29866. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29867. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29868. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29869. if (parsedMesh.applyFog !== undefined) {
  29870. mesh.applyFog = parsedMesh.applyFog;
  29871. }
  29872. if (parsedMesh.pickable !== undefined) {
  29873. mesh.isPickable = parsedMesh.pickable;
  29874. }
  29875. if (parsedMesh.alphaIndex !== undefined) {
  29876. mesh.alphaIndex = parsedMesh.alphaIndex;
  29877. }
  29878. mesh.receiveShadows = parsedMesh.receiveShadows;
  29879. mesh.billboardMode = parsedMesh.billboardMode;
  29880. if (parsedMesh.visibility !== undefined) {
  29881. mesh.visibility = parsedMesh.visibility;
  29882. }
  29883. mesh.checkCollisions = parsedMesh.checkCollisions;
  29884. if (parsedMesh.isBlocker !== undefined) {
  29885. mesh.isBlocker = parsedMesh.isBlocker;
  29886. }
  29887. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29888. // freezeWorldMatrix
  29889. if (parsedMesh.freezeWorldMatrix) {
  29890. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29891. }
  29892. // Parent
  29893. if (parsedMesh.parentId) {
  29894. mesh._waitingParentId = parsedMesh.parentId;
  29895. }
  29896. // Actions
  29897. if (parsedMesh.actions !== undefined) {
  29898. mesh._waitingActions = parsedMesh.actions;
  29899. }
  29900. // Overlay
  29901. if (parsedMesh.overlayAlpha !== undefined) {
  29902. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29903. }
  29904. if (parsedMesh.overlayColor !== undefined) {
  29905. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29906. }
  29907. if (parsedMesh.renderOverlay !== undefined) {
  29908. mesh.renderOverlay = parsedMesh.renderOverlay;
  29909. }
  29910. // Geometry
  29911. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29912. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29913. if (parsedMesh.delayLoadingFile) {
  29914. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29915. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29916. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29917. if (parsedMesh._binaryInfo) {
  29918. mesh._binaryInfo = parsedMesh._binaryInfo;
  29919. }
  29920. mesh._delayInfo = [];
  29921. if (parsedMesh.hasUVs) {
  29922. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29923. }
  29924. if (parsedMesh.hasUVs2) {
  29925. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29926. }
  29927. if (parsedMesh.hasUVs3) {
  29928. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29929. }
  29930. if (parsedMesh.hasUVs4) {
  29931. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29932. }
  29933. if (parsedMesh.hasUVs5) {
  29934. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29935. }
  29936. if (parsedMesh.hasUVs6) {
  29937. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29938. }
  29939. if (parsedMesh.hasColors) {
  29940. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29941. }
  29942. if (parsedMesh.hasMatricesIndices) {
  29943. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29944. }
  29945. if (parsedMesh.hasMatricesWeights) {
  29946. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29947. }
  29948. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29949. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29950. mesh._checkDelayState();
  29951. }
  29952. }
  29953. else {
  29954. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29955. }
  29956. // Material
  29957. if (parsedMesh.materialId) {
  29958. mesh.setMaterialByID(parsedMesh.materialId);
  29959. }
  29960. else {
  29961. mesh.material = null;
  29962. }
  29963. // Morph targets
  29964. if (parsedMesh.morphTargetManagerId > -1) {
  29965. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29966. }
  29967. // Skeleton
  29968. if (parsedMesh.skeletonId > -1) {
  29969. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29970. if (parsedMesh.numBoneInfluencers) {
  29971. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29972. }
  29973. }
  29974. // Animations
  29975. if (parsedMesh.animations) {
  29976. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29977. var parsedAnimation = parsedMesh.animations[animationIndex];
  29978. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29979. }
  29980. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29981. }
  29982. if (parsedMesh.autoAnimate) {
  29983. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29984. }
  29985. // Layer Mask
  29986. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29987. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29988. }
  29989. else {
  29990. mesh.layerMask = 0x0FFFFFFF;
  29991. }
  29992. // Physics
  29993. if (parsedMesh.physicsImpostor) {
  29994. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29995. mass: parsedMesh.physicsMass,
  29996. friction: parsedMesh.physicsFriction,
  29997. restitution: parsedMesh.physicsRestitution
  29998. }, scene);
  29999. }
  30000. // Instances
  30001. if (parsedMesh.instances) {
  30002. for (var index = 0; index < parsedMesh.instances.length; index++) {
  30003. var parsedInstance = parsedMesh.instances[index];
  30004. var instance = mesh.createInstance(parsedInstance.name);
  30005. if (parsedInstance.id) {
  30006. instance.id = parsedInstance.id;
  30007. }
  30008. if (BABYLON.Tags) {
  30009. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  30010. }
  30011. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  30012. if (parsedInstance.parentId) {
  30013. instance._waitingParentId = parsedInstance.parentId;
  30014. }
  30015. if (parsedInstance.rotationQuaternion) {
  30016. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  30017. }
  30018. else if (parsedInstance.rotation) {
  30019. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  30020. }
  30021. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  30022. instance.checkCollisions = mesh.checkCollisions;
  30023. if (parsedMesh.animations) {
  30024. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30025. parsedAnimation = parsedMesh.animations[animationIndex];
  30026. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30027. }
  30028. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  30029. }
  30030. }
  30031. }
  30032. return mesh;
  30033. };
  30034. /**
  30035. * Creates a ribbon mesh.
  30036. * Please consider using the same method from the MeshBuilder class instead.
  30037. * 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.
  30038. *
  30039. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  30040. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  30041. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  30042. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  30043. * 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.
  30044. * 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.
  30045. * 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
  30046. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30047. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30048. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30049. */
  30050. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  30051. if (closeArray === void 0) { closeArray = false; }
  30052. if (updatable === void 0) { updatable = false; }
  30053. return BABYLON.MeshBuilder.CreateRibbon(name, {
  30054. pathArray: pathArray,
  30055. closeArray: closeArray,
  30056. closePath: closePath,
  30057. offset: offset,
  30058. updatable: updatable,
  30059. sideOrientation: sideOrientation,
  30060. instance: instance
  30061. }, scene);
  30062. };
  30063. /**
  30064. * Creates a plane polygonal mesh. By default, this is a disc.
  30065. * Please consider using the same method from the MeshBuilder class instead.
  30066. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  30067. * 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.
  30068. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30069. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30070. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30071. */
  30072. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  30073. if (scene === void 0) { scene = null; }
  30074. var options = {
  30075. radius: radius,
  30076. tessellation: tessellation,
  30077. sideOrientation: sideOrientation,
  30078. updatable: updatable
  30079. };
  30080. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  30081. };
  30082. /**
  30083. * Creates a box mesh.
  30084. * Please consider using the same method from the MeshBuilder class instead.
  30085. * The parameter `size` sets the size (float) of each box side (default 1).
  30086. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30087. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30088. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30089. */
  30090. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  30091. if (scene === void 0) { scene = null; }
  30092. var options = {
  30093. size: size,
  30094. sideOrientation: sideOrientation,
  30095. updatable: updatable
  30096. };
  30097. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  30098. };
  30099. /**
  30100. * Creates a sphere mesh.
  30101. * Please consider using the same method from the MeshBuilder class instead.
  30102. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  30103. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  30104. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30105. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30106. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30107. */
  30108. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  30109. var options = {
  30110. segments: segments,
  30111. diameterX: diameter,
  30112. diameterY: diameter,
  30113. diameterZ: diameter,
  30114. sideOrientation: sideOrientation,
  30115. updatable: updatable
  30116. };
  30117. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  30118. };
  30119. /**
  30120. * Creates a cylinder or a cone mesh.
  30121. * Please consider using the same method from the MeshBuilder class instead.
  30122. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  30123. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  30124. * 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.
  30125. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  30126. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  30127. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30128. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30129. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30130. */
  30131. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  30132. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  30133. if (scene !== undefined) {
  30134. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  30135. updatable = scene;
  30136. }
  30137. scene = subdivisions;
  30138. subdivisions = 1;
  30139. }
  30140. var options = {
  30141. height: height,
  30142. diameterTop: diameterTop,
  30143. diameterBottom: diameterBottom,
  30144. tessellation: tessellation,
  30145. subdivisions: subdivisions,
  30146. sideOrientation: sideOrientation,
  30147. updatable: updatable
  30148. };
  30149. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  30150. };
  30151. // Torus (Code from SharpDX.org)
  30152. /**
  30153. * Creates a torus mesh.
  30154. * Please consider using the same method from the MeshBuilder class instead.
  30155. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  30156. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  30157. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  30158. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30159. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30160. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30161. */
  30162. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  30163. var options = {
  30164. diameter: diameter,
  30165. thickness: thickness,
  30166. tessellation: tessellation,
  30167. sideOrientation: sideOrientation,
  30168. updatable: updatable
  30169. };
  30170. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  30171. };
  30172. /**
  30173. * Creates a torus knot mesh.
  30174. * Please consider using the same method from the MeshBuilder class instead.
  30175. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  30176. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  30177. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  30178. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  30179. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30180. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30181. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30182. */
  30183. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  30184. var options = {
  30185. radius: radius,
  30186. tube: tube,
  30187. radialSegments: radialSegments,
  30188. tubularSegments: tubularSegments,
  30189. p: p,
  30190. q: q,
  30191. sideOrientation: sideOrientation,
  30192. updatable: updatable
  30193. };
  30194. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  30195. };
  30196. /**
  30197. * Creates a line mesh.
  30198. * Please consider using the same method from the MeshBuilder class instead.
  30199. * 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.
  30200. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30201. * The parameter `points` is an array successive Vector3.
  30202. * 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
  30203. * When updating an instance, remember that only point positions can change, not the number of points.
  30204. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30205. */
  30206. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  30207. if (scene === void 0) { scene = null; }
  30208. if (updatable === void 0) { updatable = false; }
  30209. if (instance === void 0) { instance = null; }
  30210. var options = {
  30211. points: points,
  30212. updatable: updatable,
  30213. instance: instance
  30214. };
  30215. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  30216. };
  30217. /**
  30218. * Creates a dashed line mesh.
  30219. * Please consider using the same method from the MeshBuilder class instead.
  30220. * 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.
  30221. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30222. * The parameter `points` is an array successive Vector3.
  30223. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  30224. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  30225. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  30226. * 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
  30227. * When updating an instance, remember that only point positions can change, not the number of points.
  30228. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30229. */
  30230. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  30231. if (scene === void 0) { scene = null; }
  30232. var options = {
  30233. points: points,
  30234. dashSize: dashSize,
  30235. gapSize: gapSize,
  30236. dashNb: dashNb,
  30237. updatable: updatable,
  30238. instance: instance
  30239. };
  30240. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  30241. };
  30242. /**
  30243. * Creates a polygon mesh.
  30244. * Please consider using the same method from the MeshBuilder class instead.
  30245. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  30246. * 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.
  30247. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30248. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30249. * Remember you can only change the shape positions, not their number when updating a polygon.
  30250. */
  30251. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  30252. var options = {
  30253. shape: shape,
  30254. holes: holes,
  30255. updatable: updatable,
  30256. sideOrientation: sideOrientation
  30257. };
  30258. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  30259. };
  30260. /**
  30261. * Creates an extruded polygon mesh, with depth in the Y direction.
  30262. * Please consider using the same method from the MeshBuilder class instead.
  30263. */
  30264. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  30265. var options = {
  30266. shape: shape,
  30267. holes: holes,
  30268. depth: depth,
  30269. updatable: updatable,
  30270. sideOrientation: sideOrientation
  30271. };
  30272. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  30273. };
  30274. /**
  30275. * Creates an extruded shape mesh.
  30276. * 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.
  30277. * Please consider using the same method from the MeshBuilder class instead.
  30278. *
  30279. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30280. * 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
  30281. * extruded along the Z axis.
  30282. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30283. * 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.
  30284. * The parameter `scale` (float, default 1) is the value to scale the shape.
  30285. * 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
  30286. * 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
  30287. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30288. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30289. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30290. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30291. */
  30292. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  30293. if (scene === void 0) { scene = null; }
  30294. var options = {
  30295. shape: shape,
  30296. path: path,
  30297. scale: scale,
  30298. rotation: rotation,
  30299. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30300. sideOrientation: sideOrientation,
  30301. instance: instance,
  30302. updatable: updatable
  30303. };
  30304. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  30305. };
  30306. /**
  30307. * Creates an custom extruded shape mesh.
  30308. * 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.
  30309. * Please consider using the same method from the MeshBuilder class instead.
  30310. *
  30311. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30312. * 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
  30313. * extruded along the Z axis.
  30314. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30315. * 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
  30316. * and the distance of this point from the begining of the path :
  30317. * ```javascript
  30318. * var rotationFunction = function(i, distance) {
  30319. * // do things
  30320. * return rotationValue; }
  30321. * ```
  30322. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30323. * 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
  30324. * and the distance of this point from the begining of the path :
  30325. * ```javascript
  30326. * var scaleFunction = function(i, distance) {
  30327. * // do things
  30328. * return scaleValue;}
  30329. * ```
  30330. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30331. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30332. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30333. * 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
  30334. * 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
  30335. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30336. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30337. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30338. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30339. */
  30340. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30341. var options = {
  30342. shape: shape,
  30343. path: path,
  30344. scaleFunction: scaleFunction,
  30345. rotationFunction: rotationFunction,
  30346. ribbonCloseArray: ribbonCloseArray,
  30347. ribbonClosePath: ribbonClosePath,
  30348. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30349. sideOrientation: sideOrientation,
  30350. instance: instance,
  30351. updatable: updatable
  30352. };
  30353. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30354. };
  30355. /**
  30356. * Creates lathe mesh.
  30357. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30358. * Please consider using the same method from the MeshBuilder class instead.
  30359. * 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
  30360. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30361. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30362. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30363. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30364. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30365. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30366. */
  30367. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30368. var options = {
  30369. shape: shape,
  30370. radius: radius,
  30371. tessellation: tessellation,
  30372. sideOrientation: sideOrientation,
  30373. updatable: updatable
  30374. };
  30375. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30376. };
  30377. /**
  30378. * Creates a plane mesh.
  30379. * Please consider using the same method from the MeshBuilder class instead.
  30380. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30381. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30382. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30383. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30384. */
  30385. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30386. var options = {
  30387. size: size,
  30388. width: size,
  30389. height: size,
  30390. sideOrientation: sideOrientation,
  30391. updatable: updatable
  30392. };
  30393. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30394. };
  30395. /**
  30396. * Creates a ground mesh.
  30397. * Please consider using the same method from the MeshBuilder class instead.
  30398. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30399. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30400. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30401. */
  30402. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30403. var options = {
  30404. width: width,
  30405. height: height,
  30406. subdivisions: subdivisions,
  30407. updatable: updatable
  30408. };
  30409. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30410. };
  30411. /**
  30412. * Creates a tiled ground mesh.
  30413. * Please consider using the same method from the MeshBuilder class instead.
  30414. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30415. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30416. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30417. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30418. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30419. * numbers of subdivisions on the ground width and height of each tile.
  30420. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30421. */
  30422. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30423. var options = {
  30424. xmin: xmin,
  30425. zmin: zmin,
  30426. xmax: xmax,
  30427. zmax: zmax,
  30428. subdivisions: subdivisions,
  30429. precision: precision,
  30430. updatable: updatable
  30431. };
  30432. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30433. };
  30434. /**
  30435. * Creates a ground mesh from a height map.
  30436. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30437. * Please consider using the same method from the MeshBuilder class instead.
  30438. * The parameter `url` sets the URL of the height map image resource.
  30439. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30440. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30441. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30442. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30443. * 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).
  30444. * This function is passed the newly built mesh :
  30445. * ```javascript
  30446. * function(mesh) { // do things
  30447. * return; }
  30448. * ```
  30449. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30450. */
  30451. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30452. var options = {
  30453. width: width,
  30454. height: height,
  30455. subdivisions: subdivisions,
  30456. minHeight: minHeight,
  30457. maxHeight: maxHeight,
  30458. updatable: updatable,
  30459. onReady: onReady
  30460. };
  30461. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30462. };
  30463. /**
  30464. * Creates a tube mesh.
  30465. * 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.
  30466. * Please consider using the same method from the MeshBuilder class instead.
  30467. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30468. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30469. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30470. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30471. * 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.
  30472. * It must return a radius value (positive float) :
  30473. * ```javascript
  30474. * var radiusFunction = function(i, distance) {
  30475. * // do things
  30476. * return radius; }
  30477. * ```
  30478. * 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
  30479. * 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
  30480. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30481. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30482. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30483. */
  30484. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30485. var options = {
  30486. path: path,
  30487. radius: radius,
  30488. tessellation: tessellation,
  30489. radiusFunction: radiusFunction,
  30490. arc: 1,
  30491. cap: cap,
  30492. updatable: updatable,
  30493. sideOrientation: sideOrientation,
  30494. instance: instance
  30495. };
  30496. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30497. };
  30498. /**
  30499. * Creates a polyhedron mesh.
  30500. * Please consider using the same method from the MeshBuilder class instead.
  30501. * 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
  30502. * to choose the wanted type.
  30503. * The parameter `size` (positive float, default 1) sets the polygon size.
  30504. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30505. * 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`.
  30506. * 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
  30507. * 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)`).
  30508. * 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
  30509. * 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.
  30510. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30511. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30513. */
  30514. Mesh.CreatePolyhedron = function (name, options, scene) {
  30515. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30516. };
  30517. /**
  30518. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30519. * Please consider using the same method from the MeshBuilder class instead.
  30520. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30521. * 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`).
  30522. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30523. * 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.
  30524. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30525. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30526. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30527. */
  30528. Mesh.CreateIcoSphere = function (name, options, scene) {
  30529. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30530. };
  30531. /**
  30532. * Creates a decal mesh.
  30533. * Please consider using the same method from the MeshBuilder class instead.
  30534. * 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.
  30535. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30536. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30537. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30538. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30539. */
  30540. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30541. var options = {
  30542. position: position,
  30543. normal: normal,
  30544. size: size,
  30545. angle: angle
  30546. };
  30547. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30548. };
  30549. // Skeletons
  30550. /**
  30551. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30552. */
  30553. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30554. if (!this._sourcePositions) {
  30555. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30556. if (!source) {
  30557. return this._sourcePositions;
  30558. }
  30559. this._sourcePositions = new Float32Array(source);
  30560. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30561. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30562. }
  30563. }
  30564. return this._sourcePositions;
  30565. };
  30566. /**
  30567. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30568. */
  30569. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30570. if (!this._sourceNormals) {
  30571. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30572. if (!source) {
  30573. return this._sourceNormals;
  30574. }
  30575. this._sourceNormals = new Float32Array(source);
  30576. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30577. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30578. }
  30579. }
  30580. return this._sourceNormals;
  30581. };
  30582. /**
  30583. * Updates the vertex buffer by applying transformation from the bones.
  30584. * Returns the Mesh.
  30585. *
  30586. * @param {skeleton} skeleton to apply
  30587. */
  30588. Mesh.prototype.applySkeleton = function (skeleton) {
  30589. if (!this.geometry) {
  30590. return this;
  30591. }
  30592. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30593. return this;
  30594. }
  30595. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30596. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30597. return this;
  30598. }
  30599. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30600. return this;
  30601. }
  30602. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30603. return this;
  30604. }
  30605. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30606. return this;
  30607. }
  30608. if (!this._sourcePositions) {
  30609. var submeshes = this.subMeshes.slice();
  30610. this.setPositionsForCPUSkinning();
  30611. this.subMeshes = submeshes;
  30612. }
  30613. if (!this._sourceNormals) {
  30614. this.setNormalsForCPUSkinning();
  30615. }
  30616. // positionsData checks for not being Float32Array will only pass at most once
  30617. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30618. if (!positionsData) {
  30619. return this;
  30620. }
  30621. if (!(positionsData instanceof Float32Array)) {
  30622. positionsData = new Float32Array(positionsData);
  30623. }
  30624. // normalsData checks for not being Float32Array will only pass at most once
  30625. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30626. if (!normalsData) {
  30627. return this;
  30628. }
  30629. if (!(normalsData instanceof Float32Array)) {
  30630. normalsData = new Float32Array(normalsData);
  30631. }
  30632. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30633. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30634. if (!matricesWeightsData || !matricesIndicesData) {
  30635. return this;
  30636. }
  30637. var needExtras = this.numBoneInfluencers > 4;
  30638. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30639. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30640. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30641. var tempVector3 = BABYLON.Vector3.Zero();
  30642. var finalMatrix = new BABYLON.Matrix();
  30643. var tempMatrix = new BABYLON.Matrix();
  30644. var matWeightIdx = 0;
  30645. var inf;
  30646. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30647. var weight;
  30648. for (inf = 0; inf < 4; inf++) {
  30649. weight = matricesWeightsData[matWeightIdx + inf];
  30650. if (weight > 0) {
  30651. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30652. finalMatrix.addToSelf(tempMatrix);
  30653. }
  30654. else
  30655. break;
  30656. }
  30657. if (needExtras) {
  30658. for (inf = 0; inf < 4; inf++) {
  30659. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30660. if (weight > 0) {
  30661. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30662. finalMatrix.addToSelf(tempMatrix);
  30663. }
  30664. else
  30665. break;
  30666. }
  30667. }
  30668. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30669. tempVector3.toArray(positionsData, index);
  30670. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30671. tempVector3.toArray(normalsData, index);
  30672. finalMatrix.reset();
  30673. }
  30674. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30675. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30676. return this;
  30677. };
  30678. // Tools
  30679. /**
  30680. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30681. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30682. */
  30683. Mesh.MinMax = function (meshes) {
  30684. var minVector = null;
  30685. var maxVector = null;
  30686. meshes.forEach(function (mesh, index, array) {
  30687. var boundingInfo = mesh.getBoundingInfo();
  30688. var boundingBox = boundingInfo.boundingBox;
  30689. if (!minVector || !maxVector) {
  30690. minVector = boundingBox.minimumWorld;
  30691. maxVector = boundingBox.maximumWorld;
  30692. }
  30693. else {
  30694. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30695. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30696. }
  30697. });
  30698. if (!minVector || !maxVector) {
  30699. return {
  30700. min: BABYLON.Vector3.Zero(),
  30701. max: BABYLON.Vector3.Zero()
  30702. };
  30703. }
  30704. return {
  30705. min: minVector,
  30706. max: maxVector
  30707. };
  30708. };
  30709. /**
  30710. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30711. */
  30712. Mesh.Center = function (meshesOrMinMaxVector) {
  30713. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30714. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30715. };
  30716. /**
  30717. * Merge the array of meshes into a single mesh for performance reasons.
  30718. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30719. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30720. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30721. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30722. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30723. */
  30724. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30725. if (disposeSource === void 0) { disposeSource = true; }
  30726. var index;
  30727. if (!allow32BitsIndices) {
  30728. var totalVertices = 0;
  30729. // Counting vertices
  30730. for (index = 0; index < meshes.length; index++) {
  30731. if (meshes[index]) {
  30732. totalVertices += meshes[index].getTotalVertices();
  30733. if (totalVertices > 65536) {
  30734. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30735. return null;
  30736. }
  30737. }
  30738. }
  30739. }
  30740. // Merge
  30741. var vertexData = null;
  30742. var otherVertexData;
  30743. var indiceArray = new Array();
  30744. var source = null;
  30745. for (index = 0; index < meshes.length; index++) {
  30746. if (meshes[index]) {
  30747. meshes[index].computeWorldMatrix(true);
  30748. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30749. otherVertexData.transform(meshes[index].getWorldMatrix());
  30750. if (vertexData) {
  30751. vertexData.merge(otherVertexData);
  30752. }
  30753. else {
  30754. vertexData = otherVertexData;
  30755. source = meshes[index];
  30756. }
  30757. if (subdivideWithSubMeshes) {
  30758. indiceArray.push(meshes[index].getTotalIndices());
  30759. }
  30760. }
  30761. }
  30762. source = source;
  30763. if (!meshSubclass) {
  30764. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30765. }
  30766. vertexData.applyToMesh(meshSubclass);
  30767. // Setting properties
  30768. meshSubclass.material = source.material;
  30769. meshSubclass.checkCollisions = source.checkCollisions;
  30770. // Cleaning
  30771. if (disposeSource) {
  30772. for (index = 0; index < meshes.length; index++) {
  30773. if (meshes[index]) {
  30774. meshes[index].dispose();
  30775. }
  30776. }
  30777. }
  30778. // Subdivide
  30779. if (subdivideWithSubMeshes) {
  30780. //-- Suppresions du submesh global
  30781. meshSubclass.releaseSubMeshes();
  30782. index = 0;
  30783. var offset = 0;
  30784. //-- aplique la subdivision en fonction du tableau d'indices
  30785. while (index < indiceArray.length) {
  30786. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30787. offset += indiceArray[index];
  30788. index++;
  30789. }
  30790. }
  30791. return meshSubclass;
  30792. };
  30793. // Consts
  30794. Mesh._FRONTSIDE = 0;
  30795. Mesh._BACKSIDE = 1;
  30796. Mesh._DOUBLESIDE = 2;
  30797. Mesh._DEFAULTSIDE = 0;
  30798. Mesh._NO_CAP = 0;
  30799. Mesh._CAP_START = 1;
  30800. Mesh._CAP_END = 2;
  30801. Mesh._CAP_ALL = 3;
  30802. return Mesh;
  30803. }(BABYLON.AbstractMesh));
  30804. BABYLON.Mesh = Mesh;
  30805. })(BABYLON || (BABYLON = {}));
  30806. //# sourceMappingURL=babylon.mesh.js.map
  30807. "use strict";
  30808. var BABYLON;
  30809. (function (BABYLON) {
  30810. var BaseSubMesh = /** @class */ (function () {
  30811. function BaseSubMesh() {
  30812. }
  30813. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30814. get: function () {
  30815. return this._materialEffect;
  30816. },
  30817. enumerable: true,
  30818. configurable: true
  30819. });
  30820. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30821. if (defines === void 0) { defines = null; }
  30822. if (this._materialEffect === effect) {
  30823. if (!effect) {
  30824. this._materialDefines = null;
  30825. }
  30826. return;
  30827. }
  30828. this._materialDefines = defines;
  30829. this._materialEffect = effect;
  30830. };
  30831. return BaseSubMesh;
  30832. }());
  30833. BABYLON.BaseSubMesh = BaseSubMesh;
  30834. var SubMesh = /** @class */ (function (_super) {
  30835. __extends(SubMesh, _super);
  30836. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30837. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30838. var _this = _super.call(this) || this;
  30839. _this.materialIndex = materialIndex;
  30840. _this.verticesStart = verticesStart;
  30841. _this.verticesCount = verticesCount;
  30842. _this.indexStart = indexStart;
  30843. _this.indexCount = indexCount;
  30844. _this._renderId = 0;
  30845. _this._mesh = mesh;
  30846. _this._renderingMesh = renderingMesh || mesh;
  30847. mesh.subMeshes.push(_this);
  30848. _this._trianglePlanes = [];
  30849. _this._id = mesh.subMeshes.length - 1;
  30850. if (createBoundingBox) {
  30851. _this.refreshBoundingInfo();
  30852. mesh.computeWorldMatrix(true);
  30853. }
  30854. return _this;
  30855. }
  30856. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30857. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30858. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30859. };
  30860. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30861. get: function () {
  30862. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30863. },
  30864. enumerable: true,
  30865. configurable: true
  30866. });
  30867. /**
  30868. * Returns the submesh BoudingInfo object.
  30869. */
  30870. SubMesh.prototype.getBoundingInfo = function () {
  30871. if (this.IsGlobal) {
  30872. return this._mesh.getBoundingInfo();
  30873. }
  30874. return this._boundingInfo;
  30875. };
  30876. /**
  30877. * Sets the submesh BoundingInfo.
  30878. * Return the SubMesh.
  30879. */
  30880. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30881. this._boundingInfo = boundingInfo;
  30882. return this;
  30883. };
  30884. /**
  30885. * Returns the mesh of the current submesh.
  30886. */
  30887. SubMesh.prototype.getMesh = function () {
  30888. return this._mesh;
  30889. };
  30890. /**
  30891. * Returns the rendering mesh of the submesh.
  30892. */
  30893. SubMesh.prototype.getRenderingMesh = function () {
  30894. return this._renderingMesh;
  30895. };
  30896. /**
  30897. * Returns the submesh material.
  30898. */
  30899. SubMesh.prototype.getMaterial = function () {
  30900. var rootMaterial = this._renderingMesh.material;
  30901. if (rootMaterial === null || rootMaterial === undefined) {
  30902. return this._mesh.getScene().defaultMaterial;
  30903. }
  30904. else if (rootMaterial.getSubMaterial) {
  30905. var multiMaterial = rootMaterial;
  30906. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30907. if (this._currentMaterial !== effectiveMaterial) {
  30908. this._currentMaterial = effectiveMaterial;
  30909. this._materialDefines = null;
  30910. }
  30911. return effectiveMaterial;
  30912. }
  30913. return rootMaterial;
  30914. };
  30915. // Methods
  30916. /**
  30917. * Sets a new updated BoundingInfo object to the submesh.
  30918. * Returns the SubMesh.
  30919. */
  30920. SubMesh.prototype.refreshBoundingInfo = function () {
  30921. this._lastColliderWorldVertices = null;
  30922. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30923. return this;
  30924. }
  30925. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30926. if (!data) {
  30927. this._boundingInfo = this._mesh.getBoundingInfo();
  30928. return this;
  30929. }
  30930. var indices = this._renderingMesh.getIndices();
  30931. var extend;
  30932. //is this the only submesh?
  30933. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30934. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30935. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30936. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30937. }
  30938. else {
  30939. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30940. }
  30941. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30942. return this;
  30943. };
  30944. SubMesh.prototype._checkCollision = function (collider) {
  30945. var boundingInfo = this.getBoundingInfo();
  30946. return boundingInfo._checkCollision(collider);
  30947. };
  30948. /**
  30949. * Updates the submesh BoundingInfo.
  30950. * Returns the Submesh.
  30951. */
  30952. SubMesh.prototype.updateBoundingInfo = function (world) {
  30953. var boundingInfo = this.getBoundingInfo();
  30954. if (!boundingInfo) {
  30955. this.refreshBoundingInfo();
  30956. boundingInfo = this.getBoundingInfo();
  30957. }
  30958. boundingInfo.update(world);
  30959. return this;
  30960. };
  30961. /**
  30962. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30963. * Boolean returned.
  30964. */
  30965. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30966. var boundingInfo = this.getBoundingInfo();
  30967. if (!boundingInfo) {
  30968. return false;
  30969. }
  30970. return boundingInfo.isInFrustum(frustumPlanes);
  30971. };
  30972. /**
  30973. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30974. * Boolean returned.
  30975. */
  30976. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30977. var boundingInfo = this.getBoundingInfo();
  30978. if (!boundingInfo) {
  30979. return false;
  30980. }
  30981. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30982. };
  30983. /**
  30984. * Renders the submesh.
  30985. * Returns it.
  30986. */
  30987. SubMesh.prototype.render = function (enableAlphaMode) {
  30988. this._renderingMesh.render(this, enableAlphaMode);
  30989. return this;
  30990. };
  30991. /**
  30992. * Returns a new Index Buffer.
  30993. * Type returned : WebGLBuffer.
  30994. */
  30995. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30996. if (!this._linesIndexBuffer) {
  30997. var linesIndices = [];
  30998. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30999. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  31000. }
  31001. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  31002. this.linesIndexCount = linesIndices.length;
  31003. }
  31004. return this._linesIndexBuffer;
  31005. };
  31006. /**
  31007. * True is the passed Ray intersects the submesh bounding box.
  31008. * Boolean returned.
  31009. */
  31010. SubMesh.prototype.canIntersects = function (ray) {
  31011. var boundingInfo = this.getBoundingInfo();
  31012. if (!boundingInfo) {
  31013. return false;
  31014. }
  31015. return ray.intersectsBox(boundingInfo.boundingBox);
  31016. };
  31017. /**
  31018. * Returns an object IntersectionInfo.
  31019. */
  31020. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  31021. var intersectInfo = null;
  31022. var material = this.getMaterial();
  31023. if (!material) {
  31024. return null;
  31025. }
  31026. switch (material.fillMode) {
  31027. case BABYLON.Material.PointListDrawMode:
  31028. case BABYLON.Material.LineListDrawMode:
  31029. case BABYLON.Material.LineLoopDrawMode:
  31030. case BABYLON.Material.LineStripDrawMode:
  31031. case BABYLON.Material.TriangleFanDrawMode:
  31032. case BABYLON.Material.TriangleStripDrawMode:
  31033. return null;
  31034. }
  31035. // LineMesh first as it's also a Mesh...
  31036. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  31037. var lineMesh = this._mesh;
  31038. // Line test
  31039. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  31040. var p0 = positions[indices[index]];
  31041. var p1 = positions[indices[index + 1]];
  31042. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  31043. if (length < 0) {
  31044. continue;
  31045. }
  31046. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  31047. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  31048. if (fastCheck) {
  31049. break;
  31050. }
  31051. }
  31052. }
  31053. }
  31054. else {
  31055. // Triangles test
  31056. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31057. var p0 = positions[indices[index]];
  31058. var p1 = positions[indices[index + 1]];
  31059. var p2 = positions[indices[index + 2]];
  31060. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  31061. if (currentIntersectInfo) {
  31062. if (currentIntersectInfo.distance < 0) {
  31063. continue;
  31064. }
  31065. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  31066. intersectInfo = currentIntersectInfo;
  31067. intersectInfo.faceId = index / 3;
  31068. if (fastCheck) {
  31069. break;
  31070. }
  31071. }
  31072. }
  31073. }
  31074. }
  31075. return intersectInfo;
  31076. };
  31077. SubMesh.prototype._rebuild = function () {
  31078. if (this._linesIndexBuffer) {
  31079. this._linesIndexBuffer = null;
  31080. }
  31081. };
  31082. // Clone
  31083. /**
  31084. * Creates a new Submesh from the passed Mesh.
  31085. */
  31086. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  31087. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  31088. if (!this.IsGlobal) {
  31089. var boundingInfo = this.getBoundingInfo();
  31090. if (!boundingInfo) {
  31091. return result;
  31092. }
  31093. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  31094. }
  31095. return result;
  31096. };
  31097. // Dispose
  31098. /**
  31099. * Disposes the Submesh.
  31100. * Returns nothing.
  31101. */
  31102. SubMesh.prototype.dispose = function () {
  31103. if (this._linesIndexBuffer) {
  31104. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  31105. this._linesIndexBuffer = null;
  31106. }
  31107. // Remove from mesh
  31108. var index = this._mesh.subMeshes.indexOf(this);
  31109. this._mesh.subMeshes.splice(index, 1);
  31110. };
  31111. // Statics
  31112. /**
  31113. * Creates a new Submesh from the passed parameters :
  31114. * - materialIndex (integer) : the index of the main mesh material.
  31115. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  31116. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  31117. * - mesh (Mesh) : the main mesh to create the submesh from.
  31118. * - renderingMesh (optional Mesh) : rendering mesh.
  31119. */
  31120. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  31121. var minVertexIndex = Number.MAX_VALUE;
  31122. var maxVertexIndex = -Number.MAX_VALUE;
  31123. renderingMesh = (renderingMesh || mesh);
  31124. var indices = renderingMesh.getIndices();
  31125. for (var index = startIndex; index < startIndex + indexCount; index++) {
  31126. var vertexIndex = indices[index];
  31127. if (vertexIndex < minVertexIndex)
  31128. minVertexIndex = vertexIndex;
  31129. if (vertexIndex > maxVertexIndex)
  31130. maxVertexIndex = vertexIndex;
  31131. }
  31132. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  31133. };
  31134. return SubMesh;
  31135. }(BaseSubMesh));
  31136. BABYLON.SubMesh = SubMesh;
  31137. })(BABYLON || (BABYLON = {}));
  31138. //# sourceMappingURL=babylon.subMesh.js.map
  31139. "use strict";
  31140. var __assign = (this && this.__assign) || Object.assign || function(t) {
  31141. for (var s, i = 1, n = arguments.length; i < n; i++) {
  31142. s = arguments[i];
  31143. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  31144. t[p] = s[p];
  31145. }
  31146. return t;
  31147. };
  31148. var BABYLON;
  31149. (function (BABYLON) {
  31150. /**
  31151. * Manages the defines for the Material.
  31152. */
  31153. var MaterialDefines = /** @class */ (function () {
  31154. function MaterialDefines() {
  31155. this._isDirty = true;
  31156. this._areLightsDirty = true;
  31157. this._areAttributesDirty = true;
  31158. this._areTexturesDirty = true;
  31159. this._areFresnelDirty = true;
  31160. this._areMiscDirty = true;
  31161. this._areImageProcessingDirty = true;
  31162. this._normals = false;
  31163. this._uvs = false;
  31164. this._needNormals = false;
  31165. this._needUVs = false;
  31166. }
  31167. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  31168. /**
  31169. * Specifies if the material needs to be re-calculated.
  31170. */
  31171. get: function () {
  31172. return this._isDirty;
  31173. },
  31174. enumerable: true,
  31175. configurable: true
  31176. });
  31177. /**
  31178. * Marks the material to indicate that it has been re-calculated.
  31179. */
  31180. MaterialDefines.prototype.markAsProcessed = function () {
  31181. this._isDirty = false;
  31182. this._areAttributesDirty = false;
  31183. this._areTexturesDirty = false;
  31184. this._areFresnelDirty = false;
  31185. this._areLightsDirty = false;
  31186. this._areMiscDirty = false;
  31187. this._areImageProcessingDirty = false;
  31188. };
  31189. /**
  31190. * Marks the material to indicate that it needs to be re-calculated.
  31191. */
  31192. MaterialDefines.prototype.markAsUnprocessed = function () {
  31193. this._isDirty = true;
  31194. };
  31195. /**
  31196. * Marks the material to indicate all of its defines need to be re-calculated.
  31197. */
  31198. MaterialDefines.prototype.markAllAsDirty = function () {
  31199. this._areTexturesDirty = true;
  31200. this._areAttributesDirty = true;
  31201. this._areLightsDirty = true;
  31202. this._areFresnelDirty = true;
  31203. this._areMiscDirty = true;
  31204. this._areImageProcessingDirty = true;
  31205. this._isDirty = true;
  31206. };
  31207. /**
  31208. * Marks the material to indicate that image processing needs to be re-calculated.
  31209. */
  31210. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  31211. this._areImageProcessingDirty = true;
  31212. this._isDirty = true;
  31213. };
  31214. /**
  31215. * Marks the material to indicate the lights need to be re-calculated.
  31216. */
  31217. MaterialDefines.prototype.markAsLightDirty = function () {
  31218. this._areLightsDirty = true;
  31219. this._isDirty = true;
  31220. };
  31221. /**
  31222. * Marks the attribute state as changed.
  31223. */
  31224. MaterialDefines.prototype.markAsAttributesDirty = function () {
  31225. this._areAttributesDirty = true;
  31226. this._isDirty = true;
  31227. };
  31228. /**
  31229. * Marks the texture state as changed.
  31230. */
  31231. MaterialDefines.prototype.markAsTexturesDirty = function () {
  31232. this._areTexturesDirty = true;
  31233. this._isDirty = true;
  31234. };
  31235. /**
  31236. * Marks the fresnel state as changed.
  31237. */
  31238. MaterialDefines.prototype.markAsFresnelDirty = function () {
  31239. this._areFresnelDirty = true;
  31240. this._isDirty = true;
  31241. };
  31242. /**
  31243. * Marks the misc state as changed.
  31244. */
  31245. MaterialDefines.prototype.markAsMiscDirty = function () {
  31246. this._areMiscDirty = true;
  31247. this._isDirty = true;
  31248. };
  31249. /**
  31250. * Rebuilds the material defines.
  31251. */
  31252. MaterialDefines.prototype.rebuild = function () {
  31253. if (this._keys) {
  31254. delete this._keys;
  31255. }
  31256. this._keys = [];
  31257. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  31258. var key = _a[_i];
  31259. if (key[0] === "_") {
  31260. continue;
  31261. }
  31262. this._keys.push(key);
  31263. }
  31264. };
  31265. /**
  31266. * Specifies if two material defines are equal.
  31267. * @param other - A material define instance to compare to.
  31268. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  31269. */
  31270. MaterialDefines.prototype.isEqual = function (other) {
  31271. if (this._keys.length !== other._keys.length) {
  31272. return false;
  31273. }
  31274. for (var index = 0; index < this._keys.length; index++) {
  31275. var prop = this._keys[index];
  31276. if (this[prop] !== other[prop]) {
  31277. return false;
  31278. }
  31279. }
  31280. return true;
  31281. };
  31282. /**
  31283. * Clones this instance's defines to another instance.
  31284. * @param other - material defines to clone values to.
  31285. */
  31286. MaterialDefines.prototype.cloneTo = function (other) {
  31287. if (this._keys.length !== other._keys.length) {
  31288. other._keys = this._keys.slice(0);
  31289. }
  31290. for (var index = 0; index < this._keys.length; index++) {
  31291. var prop = this._keys[index];
  31292. other[prop] = this[prop];
  31293. }
  31294. };
  31295. /**
  31296. * Resets the material define values.
  31297. */
  31298. MaterialDefines.prototype.reset = function () {
  31299. for (var index = 0; index < this._keys.length; index++) {
  31300. var prop = this._keys[index];
  31301. var type = typeof this[prop];
  31302. switch (type) {
  31303. case "number":
  31304. this[prop] = 0;
  31305. break;
  31306. case "string":
  31307. this[prop] = "";
  31308. break;
  31309. default:
  31310. this[prop] = false;
  31311. break;
  31312. }
  31313. }
  31314. };
  31315. /**
  31316. * Converts the material define values to a string.
  31317. * @returns - String of material define information.
  31318. */
  31319. MaterialDefines.prototype.toString = function () {
  31320. var result = "";
  31321. for (var index = 0; index < this._keys.length; index++) {
  31322. var prop = this._keys[index];
  31323. var value = this[prop];
  31324. var type = typeof value;
  31325. switch (type) {
  31326. case "number":
  31327. case "string":
  31328. result += "#define " + prop + " " + value + "\n";
  31329. break;
  31330. default:
  31331. if (value) {
  31332. result += "#define " + prop + "\n";
  31333. }
  31334. break;
  31335. }
  31336. }
  31337. return result;
  31338. };
  31339. return MaterialDefines;
  31340. }());
  31341. BABYLON.MaterialDefines = MaterialDefines;
  31342. /**
  31343. * This offers the main features of a material in BJS.
  31344. */
  31345. var Material = /** @class */ (function () {
  31346. /**
  31347. * Creates a material instance.
  31348. * @param name - The name of the material.
  31349. * @param scene - The BJS scene to reference.
  31350. * @param doNotAdd - Specifies if the material should be added to the scene.
  31351. */
  31352. function Material(name, scene, doNotAdd) {
  31353. /**
  31354. * Specifies if the ready state should be checked on each call.
  31355. */
  31356. this.checkReadyOnEveryCall = false;
  31357. /**
  31358. * Specifies if the ready state should be checked once.
  31359. */
  31360. this.checkReadyOnlyOnce = false;
  31361. /**
  31362. * The state of the material.
  31363. */
  31364. this.state = "";
  31365. /**
  31366. * The alpha value of the material.
  31367. */
  31368. this._alpha = 1.0;
  31369. /**
  31370. * Specifies if back face culling is enabled.
  31371. */
  31372. this._backFaceCulling = true;
  31373. /**
  31374. * Specifies if the material should be serialized.
  31375. */
  31376. this.doNotSerialize = false;
  31377. /**
  31378. * Specifies if the effect should be stored on sub meshes.
  31379. */
  31380. this.storeEffectOnSubMeshes = false;
  31381. /**
  31382. * An event triggered when the material is disposed.
  31383. * @type {BABYLON.Observable}
  31384. */
  31385. this.onDisposeObservable = new BABYLON.Observable();
  31386. /**
  31387. * An event triggered when the material is bound.
  31388. * @type {BABYLON.Observable}
  31389. */
  31390. this.onBindObservable = new BABYLON.Observable();
  31391. /**
  31392. * An event triggered when the material is unbound.
  31393. * @type {BABYLON.Observable}
  31394. */
  31395. this.onUnBindObservable = new BABYLON.Observable();
  31396. /**
  31397. * Stores the value of the alpha mode.
  31398. */
  31399. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31400. /**
  31401. * Stores the state of the need depth pre-pass value.
  31402. */
  31403. this._needDepthPrePass = false;
  31404. /**
  31405. * Specifies if depth writing should be disabled.
  31406. */
  31407. this.disableDepthWrite = false;
  31408. /**
  31409. * Specifies if depth writing should be forced.
  31410. */
  31411. this.forceDepthWrite = false;
  31412. /**
  31413. * Specifies if there should be a separate pass for culling.
  31414. */
  31415. this.separateCullingPass = false;
  31416. /**
  31417. * Stores the state specifing if fog should be enabled.
  31418. */
  31419. this._fogEnabled = true;
  31420. /**
  31421. * Stores the size of points.
  31422. */
  31423. this.pointSize = 1.0;
  31424. /**
  31425. * Stores the z offset value.
  31426. */
  31427. this.zOffset = 0;
  31428. /**
  31429. * Specifies if the material was previously ready.
  31430. */
  31431. this._wasPreviouslyReady = false;
  31432. /**
  31433. * Stores the fill mode state.
  31434. */
  31435. this._fillMode = Material.TriangleFillMode;
  31436. this.name = name;
  31437. this.id = name || BABYLON.Tools.RandomId();
  31438. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31439. if (this._scene.useRightHandedSystem) {
  31440. this.sideOrientation = Material.ClockWiseSideOrientation;
  31441. }
  31442. else {
  31443. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31444. }
  31445. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31446. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31447. if (!doNotAdd) {
  31448. this._scene.materials.push(this);
  31449. }
  31450. }
  31451. Object.defineProperty(Material, "TriangleFillMode", {
  31452. /**
  31453. * Returns the triangle fill mode.
  31454. */
  31455. get: function () {
  31456. return Material._TriangleFillMode;
  31457. },
  31458. enumerable: true,
  31459. configurable: true
  31460. });
  31461. Object.defineProperty(Material, "WireFrameFillMode", {
  31462. /**
  31463. * Returns the wireframe mode.
  31464. */
  31465. get: function () {
  31466. return Material._WireFrameFillMode;
  31467. },
  31468. enumerable: true,
  31469. configurable: true
  31470. });
  31471. Object.defineProperty(Material, "PointFillMode", {
  31472. /**
  31473. * Returns the point fill mode.
  31474. */
  31475. get: function () {
  31476. return Material._PointFillMode;
  31477. },
  31478. enumerable: true,
  31479. configurable: true
  31480. });
  31481. Object.defineProperty(Material, "PointListDrawMode", {
  31482. /**
  31483. * Returns the point list draw mode.
  31484. */
  31485. get: function () {
  31486. return Material._PointListDrawMode;
  31487. },
  31488. enumerable: true,
  31489. configurable: true
  31490. });
  31491. Object.defineProperty(Material, "LineListDrawMode", {
  31492. /**
  31493. * Returns the line list draw mode.
  31494. */
  31495. get: function () {
  31496. return Material._LineListDrawMode;
  31497. },
  31498. enumerable: true,
  31499. configurable: true
  31500. });
  31501. Object.defineProperty(Material, "LineLoopDrawMode", {
  31502. /**
  31503. * Returns the line loop draw mode.
  31504. */
  31505. get: function () {
  31506. return Material._LineLoopDrawMode;
  31507. },
  31508. enumerable: true,
  31509. configurable: true
  31510. });
  31511. Object.defineProperty(Material, "LineStripDrawMode", {
  31512. /**
  31513. * Returns the line strip draw mode.
  31514. */
  31515. get: function () {
  31516. return Material._LineStripDrawMode;
  31517. },
  31518. enumerable: true,
  31519. configurable: true
  31520. });
  31521. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31522. /**
  31523. * Returns the triangle strip draw mode.
  31524. */
  31525. get: function () {
  31526. return Material._TriangleStripDrawMode;
  31527. },
  31528. enumerable: true,
  31529. configurable: true
  31530. });
  31531. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31532. /**
  31533. * Returns the triangle fan draw mode.
  31534. */
  31535. get: function () {
  31536. return Material._TriangleFanDrawMode;
  31537. },
  31538. enumerable: true,
  31539. configurable: true
  31540. });
  31541. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31542. /**
  31543. * Returns the clock-wise side orientation.
  31544. */
  31545. get: function () {
  31546. return Material._ClockWiseSideOrientation;
  31547. },
  31548. enumerable: true,
  31549. configurable: true
  31550. });
  31551. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31552. /**
  31553. * Returns the counter clock-wise side orientation.
  31554. */
  31555. get: function () {
  31556. return Material._CounterClockWiseSideOrientation;
  31557. },
  31558. enumerable: true,
  31559. configurable: true
  31560. });
  31561. Object.defineProperty(Material, "TextureDirtyFlag", {
  31562. /**
  31563. * Returns the dirty texture flag value.
  31564. */
  31565. get: function () {
  31566. return Material._TextureDirtyFlag;
  31567. },
  31568. enumerable: true,
  31569. configurable: true
  31570. });
  31571. Object.defineProperty(Material, "LightDirtyFlag", {
  31572. /**
  31573. * Returns the dirty light flag value.
  31574. */
  31575. get: function () {
  31576. return Material._LightDirtyFlag;
  31577. },
  31578. enumerable: true,
  31579. configurable: true
  31580. });
  31581. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31582. /**
  31583. * Returns the dirty fresnel flag value.
  31584. */
  31585. get: function () {
  31586. return Material._FresnelDirtyFlag;
  31587. },
  31588. enumerable: true,
  31589. configurable: true
  31590. });
  31591. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31592. /**
  31593. * Returns the dirty attributes flag value.
  31594. */
  31595. get: function () {
  31596. return Material._AttributesDirtyFlag;
  31597. },
  31598. enumerable: true,
  31599. configurable: true
  31600. });
  31601. Object.defineProperty(Material, "MiscDirtyFlag", {
  31602. /**
  31603. * Returns the dirty misc flag value.
  31604. */
  31605. get: function () {
  31606. return Material._MiscDirtyFlag;
  31607. },
  31608. enumerable: true,
  31609. configurable: true
  31610. });
  31611. Object.defineProperty(Material.prototype, "alpha", {
  31612. /**
  31613. * Gets the alpha value of the material.
  31614. */
  31615. get: function () {
  31616. return this._alpha;
  31617. },
  31618. /**
  31619. * Sets the alpha value of the material.
  31620. */
  31621. set: function (value) {
  31622. if (this._alpha === value) {
  31623. return;
  31624. }
  31625. this._alpha = value;
  31626. this.markAsDirty(Material.MiscDirtyFlag);
  31627. },
  31628. enumerable: true,
  31629. configurable: true
  31630. });
  31631. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31632. /**
  31633. * Gets the back-face culling state.
  31634. */
  31635. get: function () {
  31636. return this._backFaceCulling;
  31637. },
  31638. /**
  31639. * Sets the back-face culling state.
  31640. */
  31641. set: function (value) {
  31642. if (this._backFaceCulling === value) {
  31643. return;
  31644. }
  31645. this._backFaceCulling = value;
  31646. this.markAsDirty(Material.TextureDirtyFlag);
  31647. },
  31648. enumerable: true,
  31649. configurable: true
  31650. });
  31651. Object.defineProperty(Material.prototype, "onDispose", {
  31652. /**
  31653. * Called during a dispose event.
  31654. */
  31655. set: function (callback) {
  31656. if (this._onDisposeObserver) {
  31657. this.onDisposeObservable.remove(this._onDisposeObserver);
  31658. }
  31659. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31660. },
  31661. enumerable: true,
  31662. configurable: true
  31663. });
  31664. Object.defineProperty(Material.prototype, "onBind", {
  31665. /**
  31666. * Called during a bind event.
  31667. */
  31668. set: function (callback) {
  31669. if (this._onBindObserver) {
  31670. this.onBindObservable.remove(this._onBindObserver);
  31671. }
  31672. this._onBindObserver = this.onBindObservable.add(callback);
  31673. },
  31674. enumerable: true,
  31675. configurable: true
  31676. });
  31677. Object.defineProperty(Material.prototype, "alphaMode", {
  31678. /**
  31679. * Gets the value of the alpha mode.
  31680. */
  31681. get: function () {
  31682. return this._alphaMode;
  31683. },
  31684. /**
  31685. * Sets the value of the alpha mode.
  31686. *
  31687. * | Value | Type | Description |
  31688. * | --- | --- | --- |
  31689. * | 0 | ALPHA_DISABLE | |
  31690. * | 1 | ALPHA_ADD | |
  31691. * | 2 | ALPHA_COMBINE | |
  31692. * | 3 | ALPHA_SUBTRACT | |
  31693. * | 4 | ALPHA_MULTIPLY | |
  31694. * | 5 | ALPHA_MAXIMIZED | |
  31695. * | 6 | ALPHA_ONEONE | |
  31696. * | 7 | ALPHA_PREMULTIPLIED | |
  31697. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  31698. * | 9 | ALPHA_INTERPOLATE | |
  31699. * | 10 | ALPHA_SCREENMODE | |
  31700. *
  31701. */
  31702. set: function (value) {
  31703. if (this._alphaMode === value) {
  31704. return;
  31705. }
  31706. this._alphaMode = value;
  31707. this.markAsDirty(Material.TextureDirtyFlag);
  31708. },
  31709. enumerable: true,
  31710. configurable: true
  31711. });
  31712. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31713. /**
  31714. * Gets the depth pre-pass value.
  31715. */
  31716. get: function () {
  31717. return this._needDepthPrePass;
  31718. },
  31719. /**
  31720. * Sets the need depth pre-pass value.
  31721. */
  31722. set: function (value) {
  31723. if (this._needDepthPrePass === value) {
  31724. return;
  31725. }
  31726. this._needDepthPrePass = value;
  31727. if (this._needDepthPrePass) {
  31728. this.checkReadyOnEveryCall = true;
  31729. }
  31730. },
  31731. enumerable: true,
  31732. configurable: true
  31733. });
  31734. Object.defineProperty(Material.prototype, "fogEnabled", {
  31735. /**
  31736. * Gets the value of the fog enabled state.
  31737. */
  31738. get: function () {
  31739. return this._fogEnabled;
  31740. },
  31741. /**
  31742. * Sets the state for enabling fog.
  31743. */
  31744. set: function (value) {
  31745. if (this._fogEnabled === value) {
  31746. return;
  31747. }
  31748. this._fogEnabled = value;
  31749. this.markAsDirty(Material.MiscDirtyFlag);
  31750. },
  31751. enumerable: true,
  31752. configurable: true
  31753. });
  31754. Object.defineProperty(Material.prototype, "wireframe", {
  31755. /**
  31756. * Gets a value specifying if wireframe mode is enabled.
  31757. */
  31758. get: function () {
  31759. switch (this._fillMode) {
  31760. case Material.WireFrameFillMode:
  31761. case Material.LineListDrawMode:
  31762. case Material.LineLoopDrawMode:
  31763. case Material.LineStripDrawMode:
  31764. return true;
  31765. }
  31766. return this._scene.forceWireframe;
  31767. },
  31768. /**
  31769. * Sets the state of wireframe mode.
  31770. */
  31771. set: function (value) {
  31772. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31773. },
  31774. enumerable: true,
  31775. configurable: true
  31776. });
  31777. Object.defineProperty(Material.prototype, "pointsCloud", {
  31778. /**
  31779. * Gets the value specifying if point clouds are enabled.
  31780. */
  31781. get: function () {
  31782. switch (this._fillMode) {
  31783. case Material.PointFillMode:
  31784. case Material.PointListDrawMode:
  31785. return true;
  31786. }
  31787. return this._scene.forcePointsCloud;
  31788. },
  31789. /**
  31790. * Sets the state of point cloud mode.
  31791. */
  31792. set: function (value) {
  31793. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31794. },
  31795. enumerable: true,
  31796. configurable: true
  31797. });
  31798. Object.defineProperty(Material.prototype, "fillMode", {
  31799. /**
  31800. * Gets the material fill mode.
  31801. */
  31802. get: function () {
  31803. return this._fillMode;
  31804. },
  31805. /**
  31806. * Sets the material fill mode.
  31807. */
  31808. set: function (value) {
  31809. if (this._fillMode === value) {
  31810. return;
  31811. }
  31812. this._fillMode = value;
  31813. this.markAsDirty(Material.MiscDirtyFlag);
  31814. },
  31815. enumerable: true,
  31816. configurable: true
  31817. });
  31818. /**
  31819. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31820. * subclasses should override adding information pertainent to themselves.
  31821. * @returns - String with material information.
  31822. */
  31823. Material.prototype.toString = function (fullDetails) {
  31824. var ret = "Name: " + this.name;
  31825. if (fullDetails) {
  31826. }
  31827. return ret;
  31828. };
  31829. /**
  31830. * Gets the class name of the material.
  31831. * @returns - String with the class name of the material.
  31832. */
  31833. Material.prototype.getClassName = function () {
  31834. return "Material";
  31835. };
  31836. Object.defineProperty(Material.prototype, "isFrozen", {
  31837. /**
  31838. * Specifies if updates for the material been locked.
  31839. */
  31840. get: function () {
  31841. return this.checkReadyOnlyOnce;
  31842. },
  31843. enumerable: true,
  31844. configurable: true
  31845. });
  31846. /**
  31847. * Locks updates for the material.
  31848. */
  31849. Material.prototype.freeze = function () {
  31850. this.checkReadyOnlyOnce = true;
  31851. };
  31852. /**
  31853. * Unlocks updates for the material.
  31854. */
  31855. Material.prototype.unfreeze = function () {
  31856. this.checkReadyOnlyOnce = false;
  31857. };
  31858. /**
  31859. * Specifies if the material is ready to be used.
  31860. * @param mesh - BJS mesh.
  31861. * @param useInstances - Specifies if instances should be used.
  31862. * @returns - Boolean indicating if the material is ready to be used.
  31863. */
  31864. Material.prototype.isReady = function (mesh, useInstances) {
  31865. return true;
  31866. };
  31867. /**
  31868. * Specifies that the submesh is ready to be used.
  31869. * @param mesh - BJS mesh.
  31870. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31871. * @param useInstances - Specifies that instances should be used.
  31872. * @returns - boolean indicating that the submesh is ready or not.
  31873. */
  31874. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31875. return false;
  31876. };
  31877. /**
  31878. * Returns the material effect.
  31879. * @returns - Nullable material effect.
  31880. */
  31881. Material.prototype.getEffect = function () {
  31882. return this._effect;
  31883. };
  31884. /**
  31885. * Returns the BJS scene.
  31886. * @returns - BJS Scene.
  31887. */
  31888. Material.prototype.getScene = function () {
  31889. return this._scene;
  31890. };
  31891. /**
  31892. * Specifies if the material will require alpha blending
  31893. * @returns - Boolean specifying if alpha blending is needed.
  31894. */
  31895. Material.prototype.needAlphaBlending = function () {
  31896. return (this.alpha < 1.0);
  31897. };
  31898. /**
  31899. * Specifies if the mesh will require alpha blending.
  31900. * @param mesh - BJS mesh.
  31901. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31902. */
  31903. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31904. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31905. };
  31906. /**
  31907. * Specifies if this material should be rendered in alpha test mode.
  31908. * @returns - Boolean specifying if an alpha test is needed.
  31909. */
  31910. Material.prototype.needAlphaTesting = function () {
  31911. return false;
  31912. };
  31913. /**
  31914. * Gets the texture used for the alpha test.
  31915. * @returns - Nullable alpha test texture.
  31916. */
  31917. Material.prototype.getAlphaTestTexture = function () {
  31918. return null;
  31919. };
  31920. /**
  31921. * Marks the material to indicate that it needs to be re-calculated.
  31922. */
  31923. Material.prototype.markDirty = function () {
  31924. this._wasPreviouslyReady = false;
  31925. };
  31926. Material.prototype._preBind = function (effect, overrideOrientation) {
  31927. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31928. var engine = this._scene.getEngine();
  31929. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31930. var reverse = orientation === Material.ClockWiseSideOrientation;
  31931. engine.enableEffect(effect ? effect : this._effect);
  31932. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31933. return reverse;
  31934. };
  31935. /**
  31936. * Binds the material to the mesh.
  31937. * @param world - World transformation matrix.
  31938. * @param mesh - Mesh to bind the material to.
  31939. */
  31940. Material.prototype.bind = function (world, mesh) {
  31941. };
  31942. /**
  31943. * Binds the submesh to the material.
  31944. * @param world - World transformation matrix.
  31945. * @param mesh - Mesh containing the submesh.
  31946. * @param subMesh - Submesh to bind the material to.
  31947. */
  31948. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31949. };
  31950. /**
  31951. * Binds the world matrix to the material.
  31952. * @param world - World transformation matrix.
  31953. */
  31954. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31955. };
  31956. /**
  31957. * Binds the scene's uniform buffer to the effect.
  31958. * @param effect - Effect to bind to the scene uniform buffer.
  31959. * @param sceneUbo - Scene uniform buffer.
  31960. */
  31961. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31962. sceneUbo.bindToEffect(effect, "Scene");
  31963. };
  31964. /**
  31965. * Binds the view matrix to the effect.
  31966. * @param effect - Effect to bind the view matrix to.
  31967. */
  31968. Material.prototype.bindView = function (effect) {
  31969. if (!this._useUBO) {
  31970. effect.setMatrix("view", this.getScene().getViewMatrix());
  31971. }
  31972. else {
  31973. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31974. }
  31975. };
  31976. /**
  31977. * Binds the view projection matrix to the effect.
  31978. * @param effect - Effect to bind the view projection matrix to.
  31979. */
  31980. Material.prototype.bindViewProjection = function (effect) {
  31981. if (!this._useUBO) {
  31982. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31983. }
  31984. else {
  31985. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31986. }
  31987. };
  31988. /**
  31989. * Specifies if material alpha testing should be turned on for the mesh.
  31990. * @param mesh - BJS mesh.
  31991. */
  31992. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31993. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31994. };
  31995. /**
  31996. * Processes to execute after binding the material to a mesh.
  31997. * @param mesh - BJS mesh.
  31998. */
  31999. Material.prototype._afterBind = function (mesh) {
  32000. this._scene._cachedMaterial = this;
  32001. if (mesh) {
  32002. this._scene._cachedVisibility = mesh.visibility;
  32003. }
  32004. else {
  32005. this._scene._cachedVisibility = 1;
  32006. }
  32007. if (mesh) {
  32008. this.onBindObservable.notifyObservers(mesh);
  32009. }
  32010. if (this.disableDepthWrite) {
  32011. var engine = this._scene.getEngine();
  32012. this._cachedDepthWriteState = engine.getDepthWrite();
  32013. engine.setDepthWrite(false);
  32014. }
  32015. };
  32016. /**
  32017. * Unbinds the material from the mesh.
  32018. */
  32019. Material.prototype.unbind = function () {
  32020. this.onUnBindObservable.notifyObservers(this);
  32021. if (this.disableDepthWrite) {
  32022. var engine = this._scene.getEngine();
  32023. engine.setDepthWrite(this._cachedDepthWriteState);
  32024. }
  32025. };
  32026. /**
  32027. * Gets the active textures from the material.
  32028. * @returns - Array of textures.
  32029. */
  32030. Material.prototype.getActiveTextures = function () {
  32031. return [];
  32032. };
  32033. /**
  32034. * Specifies if the material uses a texture.
  32035. * @param texture - Texture to check against the material.
  32036. * @returns - Boolean specifying if the material uses the texture.
  32037. */
  32038. Material.prototype.hasTexture = function (texture) {
  32039. return false;
  32040. };
  32041. /**
  32042. * Makes a duplicate of the material, and gives it a new name.
  32043. * @param name - Name to call the duplicated material.
  32044. * @returns - Nullable cloned material
  32045. */
  32046. Material.prototype.clone = function (name) {
  32047. return null;
  32048. };
  32049. /**
  32050. * Gets the meshes bound to the material.
  32051. * @returns - Array of meshes bound to the material.
  32052. */
  32053. Material.prototype.getBindedMeshes = function () {
  32054. var result = new Array();
  32055. for (var index = 0; index < this._scene.meshes.length; index++) {
  32056. var mesh = this._scene.meshes[index];
  32057. if (mesh.material === this) {
  32058. result.push(mesh);
  32059. }
  32060. }
  32061. return result;
  32062. };
  32063. /**
  32064. * Force shader compilation
  32065. * @param mesh - BJS mesh.
  32066. * @param onCompiled - function to execute once the material is compiled.
  32067. * @param options - options to pass to this function.
  32068. */
  32069. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  32070. var _this = this;
  32071. var localOptions = __assign({ clipPlane: false }, options);
  32072. var subMesh = new BABYLON.BaseSubMesh();
  32073. var scene = this.getScene();
  32074. var checkReady = function () {
  32075. if (!_this._scene || !_this._scene.getEngine()) {
  32076. return;
  32077. }
  32078. if (subMesh._materialDefines) {
  32079. subMesh._materialDefines._renderId = -1;
  32080. }
  32081. var clipPlaneState = scene.clipPlane;
  32082. if (localOptions.clipPlane) {
  32083. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  32084. }
  32085. if (_this.storeEffectOnSubMeshes) {
  32086. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  32087. if (onCompiled) {
  32088. onCompiled(_this);
  32089. }
  32090. }
  32091. else {
  32092. setTimeout(checkReady, 16);
  32093. }
  32094. }
  32095. else {
  32096. if (_this.isReady(mesh)) {
  32097. if (onCompiled) {
  32098. onCompiled(_this);
  32099. }
  32100. }
  32101. else {
  32102. setTimeout(checkReady, 16);
  32103. }
  32104. }
  32105. if (localOptions.clipPlane) {
  32106. scene.clipPlane = clipPlaneState;
  32107. }
  32108. };
  32109. checkReady();
  32110. };
  32111. /**
  32112. * Force shader compilation.
  32113. * @param mesh The mesh that will use this material
  32114. * @param options Additional options for compiling the shaders
  32115. * @returns A promise that resolves when the compilation completes
  32116. */
  32117. Material.prototype.forceCompilationAsync = function (mesh, options) {
  32118. var _this = this;
  32119. return new Promise(function (resolve) {
  32120. _this.forceCompilation(mesh, function () {
  32121. resolve();
  32122. }, options);
  32123. });
  32124. };
  32125. /**
  32126. * Marks a define in the material to indicate that it needs to be re-computed.
  32127. * @param flag - Material define flag.
  32128. */
  32129. Material.prototype.markAsDirty = function (flag) {
  32130. if (flag & Material.TextureDirtyFlag) {
  32131. this._markAllSubMeshesAsTexturesDirty();
  32132. }
  32133. if (flag & Material.LightDirtyFlag) {
  32134. this._markAllSubMeshesAsLightsDirty();
  32135. }
  32136. if (flag & Material.FresnelDirtyFlag) {
  32137. this._markAllSubMeshesAsFresnelDirty();
  32138. }
  32139. if (flag & Material.AttributesDirtyFlag) {
  32140. this._markAllSubMeshesAsAttributesDirty();
  32141. }
  32142. if (flag & Material.MiscDirtyFlag) {
  32143. this._markAllSubMeshesAsMiscDirty();
  32144. }
  32145. this.getScene().resetCachedMaterial();
  32146. };
  32147. /**
  32148. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  32149. * @param func - function which checks material defines against the submeshes.
  32150. */
  32151. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  32152. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  32153. var mesh = _a[_i];
  32154. if (!mesh.subMeshes) {
  32155. continue;
  32156. }
  32157. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  32158. var subMesh = _c[_b];
  32159. if (subMesh.getMaterial() !== this) {
  32160. continue;
  32161. }
  32162. if (!subMesh._materialDefines) {
  32163. continue;
  32164. }
  32165. func(subMesh._materialDefines);
  32166. }
  32167. }
  32168. };
  32169. /**
  32170. * Indicates that image processing needs to be re-calculated for all submeshes.
  32171. */
  32172. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  32173. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  32174. };
  32175. /**
  32176. * Indicates that textures need to be re-calculated for all submeshes.
  32177. */
  32178. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  32179. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  32180. };
  32181. /**
  32182. * Indicates that fresnel needs to be re-calculated for all submeshes.
  32183. */
  32184. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  32185. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  32186. };
  32187. /**
  32188. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  32189. */
  32190. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  32191. this._markAllSubMeshesAsDirty(function (defines) {
  32192. defines.markAsFresnelDirty();
  32193. defines.markAsMiscDirty();
  32194. });
  32195. };
  32196. /**
  32197. * Indicates that lights need to be re-calculated for all submeshes.
  32198. */
  32199. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  32200. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  32201. };
  32202. /**
  32203. * Indicates that attributes need to be re-calculated for all submeshes.
  32204. */
  32205. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  32206. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  32207. };
  32208. /**
  32209. * Indicates that misc needs to be re-calculated for all submeshes.
  32210. */
  32211. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  32212. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  32213. };
  32214. /**
  32215. * Indicates that textures and misc need to be re-calculated for all submeshes.
  32216. */
  32217. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  32218. this._markAllSubMeshesAsDirty(function (defines) {
  32219. defines.markAsTexturesDirty();
  32220. defines.markAsMiscDirty();
  32221. });
  32222. };
  32223. /**
  32224. * Disposes the material.
  32225. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  32226. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  32227. */
  32228. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32229. // Animations
  32230. this.getScene().stopAnimation(this);
  32231. this.getScene().freeProcessedMaterials();
  32232. // Remove from scene
  32233. var index = this._scene.materials.indexOf(this);
  32234. if (index >= 0) {
  32235. this._scene.materials.splice(index, 1);
  32236. }
  32237. // Remove from meshes
  32238. for (index = 0; index < this._scene.meshes.length; index++) {
  32239. var mesh = this._scene.meshes[index];
  32240. if (mesh.material === this) {
  32241. mesh.material = null;
  32242. if (mesh.geometry) {
  32243. var geometry = (mesh.geometry);
  32244. if (this.storeEffectOnSubMeshes) {
  32245. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  32246. var subMesh = _a[_i];
  32247. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  32248. if (forceDisposeEffect && subMesh._materialEffect) {
  32249. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  32250. }
  32251. }
  32252. }
  32253. else {
  32254. geometry._releaseVertexArrayObject(this._effect);
  32255. }
  32256. }
  32257. }
  32258. }
  32259. this._uniformBuffer.dispose();
  32260. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  32261. if (forceDisposeEffect && this._effect) {
  32262. if (!this.storeEffectOnSubMeshes) {
  32263. this._scene.getEngine()._releaseEffect(this._effect);
  32264. }
  32265. this._effect = null;
  32266. }
  32267. // Callback
  32268. this.onDisposeObservable.notifyObservers(this);
  32269. this.onDisposeObservable.clear();
  32270. this.onBindObservable.clear();
  32271. this.onUnBindObservable.clear();
  32272. };
  32273. /**
  32274. * Serializes this material.
  32275. * @returns - serialized material object.
  32276. */
  32277. Material.prototype.serialize = function () {
  32278. return BABYLON.SerializationHelper.Serialize(this);
  32279. };
  32280. /**
  32281. * Creates a MultiMaterial from parse MultiMaterial data.
  32282. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  32283. * @param scene - BJS scene.
  32284. * @returns - MultiMaterial.
  32285. */
  32286. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  32287. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  32288. multiMaterial.id = parsedMultiMaterial.id;
  32289. if (BABYLON.Tags) {
  32290. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  32291. }
  32292. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  32293. var subMatId = parsedMultiMaterial.materials[matIndex];
  32294. if (subMatId) {
  32295. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  32296. }
  32297. else {
  32298. multiMaterial.subMaterials.push(null);
  32299. }
  32300. }
  32301. return multiMaterial;
  32302. };
  32303. /**
  32304. * Creates a material from parsed material data.
  32305. * @param parsedMaterial - Parsed material data.
  32306. * @param scene - BJS scene.
  32307. * @param rootUrl - Root URL containing the material information.
  32308. * @returns - Parsed material.
  32309. */
  32310. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  32311. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  32312. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  32313. }
  32314. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  32315. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  32316. if (!BABYLON.LegacyPBRMaterial) {
  32317. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  32318. return;
  32319. }
  32320. }
  32321. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  32322. return materialType.Parse(parsedMaterial, scene, rootUrl);
  32323. ;
  32324. };
  32325. // Triangle views
  32326. Material._TriangleFillMode = 0;
  32327. Material._WireFrameFillMode = 1;
  32328. Material._PointFillMode = 2;
  32329. // Draw modes
  32330. Material._PointListDrawMode = 3;
  32331. Material._LineListDrawMode = 4;
  32332. Material._LineLoopDrawMode = 5;
  32333. Material._LineStripDrawMode = 6;
  32334. Material._TriangleStripDrawMode = 7;
  32335. Material._TriangleFanDrawMode = 8;
  32336. /**
  32337. * Stores the clock-wise side orientation.
  32338. */
  32339. Material._ClockWiseSideOrientation = 0;
  32340. /**
  32341. * Stores the counter clock-wise side orientation.
  32342. */
  32343. Material._CounterClockWiseSideOrientation = 1;
  32344. /**
  32345. * The dirty texture flag value.
  32346. */
  32347. Material._TextureDirtyFlag = 1;
  32348. /**
  32349. * The dirty light flag value.
  32350. */
  32351. Material._LightDirtyFlag = 2;
  32352. /**
  32353. * The dirty fresnel flag value.
  32354. */
  32355. Material._FresnelDirtyFlag = 4;
  32356. /**
  32357. * The dirty attribute flag value.
  32358. */
  32359. Material._AttributesDirtyFlag = 8;
  32360. /**
  32361. * The dirty misc flag value.
  32362. */
  32363. Material._MiscDirtyFlag = 16;
  32364. __decorate([
  32365. BABYLON.serialize()
  32366. ], Material.prototype, "id", void 0);
  32367. __decorate([
  32368. BABYLON.serialize()
  32369. ], Material.prototype, "name", void 0);
  32370. __decorate([
  32371. BABYLON.serialize()
  32372. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32373. __decorate([
  32374. BABYLON.serialize()
  32375. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32376. __decorate([
  32377. BABYLON.serialize()
  32378. ], Material.prototype, "state", void 0);
  32379. __decorate([
  32380. BABYLON.serialize("alpha")
  32381. ], Material.prototype, "_alpha", void 0);
  32382. __decorate([
  32383. BABYLON.serialize("backFaceCulling")
  32384. ], Material.prototype, "_backFaceCulling", void 0);
  32385. __decorate([
  32386. BABYLON.serialize()
  32387. ], Material.prototype, "sideOrientation", void 0);
  32388. __decorate([
  32389. BABYLON.serialize("alphaMode")
  32390. ], Material.prototype, "_alphaMode", void 0);
  32391. __decorate([
  32392. BABYLON.serialize()
  32393. ], Material.prototype, "_needDepthPrePass", void 0);
  32394. __decorate([
  32395. BABYLON.serialize()
  32396. ], Material.prototype, "disableDepthWrite", void 0);
  32397. __decorate([
  32398. BABYLON.serialize()
  32399. ], Material.prototype, "forceDepthWrite", void 0);
  32400. __decorate([
  32401. BABYLON.serialize()
  32402. ], Material.prototype, "separateCullingPass", void 0);
  32403. __decorate([
  32404. BABYLON.serialize("fogEnabled")
  32405. ], Material.prototype, "_fogEnabled", void 0);
  32406. __decorate([
  32407. BABYLON.serialize()
  32408. ], Material.prototype, "pointSize", void 0);
  32409. __decorate([
  32410. BABYLON.serialize()
  32411. ], Material.prototype, "zOffset", void 0);
  32412. __decorate([
  32413. BABYLON.serialize()
  32414. ], Material.prototype, "wireframe", null);
  32415. __decorate([
  32416. BABYLON.serialize()
  32417. ], Material.prototype, "pointsCloud", null);
  32418. __decorate([
  32419. BABYLON.serialize()
  32420. ], Material.prototype, "fillMode", null);
  32421. return Material;
  32422. }());
  32423. BABYLON.Material = Material;
  32424. })(BABYLON || (BABYLON = {}));
  32425. //# sourceMappingURL=babylon.material.js.map
  32426. "use strict";
  32427. var BABYLON;
  32428. (function (BABYLON) {
  32429. var UniformBuffer = /** @class */ (function () {
  32430. /**
  32431. * Uniform buffer objects.
  32432. *
  32433. * Handles blocks of uniform on the GPU.
  32434. *
  32435. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32436. *
  32437. * For more information, please refer to :
  32438. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32439. */
  32440. function UniformBuffer(engine, data, dynamic) {
  32441. this._engine = engine;
  32442. this._noUBO = !engine.supportsUniformBuffers;
  32443. this._dynamic = dynamic;
  32444. this._data = data || [];
  32445. this._uniformLocations = {};
  32446. this._uniformSizes = {};
  32447. this._uniformLocationPointer = 0;
  32448. this._needSync = false;
  32449. if (this._noUBO) {
  32450. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32451. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32452. this.updateFloat = this._updateFloatForEffect;
  32453. this.updateFloat2 = this._updateFloat2ForEffect;
  32454. this.updateFloat3 = this._updateFloat3ForEffect;
  32455. this.updateFloat4 = this._updateFloat4ForEffect;
  32456. this.updateMatrix = this._updateMatrixForEffect;
  32457. this.updateVector3 = this._updateVector3ForEffect;
  32458. this.updateVector4 = this._updateVector4ForEffect;
  32459. this.updateColor3 = this._updateColor3ForEffect;
  32460. this.updateColor4 = this._updateColor4ForEffect;
  32461. }
  32462. else {
  32463. this._engine._uniformBuffers.push(this);
  32464. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32465. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32466. this.updateFloat = this._updateFloatForUniform;
  32467. this.updateFloat2 = this._updateFloat2ForUniform;
  32468. this.updateFloat3 = this._updateFloat3ForUniform;
  32469. this.updateFloat4 = this._updateFloat4ForUniform;
  32470. this.updateMatrix = this._updateMatrixForUniform;
  32471. this.updateVector3 = this._updateVector3ForUniform;
  32472. this.updateVector4 = this._updateVector4ForUniform;
  32473. this.updateColor3 = this._updateColor3ForUniform;
  32474. this.updateColor4 = this._updateColor4ForUniform;
  32475. }
  32476. }
  32477. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32478. // Properties
  32479. /**
  32480. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32481. * or just falling back on setUniformXXX calls.
  32482. */
  32483. get: function () {
  32484. return !this._noUBO;
  32485. },
  32486. enumerable: true,
  32487. configurable: true
  32488. });
  32489. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32490. /**
  32491. * Indicates if the WebGL underlying uniform buffer is in sync
  32492. * with the javascript cache data.
  32493. */
  32494. get: function () {
  32495. return !this._needSync;
  32496. },
  32497. enumerable: true,
  32498. configurable: true
  32499. });
  32500. /**
  32501. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32502. * Also, a dynamic UniformBuffer will disable cache verification and always
  32503. * update the underlying WebGL uniform buffer to the GPU.
  32504. */
  32505. UniformBuffer.prototype.isDynamic = function () {
  32506. return this._dynamic !== undefined;
  32507. };
  32508. /**
  32509. * The data cache on JS side.
  32510. */
  32511. UniformBuffer.prototype.getData = function () {
  32512. return this._bufferData;
  32513. };
  32514. /**
  32515. * The underlying WebGL Uniform buffer.
  32516. */
  32517. UniformBuffer.prototype.getBuffer = function () {
  32518. return this._buffer;
  32519. };
  32520. /**
  32521. * std140 layout specifies how to align data within an UBO structure.
  32522. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32523. * for specs.
  32524. */
  32525. UniformBuffer.prototype._fillAlignment = function (size) {
  32526. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32527. // and 4x4 matrices
  32528. // TODO : change if other types are used
  32529. var alignment;
  32530. if (size <= 2) {
  32531. alignment = size;
  32532. }
  32533. else {
  32534. alignment = 4;
  32535. }
  32536. if ((this._uniformLocationPointer % alignment) !== 0) {
  32537. var oldPointer = this._uniformLocationPointer;
  32538. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32539. var diff = this._uniformLocationPointer - oldPointer;
  32540. for (var i = 0; i < diff; i++) {
  32541. this._data.push(0);
  32542. }
  32543. }
  32544. };
  32545. /**
  32546. * Adds an uniform in the buffer.
  32547. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32548. * for the layout to be correct !
  32549. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32550. * @param {number|number[]} size Data size, or data directly.
  32551. */
  32552. UniformBuffer.prototype.addUniform = function (name, size) {
  32553. if (this._noUBO) {
  32554. return;
  32555. }
  32556. if (this._uniformLocations[name] !== undefined) {
  32557. // Already existing uniform
  32558. return;
  32559. }
  32560. // This function must be called in the order of the shader layout !
  32561. // size can be the size of the uniform, or data directly
  32562. var data;
  32563. if (size instanceof Array) {
  32564. data = size;
  32565. size = data.length;
  32566. }
  32567. else {
  32568. size = size;
  32569. data = [];
  32570. // Fill with zeros
  32571. for (var i = 0; i < size; i++) {
  32572. data.push(0);
  32573. }
  32574. }
  32575. this._fillAlignment(size);
  32576. this._uniformSizes[name] = size;
  32577. this._uniformLocations[name] = this._uniformLocationPointer;
  32578. this._uniformLocationPointer += size;
  32579. for (var i = 0; i < size; i++) {
  32580. this._data.push(data[i]);
  32581. }
  32582. this._needSync = true;
  32583. };
  32584. /**
  32585. * Wrapper for addUniform.
  32586. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32587. * @param {Matrix} mat A 4x4 matrix.
  32588. */
  32589. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32590. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32591. };
  32592. /**
  32593. * Wrapper for addUniform.
  32594. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32595. * @param {number} x
  32596. * @param {number} y
  32597. */
  32598. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32599. var temp = [x, y];
  32600. this.addUniform(name, temp);
  32601. };
  32602. /**
  32603. * Wrapper for addUniform.
  32604. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32605. * @param {number} x
  32606. * @param {number} y
  32607. * @param {number} z
  32608. */
  32609. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32610. var temp = [x, y, z];
  32611. this.addUniform(name, temp);
  32612. };
  32613. /**
  32614. * Wrapper for addUniform.
  32615. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32616. * @param {Color3} color
  32617. */
  32618. UniformBuffer.prototype.addColor3 = function (name, color) {
  32619. var temp = new Array();
  32620. color.toArray(temp);
  32621. this.addUniform(name, temp);
  32622. };
  32623. /**
  32624. * Wrapper for addUniform.
  32625. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32626. * @param {Color3} color
  32627. * @param {number} alpha
  32628. */
  32629. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32630. var temp = new Array();
  32631. color.toArray(temp);
  32632. temp.push(alpha);
  32633. this.addUniform(name, temp);
  32634. };
  32635. /**
  32636. * Wrapper for addUniform.
  32637. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32638. * @param {Vector3} vector
  32639. */
  32640. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32641. var temp = new Array();
  32642. vector.toArray(temp);
  32643. this.addUniform(name, temp);
  32644. };
  32645. /**
  32646. * Wrapper for addUniform.
  32647. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32648. */
  32649. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32650. this.addUniform(name, 12);
  32651. };
  32652. /**
  32653. * Wrapper for addUniform.
  32654. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32655. */
  32656. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32657. this.addUniform(name, 8);
  32658. };
  32659. /**
  32660. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32661. */
  32662. UniformBuffer.prototype.create = function () {
  32663. if (this._noUBO) {
  32664. return;
  32665. }
  32666. if (this._buffer) {
  32667. return; // nothing to do
  32668. }
  32669. // See spec, alignment must be filled as a vec4
  32670. this._fillAlignment(4);
  32671. this._bufferData = new Float32Array(this._data);
  32672. this._rebuild();
  32673. this._needSync = true;
  32674. };
  32675. UniformBuffer.prototype._rebuild = function () {
  32676. if (this._noUBO) {
  32677. return;
  32678. }
  32679. if (this._dynamic) {
  32680. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32681. }
  32682. else {
  32683. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32684. }
  32685. };
  32686. /**
  32687. * Updates the WebGL Uniform Buffer on the GPU.
  32688. * If the `dynamic` flag is set to true, no cache comparison is done.
  32689. * Otherwise, the buffer will be updated only if the cache differs.
  32690. */
  32691. UniformBuffer.prototype.update = function () {
  32692. if (!this._buffer) {
  32693. this.create();
  32694. return;
  32695. }
  32696. if (!this._dynamic && !this._needSync) {
  32697. return;
  32698. }
  32699. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32700. this._needSync = false;
  32701. };
  32702. /**
  32703. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32704. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32705. * @param {number[]|Float32Array} data Flattened data
  32706. * @param {number} size Size of the data.
  32707. */
  32708. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32709. var location = this._uniformLocations[uniformName];
  32710. if (location === undefined) {
  32711. if (this._buffer) {
  32712. // Cannot add an uniform if the buffer is already created
  32713. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32714. return;
  32715. }
  32716. this.addUniform(uniformName, size);
  32717. location = this._uniformLocations[uniformName];
  32718. }
  32719. if (!this._buffer) {
  32720. this.create();
  32721. }
  32722. if (!this._dynamic) {
  32723. // Cache for static uniform buffers
  32724. var changed = false;
  32725. for (var i = 0; i < size; i++) {
  32726. if (this._bufferData[location + i] !== data[i]) {
  32727. changed = true;
  32728. this._bufferData[location + i] = data[i];
  32729. }
  32730. }
  32731. this._needSync = this._needSync || changed;
  32732. }
  32733. else {
  32734. // No cache for dynamic
  32735. for (var i = 0; i < size; i++) {
  32736. this._bufferData[location + i] = data[i];
  32737. }
  32738. }
  32739. };
  32740. // Update methods
  32741. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32742. // To match std140, matrix must be realigned
  32743. for (var i = 0; i < 3; i++) {
  32744. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32745. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32746. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32747. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32748. }
  32749. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32750. };
  32751. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32752. this._currentEffect.setMatrix3x3(name, matrix);
  32753. };
  32754. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32755. this._currentEffect.setMatrix2x2(name, matrix);
  32756. };
  32757. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32758. // To match std140, matrix must be realigned
  32759. for (var i = 0; i < 2; i++) {
  32760. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32761. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32762. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32763. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32764. }
  32765. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32766. };
  32767. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32768. this._currentEffect.setFloat(name, x);
  32769. };
  32770. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32771. UniformBuffer._tempBuffer[0] = x;
  32772. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32773. };
  32774. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32775. if (suffix === void 0) { suffix = ""; }
  32776. this._currentEffect.setFloat2(name + suffix, x, y);
  32777. };
  32778. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32779. if (suffix === void 0) { suffix = ""; }
  32780. UniformBuffer._tempBuffer[0] = x;
  32781. UniformBuffer._tempBuffer[1] = y;
  32782. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32783. };
  32784. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32785. if (suffix === void 0) { suffix = ""; }
  32786. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32787. };
  32788. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32789. if (suffix === void 0) { suffix = ""; }
  32790. UniformBuffer._tempBuffer[0] = x;
  32791. UniformBuffer._tempBuffer[1] = y;
  32792. UniformBuffer._tempBuffer[2] = z;
  32793. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32794. };
  32795. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32796. if (suffix === void 0) { suffix = ""; }
  32797. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32798. };
  32799. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32800. if (suffix === void 0) { suffix = ""; }
  32801. UniformBuffer._tempBuffer[0] = x;
  32802. UniformBuffer._tempBuffer[1] = y;
  32803. UniformBuffer._tempBuffer[2] = z;
  32804. UniformBuffer._tempBuffer[3] = w;
  32805. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32806. };
  32807. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32808. this._currentEffect.setMatrix(name, mat);
  32809. };
  32810. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32811. this.updateUniform(name, mat.toArray(), 16);
  32812. };
  32813. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32814. this._currentEffect.setVector3(name, vector);
  32815. };
  32816. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32817. vector.toArray(UniformBuffer._tempBuffer);
  32818. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32819. };
  32820. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32821. this._currentEffect.setVector4(name, vector);
  32822. };
  32823. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32824. vector.toArray(UniformBuffer._tempBuffer);
  32825. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32826. };
  32827. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32828. if (suffix === void 0) { suffix = ""; }
  32829. this._currentEffect.setColor3(name + suffix, color);
  32830. };
  32831. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32832. if (suffix === void 0) { suffix = ""; }
  32833. color.toArray(UniformBuffer._tempBuffer);
  32834. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32835. };
  32836. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32837. if (suffix === void 0) { suffix = ""; }
  32838. this._currentEffect.setColor4(name + suffix, color, alpha);
  32839. };
  32840. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32841. if (suffix === void 0) { suffix = ""; }
  32842. color.toArray(UniformBuffer._tempBuffer);
  32843. UniformBuffer._tempBuffer[3] = alpha;
  32844. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32845. };
  32846. /**
  32847. * Sets a sampler uniform on the effect.
  32848. * @param {string} name Name of the sampler.
  32849. * @param {Texture} texture
  32850. */
  32851. UniformBuffer.prototype.setTexture = function (name, texture) {
  32852. this._currentEffect.setTexture(name, texture);
  32853. };
  32854. /**
  32855. * Directly updates the value of the uniform in the cache AND on the GPU.
  32856. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32857. * @param {number[]|Float32Array} data Flattened data
  32858. */
  32859. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32860. this.updateUniform(uniformName, data, data.length);
  32861. this.update();
  32862. };
  32863. /**
  32864. * Binds this uniform buffer to an effect.
  32865. * @param {Effect} effect
  32866. * @param {string} name Name of the uniform block in the shader.
  32867. */
  32868. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32869. this._currentEffect = effect;
  32870. if (this._noUBO || !this._buffer) {
  32871. return;
  32872. }
  32873. effect.bindUniformBuffer(this._buffer, name);
  32874. };
  32875. /**
  32876. * Disposes the uniform buffer.
  32877. */
  32878. UniformBuffer.prototype.dispose = function () {
  32879. if (this._noUBO) {
  32880. return;
  32881. }
  32882. var index = this._engine._uniformBuffers.indexOf(this);
  32883. if (index !== -1) {
  32884. this._engine._uniformBuffers.splice(index, 1);
  32885. }
  32886. if (!this._buffer) {
  32887. return;
  32888. }
  32889. if (this._engine._releaseBuffer(this._buffer)) {
  32890. this._buffer = null;
  32891. }
  32892. };
  32893. // Pool for avoiding memory leaks
  32894. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32895. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32896. return UniformBuffer;
  32897. }());
  32898. BABYLON.UniformBuffer = UniformBuffer;
  32899. })(BABYLON || (BABYLON = {}));
  32900. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32901. "use strict";
  32902. var BABYLON;
  32903. (function (BABYLON) {
  32904. var VertexData = /** @class */ (function () {
  32905. function VertexData() {
  32906. }
  32907. VertexData.prototype.set = function (data, kind) {
  32908. switch (kind) {
  32909. case BABYLON.VertexBuffer.PositionKind:
  32910. this.positions = data;
  32911. break;
  32912. case BABYLON.VertexBuffer.NormalKind:
  32913. this.normals = data;
  32914. break;
  32915. case BABYLON.VertexBuffer.TangentKind:
  32916. this.tangents = data;
  32917. break;
  32918. case BABYLON.VertexBuffer.UVKind:
  32919. this.uvs = data;
  32920. break;
  32921. case BABYLON.VertexBuffer.UV2Kind:
  32922. this.uvs2 = data;
  32923. break;
  32924. case BABYLON.VertexBuffer.UV3Kind:
  32925. this.uvs3 = data;
  32926. break;
  32927. case BABYLON.VertexBuffer.UV4Kind:
  32928. this.uvs4 = data;
  32929. break;
  32930. case BABYLON.VertexBuffer.UV5Kind:
  32931. this.uvs5 = data;
  32932. break;
  32933. case BABYLON.VertexBuffer.UV6Kind:
  32934. this.uvs6 = data;
  32935. break;
  32936. case BABYLON.VertexBuffer.ColorKind:
  32937. this.colors = data;
  32938. break;
  32939. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32940. this.matricesIndices = data;
  32941. break;
  32942. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32943. this.matricesWeights = data;
  32944. break;
  32945. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32946. this.matricesIndicesExtra = data;
  32947. break;
  32948. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32949. this.matricesWeightsExtra = data;
  32950. break;
  32951. }
  32952. };
  32953. /**
  32954. * Associates the vertexData to the passed Mesh.
  32955. * Sets it as updatable or not (default `false`).
  32956. * Returns the VertexData.
  32957. */
  32958. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32959. this._applyTo(mesh, updatable);
  32960. return this;
  32961. };
  32962. /**
  32963. * Associates the vertexData to the passed Geometry.
  32964. * Sets it as updatable or not (default `false`).
  32965. * Returns the VertexData.
  32966. */
  32967. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32968. this._applyTo(geometry, updatable);
  32969. return this;
  32970. };
  32971. /**
  32972. * Updates the associated mesh.
  32973. * Returns the VertexData.
  32974. */
  32975. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32976. this._update(mesh);
  32977. return this;
  32978. };
  32979. /**
  32980. * Updates the associated geometry.
  32981. * Returns the VertexData.
  32982. */
  32983. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32984. this._update(geometry);
  32985. return this;
  32986. };
  32987. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32988. if (updatable === void 0) { updatable = false; }
  32989. if (this.positions) {
  32990. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32991. }
  32992. if (this.normals) {
  32993. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32994. }
  32995. if (this.tangents) {
  32996. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32997. }
  32998. if (this.uvs) {
  32999. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  33000. }
  33001. if (this.uvs2) {
  33002. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  33003. }
  33004. if (this.uvs3) {
  33005. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  33006. }
  33007. if (this.uvs4) {
  33008. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  33009. }
  33010. if (this.uvs5) {
  33011. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  33012. }
  33013. if (this.uvs6) {
  33014. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  33015. }
  33016. if (this.colors) {
  33017. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  33018. }
  33019. if (this.matricesIndices) {
  33020. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  33021. }
  33022. if (this.matricesWeights) {
  33023. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  33024. }
  33025. if (this.matricesIndicesExtra) {
  33026. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  33027. }
  33028. if (this.matricesWeightsExtra) {
  33029. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  33030. }
  33031. if (this.indices) {
  33032. meshOrGeometry.setIndices(this.indices, null, updatable);
  33033. }
  33034. return this;
  33035. };
  33036. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  33037. if (this.positions) {
  33038. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  33039. }
  33040. if (this.normals) {
  33041. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  33042. }
  33043. if (this.tangents) {
  33044. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  33045. }
  33046. if (this.uvs) {
  33047. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33048. }
  33049. if (this.uvs2) {
  33050. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33051. }
  33052. if (this.uvs3) {
  33053. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33054. }
  33055. if (this.uvs4) {
  33056. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33057. }
  33058. if (this.uvs5) {
  33059. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33060. }
  33061. if (this.uvs6) {
  33062. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33063. }
  33064. if (this.colors) {
  33065. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33066. }
  33067. if (this.matricesIndices) {
  33068. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33069. }
  33070. if (this.matricesWeights) {
  33071. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33072. }
  33073. if (this.matricesIndicesExtra) {
  33074. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33075. }
  33076. if (this.matricesWeightsExtra) {
  33077. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33078. }
  33079. if (this.indices) {
  33080. meshOrGeometry.setIndices(this.indices, null);
  33081. }
  33082. return this;
  33083. };
  33084. /**
  33085. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  33086. * Returns the VertexData.
  33087. */
  33088. VertexData.prototype.transform = function (matrix) {
  33089. var transformed = BABYLON.Vector3.Zero();
  33090. var index;
  33091. if (this.positions) {
  33092. var position = BABYLON.Vector3.Zero();
  33093. for (index = 0; index < this.positions.length; index += 3) {
  33094. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33095. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33096. this.positions[index] = transformed.x;
  33097. this.positions[index + 1] = transformed.y;
  33098. this.positions[index + 2] = transformed.z;
  33099. }
  33100. }
  33101. if (this.normals) {
  33102. var normal = BABYLON.Vector3.Zero();
  33103. for (index = 0; index < this.normals.length; index += 3) {
  33104. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33105. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33106. this.normals[index] = transformed.x;
  33107. this.normals[index + 1] = transformed.y;
  33108. this.normals[index + 2] = transformed.z;
  33109. }
  33110. }
  33111. if (this.tangents) {
  33112. var tangent = BABYLON.Vector4.Zero();
  33113. var tangentTransformed = BABYLON.Vector4.Zero();
  33114. for (index = 0; index < this.tangents.length; index += 4) {
  33115. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  33116. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  33117. this.tangents[index] = tangentTransformed.x;
  33118. this.tangents[index + 1] = tangentTransformed.y;
  33119. this.tangents[index + 2] = tangentTransformed.z;
  33120. this.tangents[index + 3] = tangentTransformed.w;
  33121. }
  33122. }
  33123. return this;
  33124. };
  33125. /**
  33126. * Merges the passed VertexData into the current one.
  33127. * Returns the modified VertexData.
  33128. */
  33129. VertexData.prototype.merge = function (other) {
  33130. this._validate();
  33131. other._validate();
  33132. if (!this.normals !== !other.normals ||
  33133. !this.tangents !== !other.tangents ||
  33134. !this.uvs !== !other.uvs ||
  33135. !this.uvs2 !== !other.uvs2 ||
  33136. !this.uvs3 !== !other.uvs3 ||
  33137. !this.uvs4 !== !other.uvs4 ||
  33138. !this.uvs5 !== !other.uvs5 ||
  33139. !this.uvs6 !== !other.uvs6 ||
  33140. !this.colors !== !other.colors ||
  33141. !this.matricesIndices !== !other.matricesIndices ||
  33142. !this.matricesWeights !== !other.matricesWeights ||
  33143. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  33144. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  33145. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  33146. }
  33147. if (other.indices) {
  33148. if (!this.indices) {
  33149. this.indices = [];
  33150. }
  33151. var offset = this.positions ? this.positions.length / 3 : 0;
  33152. for (var index = 0; index < other.indices.length; index++) {
  33153. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33154. this.indices.push(other.indices[index] + offset);
  33155. }
  33156. }
  33157. this.positions = this._mergeElement(this.positions, other.positions);
  33158. this.normals = this._mergeElement(this.normals, other.normals);
  33159. this.tangents = this._mergeElement(this.tangents, other.tangents);
  33160. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33161. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33162. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33163. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33164. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33165. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33166. this.colors = this._mergeElement(this.colors, other.colors);
  33167. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33168. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33169. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33170. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33171. return this;
  33172. };
  33173. VertexData.prototype._mergeElement = function (source, other) {
  33174. if (!source) {
  33175. return other;
  33176. }
  33177. if (!other) {
  33178. return source;
  33179. }
  33180. var len = other.length + source.length;
  33181. var isSrcTypedArray = source instanceof Float32Array;
  33182. var isOthTypedArray = other instanceof Float32Array;
  33183. // use non-loop method when the source is Float32Array
  33184. if (isSrcTypedArray) {
  33185. var ret32 = new Float32Array(len);
  33186. ret32.set(source);
  33187. ret32.set(other, source.length);
  33188. return ret32;
  33189. // source is number[], when other is also use concat
  33190. }
  33191. else if (!isOthTypedArray) {
  33192. return source.concat(other);
  33193. // source is a number[], but other is a Float32Array, loop required
  33194. }
  33195. else {
  33196. var ret = source.slice(0); // copy source to a separate array
  33197. for (var i = 0, len = other.length; i < len; i++) {
  33198. ret.push(other[i]);
  33199. }
  33200. return ret;
  33201. }
  33202. };
  33203. VertexData.prototype._validate = function () {
  33204. if (!this.positions) {
  33205. throw new Error("Positions are required");
  33206. }
  33207. var getElementCount = function (kind, values) {
  33208. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  33209. if ((values.length % stride) !== 0) {
  33210. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  33211. }
  33212. return values.length / stride;
  33213. };
  33214. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  33215. var validateElementCount = function (kind, values) {
  33216. var elementCount = getElementCount(kind, values);
  33217. if (elementCount !== positionsElementCount) {
  33218. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  33219. }
  33220. };
  33221. if (this.normals)
  33222. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  33223. if (this.tangents)
  33224. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  33225. if (this.uvs)
  33226. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  33227. if (this.uvs2)
  33228. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  33229. if (this.uvs3)
  33230. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  33231. if (this.uvs4)
  33232. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  33233. if (this.uvs5)
  33234. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  33235. if (this.uvs6)
  33236. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  33237. if (this.colors)
  33238. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  33239. if (this.matricesIndices)
  33240. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  33241. if (this.matricesWeights)
  33242. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  33243. if (this.matricesIndicesExtra)
  33244. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  33245. if (this.matricesWeightsExtra)
  33246. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  33247. };
  33248. /**
  33249. * Serializes the VertexData.
  33250. * Returns a serialized object.
  33251. */
  33252. VertexData.prototype.serialize = function () {
  33253. var serializationObject = this.serialize();
  33254. if (this.positions) {
  33255. serializationObject.positions = this.positions;
  33256. }
  33257. if (this.normals) {
  33258. serializationObject.normals = this.normals;
  33259. }
  33260. if (this.tangents) {
  33261. serializationObject.tangents = this.tangents;
  33262. }
  33263. if (this.uvs) {
  33264. serializationObject.uvs = this.uvs;
  33265. }
  33266. if (this.uvs2) {
  33267. serializationObject.uvs2 = this.uvs2;
  33268. }
  33269. if (this.uvs3) {
  33270. serializationObject.uvs3 = this.uvs3;
  33271. }
  33272. if (this.uvs4) {
  33273. serializationObject.uvs4 = this.uvs4;
  33274. }
  33275. if (this.uvs5) {
  33276. serializationObject.uvs5 = this.uvs5;
  33277. }
  33278. if (this.uvs6) {
  33279. serializationObject.uvs6 = this.uvs6;
  33280. }
  33281. if (this.colors) {
  33282. serializationObject.colors = this.colors;
  33283. }
  33284. if (this.matricesIndices) {
  33285. serializationObject.matricesIndices = this.matricesIndices;
  33286. serializationObject.matricesIndices._isExpanded = true;
  33287. }
  33288. if (this.matricesWeights) {
  33289. serializationObject.matricesWeights = this.matricesWeights;
  33290. }
  33291. if (this.matricesIndicesExtra) {
  33292. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33293. serializationObject.matricesIndicesExtra._isExpanded = true;
  33294. }
  33295. if (this.matricesWeightsExtra) {
  33296. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33297. }
  33298. serializationObject.indices = this.indices;
  33299. return serializationObject;
  33300. };
  33301. // Statics
  33302. /**
  33303. * Returns the object VertexData associated to the passed mesh.
  33304. */
  33305. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  33306. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  33307. };
  33308. /**
  33309. * Returns the object VertexData associated to the passed geometry.
  33310. */
  33311. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  33312. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  33313. };
  33314. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  33315. var result = new VertexData();
  33316. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33317. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  33318. }
  33319. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33320. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  33321. }
  33322. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33323. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  33324. }
  33325. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33326. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  33327. }
  33328. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33329. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  33330. }
  33331. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33332. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  33333. }
  33334. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33335. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  33336. }
  33337. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33338. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  33339. }
  33340. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33341. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  33342. }
  33343. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33344. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  33345. }
  33346. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33347. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  33348. }
  33349. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33350. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  33351. }
  33352. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33353. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  33354. }
  33355. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33356. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  33357. }
  33358. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33359. return result;
  33360. };
  33361. /**
  33362. * Creates the vertexData of the Ribbon.
  33363. */
  33364. VertexData.CreateRibbon = function (options) {
  33365. var pathArray = options.pathArray;
  33366. var closeArray = options.closeArray || false;
  33367. var closePath = options.closePath || false;
  33368. var invertUV = options.invertUV || false;
  33369. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33370. var offset = options.offset || defaultOffset;
  33371. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33372. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33373. var customUV = options.uvs;
  33374. var customColors = options.colors;
  33375. var positions = [];
  33376. var indices = [];
  33377. var normals = [];
  33378. var uvs = [];
  33379. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33380. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33381. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33382. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33383. var minlg; // minimal length among all paths from pathArray
  33384. var lg = []; // array of path lengths : nb of vertex per path
  33385. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33386. var p; // path iterator
  33387. var i; // point iterator
  33388. var j; // point iterator
  33389. // if single path in pathArray
  33390. if (pathArray.length < 2) {
  33391. var ar1 = [];
  33392. var ar2 = [];
  33393. for (i = 0; i < pathArray[0].length - offset; i++) {
  33394. ar1.push(pathArray[0][i]);
  33395. ar2.push(pathArray[0][i + offset]);
  33396. }
  33397. pathArray = [ar1, ar2];
  33398. }
  33399. // positions and horizontal distances (u)
  33400. var idc = 0;
  33401. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33402. var path;
  33403. var l;
  33404. minlg = pathArray[0].length;
  33405. var vectlg;
  33406. var dist;
  33407. for (p = 0; p < pathArray.length; p++) {
  33408. uTotalDistance[p] = 0;
  33409. us[p] = [0];
  33410. path = pathArray[p];
  33411. l = path.length;
  33412. minlg = (minlg < l) ? minlg : l;
  33413. j = 0;
  33414. while (j < l) {
  33415. positions.push(path[j].x, path[j].y, path[j].z);
  33416. if (j > 0) {
  33417. vectlg = path[j].subtract(path[j - 1]).length();
  33418. dist = vectlg + uTotalDistance[p];
  33419. us[p].push(dist);
  33420. uTotalDistance[p] = dist;
  33421. }
  33422. j++;
  33423. }
  33424. if (closePath) {
  33425. j--;
  33426. positions.push(path[0].x, path[0].y, path[0].z);
  33427. vectlg = path[j].subtract(path[0]).length();
  33428. dist = vectlg + uTotalDistance[p];
  33429. us[p].push(dist);
  33430. uTotalDistance[p] = dist;
  33431. }
  33432. lg[p] = l + closePathCorr;
  33433. idx[p] = idc;
  33434. idc += (l + closePathCorr);
  33435. }
  33436. // vertical distances (v)
  33437. var path1;
  33438. var path2;
  33439. var vertex1 = null;
  33440. var vertex2 = null;
  33441. for (i = 0; i < minlg + closePathCorr; i++) {
  33442. vTotalDistance[i] = 0;
  33443. vs[i] = [0];
  33444. for (p = 0; p < pathArray.length - 1; p++) {
  33445. path1 = pathArray[p];
  33446. path2 = pathArray[p + 1];
  33447. if (i === minlg) {
  33448. vertex1 = path1[0];
  33449. vertex2 = path2[0];
  33450. }
  33451. else {
  33452. vertex1 = path1[i];
  33453. vertex2 = path2[i];
  33454. }
  33455. vectlg = vertex2.subtract(vertex1).length();
  33456. dist = vectlg + vTotalDistance[i];
  33457. vs[i].push(dist);
  33458. vTotalDistance[i] = dist;
  33459. }
  33460. if (closeArray && vertex2 && vertex1) {
  33461. path1 = pathArray[p];
  33462. path2 = pathArray[0];
  33463. if (i === minlg) {
  33464. vertex2 = path2[0];
  33465. }
  33466. vectlg = vertex2.subtract(vertex1).length();
  33467. dist = vectlg + vTotalDistance[i];
  33468. vTotalDistance[i] = dist;
  33469. }
  33470. }
  33471. // uvs
  33472. var u;
  33473. var v;
  33474. if (customUV) {
  33475. for (p = 0; p < customUV.length; p++) {
  33476. uvs.push(customUV[p].x, customUV[p].y);
  33477. }
  33478. }
  33479. else {
  33480. for (p = 0; p < pathArray.length; p++) {
  33481. for (i = 0; i < minlg + closePathCorr; i++) {
  33482. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33483. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33484. if (invertUV) {
  33485. uvs.push(v, u);
  33486. }
  33487. else {
  33488. uvs.push(u, v);
  33489. }
  33490. }
  33491. }
  33492. }
  33493. // indices
  33494. p = 0; // path index
  33495. var pi = 0; // positions array index
  33496. var l1 = lg[p] - 1; // path1 length
  33497. var l2 = lg[p + 1] - 1; // path2 length
  33498. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33499. var shft = idx[1] - idx[0]; // shift
  33500. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33501. while (pi <= min && p < path1nb) {
  33502. // 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
  33503. indices.push(pi, pi + shft, pi + 1);
  33504. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33505. pi += 1;
  33506. if (pi === min) {
  33507. p++;
  33508. if (p === lg.length - 1) {
  33509. shft = idx[0] - idx[p];
  33510. l1 = lg[p] - 1;
  33511. l2 = lg[0] - 1;
  33512. }
  33513. else {
  33514. shft = idx[p + 1] - idx[p];
  33515. l1 = lg[p] - 1;
  33516. l2 = lg[p + 1] - 1;
  33517. }
  33518. pi = idx[p];
  33519. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33520. }
  33521. }
  33522. // normals
  33523. VertexData.ComputeNormals(positions, indices, normals);
  33524. if (closePath) {
  33525. var indexFirst = 0;
  33526. var indexLast = 0;
  33527. for (p = 0; p < pathArray.length; p++) {
  33528. indexFirst = idx[p] * 3;
  33529. if (p + 1 < pathArray.length) {
  33530. indexLast = (idx[p + 1] - 1) * 3;
  33531. }
  33532. else {
  33533. indexLast = normals.length - 3;
  33534. }
  33535. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33536. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33537. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33538. normals[indexLast] = normals[indexFirst];
  33539. normals[indexLast + 1] = normals[indexFirst + 1];
  33540. normals[indexLast + 2] = normals[indexFirst + 2];
  33541. }
  33542. }
  33543. // sides
  33544. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33545. // Colors
  33546. var colors = null;
  33547. if (customColors) {
  33548. colors = new Float32Array(customColors.length * 4);
  33549. for (var c = 0; c < customColors.length; c++) {
  33550. colors[c * 4] = customColors[c].r;
  33551. colors[c * 4 + 1] = customColors[c].g;
  33552. colors[c * 4 + 2] = customColors[c].b;
  33553. colors[c * 4 + 3] = customColors[c].a;
  33554. }
  33555. }
  33556. // Result
  33557. var vertexData = new VertexData();
  33558. var positions32 = new Float32Array(positions);
  33559. var normals32 = new Float32Array(normals);
  33560. var uvs32 = new Float32Array(uvs);
  33561. vertexData.indices = indices;
  33562. vertexData.positions = positions32;
  33563. vertexData.normals = normals32;
  33564. vertexData.uvs = uvs32;
  33565. if (colors) {
  33566. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33567. }
  33568. if (closePath) {
  33569. vertexData._idx = idx;
  33570. }
  33571. return vertexData;
  33572. };
  33573. /**
  33574. * Creates the VertexData of the Box.
  33575. */
  33576. VertexData.CreateBox = function (options) {
  33577. var normalsSource = [
  33578. new BABYLON.Vector3(0, 0, 1),
  33579. new BABYLON.Vector3(0, 0, -1),
  33580. new BABYLON.Vector3(1, 0, 0),
  33581. new BABYLON.Vector3(-1, 0, 0),
  33582. new BABYLON.Vector3(0, 1, 0),
  33583. new BABYLON.Vector3(0, -1, 0)
  33584. ];
  33585. var indices = [];
  33586. var positions = [];
  33587. var normals = [];
  33588. var uvs = [];
  33589. var width = options.width || options.size || 1;
  33590. var height = options.height || options.size || 1;
  33591. var depth = options.depth || options.size || 1;
  33592. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33593. var faceUV = options.faceUV || new Array(6);
  33594. var faceColors = options.faceColors;
  33595. var colors = [];
  33596. // default face colors and UV if undefined
  33597. for (var f = 0; f < 6; f++) {
  33598. if (faceUV[f] === undefined) {
  33599. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33600. }
  33601. if (faceColors && faceColors[f] === undefined) {
  33602. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33603. }
  33604. }
  33605. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33606. // Create each face in turn.
  33607. for (var index = 0; index < normalsSource.length; index++) {
  33608. var normal = normalsSource[index];
  33609. // Get two vectors perpendicular to the face normal and to each other.
  33610. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33611. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33612. // Six indices (two triangles) per face.
  33613. var verticesLength = positions.length / 3;
  33614. indices.push(verticesLength);
  33615. indices.push(verticesLength + 1);
  33616. indices.push(verticesLength + 2);
  33617. indices.push(verticesLength);
  33618. indices.push(verticesLength + 2);
  33619. indices.push(verticesLength + 3);
  33620. // Four vertices per face.
  33621. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33622. positions.push(vertex.x, vertex.y, vertex.z);
  33623. normals.push(normal.x, normal.y, normal.z);
  33624. uvs.push(faceUV[index].z, faceUV[index].w);
  33625. if (faceColors) {
  33626. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33627. }
  33628. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33629. positions.push(vertex.x, vertex.y, vertex.z);
  33630. normals.push(normal.x, normal.y, normal.z);
  33631. uvs.push(faceUV[index].x, faceUV[index].w);
  33632. if (faceColors) {
  33633. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33634. }
  33635. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33636. positions.push(vertex.x, vertex.y, vertex.z);
  33637. normals.push(normal.x, normal.y, normal.z);
  33638. uvs.push(faceUV[index].x, faceUV[index].y);
  33639. if (faceColors) {
  33640. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33641. }
  33642. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33643. positions.push(vertex.x, vertex.y, vertex.z);
  33644. normals.push(normal.x, normal.y, normal.z);
  33645. uvs.push(faceUV[index].z, faceUV[index].y);
  33646. if (faceColors) {
  33647. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33648. }
  33649. }
  33650. // sides
  33651. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33652. // Result
  33653. var vertexData = new VertexData();
  33654. vertexData.indices = indices;
  33655. vertexData.positions = positions;
  33656. vertexData.normals = normals;
  33657. vertexData.uvs = uvs;
  33658. if (faceColors) {
  33659. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33660. vertexData.colors = totalColors;
  33661. }
  33662. return vertexData;
  33663. };
  33664. /**
  33665. * Creates the VertexData of the Sphere.
  33666. */
  33667. VertexData.CreateSphere = function (options) {
  33668. var segments = options.segments || 32;
  33669. var diameterX = options.diameterX || options.diameter || 1;
  33670. var diameterY = options.diameterY || options.diameter || 1;
  33671. var diameterZ = options.diameterZ || options.diameter || 1;
  33672. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33673. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33674. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33675. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33676. var totalZRotationSteps = 2 + segments;
  33677. var totalYRotationSteps = 2 * totalZRotationSteps;
  33678. var indices = [];
  33679. var positions = [];
  33680. var normals = [];
  33681. var uvs = [];
  33682. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33683. var normalizedZ = zRotationStep / totalZRotationSteps;
  33684. var angleZ = normalizedZ * Math.PI * slice;
  33685. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33686. var normalizedY = yRotationStep / totalYRotationSteps;
  33687. var angleY = normalizedY * Math.PI * 2 * arc;
  33688. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33689. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33690. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33691. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33692. var vertex = complete.multiply(radius);
  33693. var normal = complete.divide(radius).normalize();
  33694. positions.push(vertex.x, vertex.y, vertex.z);
  33695. normals.push(normal.x, normal.y, normal.z);
  33696. uvs.push(normalizedY, normalizedZ);
  33697. }
  33698. if (zRotationStep > 0) {
  33699. var verticesCount = positions.length / 3;
  33700. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33701. indices.push((firstIndex));
  33702. indices.push((firstIndex + 1));
  33703. indices.push(firstIndex + totalYRotationSteps + 1);
  33704. indices.push((firstIndex + totalYRotationSteps + 1));
  33705. indices.push((firstIndex + 1));
  33706. indices.push((firstIndex + totalYRotationSteps + 2));
  33707. }
  33708. }
  33709. }
  33710. // Sides
  33711. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33712. // Result
  33713. var vertexData = new VertexData();
  33714. vertexData.indices = indices;
  33715. vertexData.positions = positions;
  33716. vertexData.normals = normals;
  33717. vertexData.uvs = uvs;
  33718. return vertexData;
  33719. };
  33720. /**
  33721. * Creates the VertexData of the Cylinder or Cone.
  33722. */
  33723. VertexData.CreateCylinder = function (options) {
  33724. var height = options.height || 2;
  33725. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33726. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33727. var tessellation = options.tessellation || 24;
  33728. var subdivisions = options.subdivisions || 1;
  33729. var hasRings = options.hasRings ? true : false;
  33730. var enclose = options.enclose ? true : false;
  33731. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33732. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33733. var faceUV = options.faceUV || new Array(3);
  33734. var faceColors = options.faceColors;
  33735. // default face colors and UV if undefined
  33736. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33737. var ringNb = (hasRings) ? subdivisions : 1;
  33738. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33739. var f;
  33740. for (f = 0; f < surfaceNb; f++) {
  33741. if (faceColors && faceColors[f] === undefined) {
  33742. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33743. }
  33744. }
  33745. for (f = 0; f < surfaceNb; f++) {
  33746. if (faceUV && faceUV[f] === undefined) {
  33747. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33748. }
  33749. }
  33750. var indices = new Array();
  33751. var positions = new Array();
  33752. var normals = new Array();
  33753. var uvs = new Array();
  33754. var colors = new Array();
  33755. var angle_step = Math.PI * 2 * arc / tessellation;
  33756. var angle;
  33757. var h;
  33758. var radius;
  33759. var tan = (diameterBottom - diameterTop) / 2 / height;
  33760. var ringVertex = BABYLON.Vector3.Zero();
  33761. var ringNormal = BABYLON.Vector3.Zero();
  33762. var ringFirstVertex = BABYLON.Vector3.Zero();
  33763. var ringFirstNormal = BABYLON.Vector3.Zero();
  33764. var quadNormal = BABYLON.Vector3.Zero();
  33765. var Y = BABYLON.Axis.Y;
  33766. // positions, normals, uvs
  33767. var i;
  33768. var j;
  33769. var r;
  33770. var ringIdx = 1;
  33771. var s = 1; // surface index
  33772. var cs = 0;
  33773. var v = 0;
  33774. for (i = 0; i <= subdivisions; i++) {
  33775. h = i / subdivisions;
  33776. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33777. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33778. for (r = 0; r < ringIdx; r++) {
  33779. if (hasRings) {
  33780. s += r;
  33781. }
  33782. if (enclose) {
  33783. s += 2 * r;
  33784. }
  33785. for (j = 0; j <= tessellation; j++) {
  33786. angle = j * angle_step;
  33787. // position
  33788. ringVertex.x = Math.cos(-angle) * radius;
  33789. ringVertex.y = -height / 2 + h * height;
  33790. ringVertex.z = Math.sin(-angle) * radius;
  33791. // normal
  33792. if (diameterTop === 0 && i === subdivisions) {
  33793. // if no top cap, reuse former normals
  33794. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33795. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33796. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33797. }
  33798. else {
  33799. ringNormal.x = ringVertex.x;
  33800. ringNormal.z = ringVertex.z;
  33801. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33802. ringNormal.normalize();
  33803. }
  33804. // keep first ring vertex values for enclose
  33805. if (j === 0) {
  33806. ringFirstVertex.copyFrom(ringVertex);
  33807. ringFirstNormal.copyFrom(ringNormal);
  33808. }
  33809. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33810. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33811. if (hasRings) {
  33812. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33813. }
  33814. else {
  33815. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33816. }
  33817. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33818. if (faceColors) {
  33819. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33820. }
  33821. }
  33822. // if enclose, add four vertices and their dedicated normals
  33823. if (arc !== 1 && enclose) {
  33824. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33825. positions.push(0, ringVertex.y, 0);
  33826. positions.push(0, ringVertex.y, 0);
  33827. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33828. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33829. quadNormal.normalize();
  33830. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33831. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33832. quadNormal.normalize();
  33833. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33834. if (hasRings) {
  33835. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33836. }
  33837. else {
  33838. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33839. }
  33840. uvs.push(faceUV[s + 1].x, v);
  33841. uvs.push(faceUV[s + 1].z, v);
  33842. if (hasRings) {
  33843. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33844. }
  33845. else {
  33846. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33847. }
  33848. uvs.push(faceUV[s + 2].x, v);
  33849. uvs.push(faceUV[s + 2].z, v);
  33850. if (faceColors) {
  33851. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33852. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33853. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33854. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33855. }
  33856. }
  33857. if (cs !== s) {
  33858. cs = s;
  33859. }
  33860. }
  33861. }
  33862. // indices
  33863. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33864. var s;
  33865. i = 0;
  33866. for (s = 0; s < subdivisions; s++) {
  33867. var i0 = 0;
  33868. var i1 = 0;
  33869. var i2 = 0;
  33870. var i3 = 0;
  33871. for (j = 0; j < tessellation; j++) {
  33872. i0 = i * (e + 1) + j;
  33873. i1 = (i + 1) * (e + 1) + j;
  33874. i2 = i * (e + 1) + (j + 1);
  33875. i3 = (i + 1) * (e + 1) + (j + 1);
  33876. indices.push(i0, i1, i2);
  33877. indices.push(i3, i2, i1);
  33878. }
  33879. if (arc !== 1 && enclose) {
  33880. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33881. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33882. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33883. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33884. }
  33885. i = (hasRings) ? (i + 2) : (i + 1);
  33886. }
  33887. // Caps
  33888. var createCylinderCap = function (isTop) {
  33889. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33890. if (radius === 0) {
  33891. return;
  33892. }
  33893. // Cap positions, normals & uvs
  33894. var angle;
  33895. var circleVector;
  33896. var i;
  33897. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33898. var c = null;
  33899. if (faceColors) {
  33900. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33901. }
  33902. // cap center
  33903. var vbase = positions.length / 3;
  33904. var offset = isTop ? height / 2 : -height / 2;
  33905. var center = new BABYLON.Vector3(0, offset, 0);
  33906. positions.push(center.x, center.y, center.z);
  33907. normals.push(0, isTop ? 1 : -1, 0);
  33908. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33909. if (c) {
  33910. colors.push(c.r, c.g, c.b, c.a);
  33911. }
  33912. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33913. for (i = 0; i <= tessellation; i++) {
  33914. angle = Math.PI * 2 * i * arc / tessellation;
  33915. var cos = Math.cos(-angle);
  33916. var sin = Math.sin(-angle);
  33917. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33918. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33919. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33920. normals.push(0, isTop ? 1 : -1, 0);
  33921. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33922. if (c) {
  33923. colors.push(c.r, c.g, c.b, c.a);
  33924. }
  33925. }
  33926. // Cap indices
  33927. for (i = 0; i < tessellation; i++) {
  33928. if (!isTop) {
  33929. indices.push(vbase);
  33930. indices.push(vbase + (i + 1));
  33931. indices.push(vbase + (i + 2));
  33932. }
  33933. else {
  33934. indices.push(vbase);
  33935. indices.push(vbase + (i + 2));
  33936. indices.push(vbase + (i + 1));
  33937. }
  33938. }
  33939. };
  33940. // add caps to geometry
  33941. createCylinderCap(false);
  33942. createCylinderCap(true);
  33943. // Sides
  33944. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33945. var vertexData = new VertexData();
  33946. vertexData.indices = indices;
  33947. vertexData.positions = positions;
  33948. vertexData.normals = normals;
  33949. vertexData.uvs = uvs;
  33950. if (faceColors) {
  33951. vertexData.colors = colors;
  33952. }
  33953. return vertexData;
  33954. };
  33955. /**
  33956. * Creates the VertexData of the Torus.
  33957. */
  33958. VertexData.CreateTorus = function (options) {
  33959. var indices = [];
  33960. var positions = [];
  33961. var normals = [];
  33962. var uvs = [];
  33963. var diameter = options.diameter || 1;
  33964. var thickness = options.thickness || 0.5;
  33965. var tessellation = options.tessellation || 16;
  33966. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33967. var stride = tessellation + 1;
  33968. for (var i = 0; i <= tessellation; i++) {
  33969. var u = i / tessellation;
  33970. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33971. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33972. for (var j = 0; j <= tessellation; j++) {
  33973. var v = 1 - j / tessellation;
  33974. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33975. var dx = Math.cos(innerAngle);
  33976. var dy = Math.sin(innerAngle);
  33977. // Create a vertex.
  33978. var normal = new BABYLON.Vector3(dx, dy, 0);
  33979. var position = normal.scale(thickness / 2);
  33980. var textureCoordinate = new BABYLON.Vector2(u, v);
  33981. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33982. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33983. positions.push(position.x, position.y, position.z);
  33984. normals.push(normal.x, normal.y, normal.z);
  33985. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33986. // And create indices for two triangles.
  33987. var nextI = (i + 1) % stride;
  33988. var nextJ = (j + 1) % stride;
  33989. indices.push(i * stride + j);
  33990. indices.push(i * stride + nextJ);
  33991. indices.push(nextI * stride + j);
  33992. indices.push(i * stride + nextJ);
  33993. indices.push(nextI * stride + nextJ);
  33994. indices.push(nextI * stride + j);
  33995. }
  33996. }
  33997. // Sides
  33998. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33999. // Result
  34000. var vertexData = new VertexData();
  34001. vertexData.indices = indices;
  34002. vertexData.positions = positions;
  34003. vertexData.normals = normals;
  34004. vertexData.uvs = uvs;
  34005. return vertexData;
  34006. };
  34007. /**
  34008. * Creates the VertexData of the LineSystem.
  34009. */
  34010. VertexData.CreateLineSystem = function (options) {
  34011. var indices = [];
  34012. var positions = [];
  34013. var lines = options.lines;
  34014. var colors = options.colors;
  34015. var vertexColors = [];
  34016. var idx = 0;
  34017. for (var l = 0; l < lines.length; l++) {
  34018. var points = lines[l];
  34019. for (var index = 0; index < points.length; index++) {
  34020. positions.push(points[index].x, points[index].y, points[index].z);
  34021. if (colors) {
  34022. var color = colors[l];
  34023. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  34024. }
  34025. if (index > 0) {
  34026. indices.push(idx - 1);
  34027. indices.push(idx);
  34028. }
  34029. idx++;
  34030. }
  34031. }
  34032. var vertexData = new VertexData();
  34033. vertexData.indices = indices;
  34034. vertexData.positions = positions;
  34035. if (colors) {
  34036. vertexData.colors = vertexColors;
  34037. }
  34038. return vertexData;
  34039. };
  34040. /**
  34041. * Create the VertexData of the DashedLines.
  34042. */
  34043. VertexData.CreateDashedLines = function (options) {
  34044. var dashSize = options.dashSize || 3;
  34045. var gapSize = options.gapSize || 1;
  34046. var dashNb = options.dashNb || 200;
  34047. var points = options.points;
  34048. var positions = new Array();
  34049. var indices = new Array();
  34050. var curvect = BABYLON.Vector3.Zero();
  34051. var lg = 0;
  34052. var nb = 0;
  34053. var shft = 0;
  34054. var dashshft = 0;
  34055. var curshft = 0;
  34056. var idx = 0;
  34057. var i = 0;
  34058. for (i = 0; i < points.length - 1; i++) {
  34059. points[i + 1].subtractToRef(points[i], curvect);
  34060. lg += curvect.length();
  34061. }
  34062. shft = lg / dashNb;
  34063. dashshft = dashSize * shft / (dashSize + gapSize);
  34064. for (i = 0; i < points.length - 1; i++) {
  34065. points[i + 1].subtractToRef(points[i], curvect);
  34066. nb = Math.floor(curvect.length() / shft);
  34067. curvect.normalize();
  34068. for (var j = 0; j < nb; j++) {
  34069. curshft = shft * j;
  34070. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34071. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34072. indices.push(idx, idx + 1);
  34073. idx += 2;
  34074. }
  34075. }
  34076. // Result
  34077. var vertexData = new VertexData();
  34078. vertexData.positions = positions;
  34079. vertexData.indices = indices;
  34080. return vertexData;
  34081. };
  34082. /**
  34083. * Creates the VertexData of the Ground.
  34084. */
  34085. VertexData.CreateGround = function (options) {
  34086. var indices = [];
  34087. var positions = [];
  34088. var normals = [];
  34089. var uvs = [];
  34090. var row, col;
  34091. var width = options.width || 1;
  34092. var height = options.height || 1;
  34093. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34094. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34095. for (row = 0; row <= subdivisionsY; row++) {
  34096. for (col = 0; col <= subdivisionsX; col++) {
  34097. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34098. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34099. positions.push(position.x, position.y, position.z);
  34100. normals.push(normal.x, normal.y, normal.z);
  34101. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34102. }
  34103. }
  34104. for (row = 0; row < subdivisionsY; row++) {
  34105. for (col = 0; col < subdivisionsX; col++) {
  34106. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34107. indices.push(col + 1 + row * (subdivisionsX + 1));
  34108. indices.push(col + row * (subdivisionsX + 1));
  34109. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34110. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34111. indices.push(col + row * (subdivisionsX + 1));
  34112. }
  34113. }
  34114. // Result
  34115. var vertexData = new VertexData();
  34116. vertexData.indices = indices;
  34117. vertexData.positions = positions;
  34118. vertexData.normals = normals;
  34119. vertexData.uvs = uvs;
  34120. return vertexData;
  34121. };
  34122. /**
  34123. * Creates the VertexData of the TiledGround.
  34124. */
  34125. VertexData.CreateTiledGround = function (options) {
  34126. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  34127. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  34128. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  34129. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  34130. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34131. var precision = options.precision || { w: 1, h: 1 };
  34132. var indices = new Array();
  34133. var positions = new Array();
  34134. var normals = new Array();
  34135. var uvs = new Array();
  34136. var row, col, tileRow, tileCol;
  34137. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34138. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34139. precision.w = (precision.w < 1) ? 1 : precision.w;
  34140. precision.h = (precision.h < 1) ? 1 : precision.h;
  34141. var tileSize = {
  34142. 'w': (xmax - xmin) / subdivisions.w,
  34143. 'h': (zmax - zmin) / subdivisions.h
  34144. };
  34145. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34146. // Indices
  34147. var base = positions.length / 3;
  34148. var rowLength = precision.w + 1;
  34149. for (row = 0; row < precision.h; row++) {
  34150. for (col = 0; col < precision.w; col++) {
  34151. var square = [
  34152. base + col + row * rowLength,
  34153. base + (col + 1) + row * rowLength,
  34154. base + (col + 1) + (row + 1) * rowLength,
  34155. base + col + (row + 1) * rowLength
  34156. ];
  34157. indices.push(square[1]);
  34158. indices.push(square[2]);
  34159. indices.push(square[3]);
  34160. indices.push(square[0]);
  34161. indices.push(square[1]);
  34162. indices.push(square[3]);
  34163. }
  34164. }
  34165. // Position, normals and uvs
  34166. var position = BABYLON.Vector3.Zero();
  34167. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34168. for (row = 0; row <= precision.h; row++) {
  34169. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34170. for (col = 0; col <= precision.w; col++) {
  34171. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34172. position.y = 0;
  34173. positions.push(position.x, position.y, position.z);
  34174. normals.push(normal.x, normal.y, normal.z);
  34175. uvs.push(col / precision.w, row / precision.h);
  34176. }
  34177. }
  34178. }
  34179. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34180. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34181. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34182. }
  34183. }
  34184. // Result
  34185. var vertexData = new VertexData();
  34186. vertexData.indices = indices;
  34187. vertexData.positions = positions;
  34188. vertexData.normals = normals;
  34189. vertexData.uvs = uvs;
  34190. return vertexData;
  34191. };
  34192. /**
  34193. * Creates the VertexData of the Ground designed from a heightmap.
  34194. */
  34195. VertexData.CreateGroundFromHeightMap = function (options) {
  34196. var indices = [];
  34197. var positions = [];
  34198. var normals = [];
  34199. var uvs = [];
  34200. var row, col;
  34201. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  34202. // Vertices
  34203. for (row = 0; row <= options.subdivisions; row++) {
  34204. for (col = 0; col <= options.subdivisions; col++) {
  34205. 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));
  34206. // Compute height
  34207. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34208. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34209. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34210. var r = options.buffer[pos] / 255.0;
  34211. var g = options.buffer[pos + 1] / 255.0;
  34212. var b = options.buffer[pos + 2] / 255.0;
  34213. var gradient = r * filter.r + g * filter.g + b * filter.b;
  34214. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34215. // Add vertex
  34216. positions.push(position.x, position.y, position.z);
  34217. normals.push(0, 0, 0);
  34218. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34219. }
  34220. }
  34221. // Indices
  34222. for (row = 0; row < options.subdivisions; row++) {
  34223. for (col = 0; col < options.subdivisions; col++) {
  34224. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34225. indices.push(col + 1 + row * (options.subdivisions + 1));
  34226. indices.push(col + row * (options.subdivisions + 1));
  34227. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34228. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34229. indices.push(col + row * (options.subdivisions + 1));
  34230. }
  34231. }
  34232. // Normals
  34233. VertexData.ComputeNormals(positions, indices, normals);
  34234. // Result
  34235. var vertexData = new VertexData();
  34236. vertexData.indices = indices;
  34237. vertexData.positions = positions;
  34238. vertexData.normals = normals;
  34239. vertexData.uvs = uvs;
  34240. return vertexData;
  34241. };
  34242. /**
  34243. * Creates the VertexData of the Plane.
  34244. */
  34245. VertexData.CreatePlane = function (options) {
  34246. var indices = [];
  34247. var positions = [];
  34248. var normals = [];
  34249. var uvs = [];
  34250. var width = options.width || options.size || 1;
  34251. var height = options.height || options.size || 1;
  34252. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34253. // Vertices
  34254. var halfWidth = width / 2.0;
  34255. var halfHeight = height / 2.0;
  34256. positions.push(-halfWidth, -halfHeight, 0);
  34257. normals.push(0, 0, -1.0);
  34258. uvs.push(0.0, 0.0);
  34259. positions.push(halfWidth, -halfHeight, 0);
  34260. normals.push(0, 0, -1.0);
  34261. uvs.push(1.0, 0.0);
  34262. positions.push(halfWidth, halfHeight, 0);
  34263. normals.push(0, 0, -1.0);
  34264. uvs.push(1.0, 1.0);
  34265. positions.push(-halfWidth, halfHeight, 0);
  34266. normals.push(0, 0, -1.0);
  34267. uvs.push(0.0, 1.0);
  34268. // Indices
  34269. indices.push(0);
  34270. indices.push(1);
  34271. indices.push(2);
  34272. indices.push(0);
  34273. indices.push(2);
  34274. indices.push(3);
  34275. // Sides
  34276. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34277. // Result
  34278. var vertexData = new VertexData();
  34279. vertexData.indices = indices;
  34280. vertexData.positions = positions;
  34281. vertexData.normals = normals;
  34282. vertexData.uvs = uvs;
  34283. return vertexData;
  34284. };
  34285. /**
  34286. * Creates the VertexData of the Disc or regular Polygon.
  34287. */
  34288. VertexData.CreateDisc = function (options) {
  34289. var positions = new Array();
  34290. var indices = new Array();
  34291. var normals = new Array();
  34292. var uvs = new Array();
  34293. var radius = options.radius || 0.5;
  34294. var tessellation = options.tessellation || 64;
  34295. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34296. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34297. // positions and uvs
  34298. positions.push(0, 0, 0); // disc center first
  34299. uvs.push(0.5, 0.5);
  34300. var theta = Math.PI * 2 * arc;
  34301. var step = theta / tessellation;
  34302. for (var a = 0; a < theta; a += step) {
  34303. var x = Math.cos(a);
  34304. var y = Math.sin(a);
  34305. var u = (x + 1) / 2;
  34306. var v = (1 - y) / 2;
  34307. positions.push(radius * x, radius * y, 0);
  34308. uvs.push(u, v);
  34309. }
  34310. if (arc === 1) {
  34311. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34312. uvs.push(uvs[2], uvs[3]);
  34313. }
  34314. //indices
  34315. var vertexNb = positions.length / 3;
  34316. for (var i = 1; i < vertexNb - 1; i++) {
  34317. indices.push(i + 1, 0, i);
  34318. }
  34319. // result
  34320. VertexData.ComputeNormals(positions, indices, normals);
  34321. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34322. var vertexData = new VertexData();
  34323. vertexData.indices = indices;
  34324. vertexData.positions = positions;
  34325. vertexData.normals = normals;
  34326. vertexData.uvs = uvs;
  34327. return vertexData;
  34328. };
  34329. /**
  34330. * Re-creates the VertexData of the Polygon for sideOrientation.
  34331. */
  34332. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  34333. var faceUV = fUV || new Array(3);
  34334. var faceColors = fColors;
  34335. var colors = [];
  34336. // default face colors and UV if undefined
  34337. for (var f = 0; f < 3; f++) {
  34338. if (faceUV[f] === undefined) {
  34339. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34340. }
  34341. if (faceColors && faceColors[f] === undefined) {
  34342. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34343. }
  34344. }
  34345. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34346. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34347. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34348. var indices = polygon.getIndices();
  34349. // set face colours and textures
  34350. var idx = 0;
  34351. var face = 0;
  34352. for (var index = 0; index < normals.length; index += 3) {
  34353. //Edge Face no. 1
  34354. if (Math.abs(normals[index + 1]) < 0.001) {
  34355. face = 1;
  34356. }
  34357. //Top Face no. 0
  34358. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  34359. face = 0;
  34360. }
  34361. //Bottom Face no. 2
  34362. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34363. face = 2;
  34364. }
  34365. idx = index / 3;
  34366. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34367. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34368. if (faceColors) {
  34369. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34370. }
  34371. }
  34372. // sides
  34373. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34374. // Result
  34375. var vertexData = new VertexData();
  34376. vertexData.indices = indices;
  34377. vertexData.positions = positions;
  34378. vertexData.normals = normals;
  34379. vertexData.uvs = uvs;
  34380. if (faceColors) {
  34381. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34382. vertexData.colors = totalColors;
  34383. }
  34384. return vertexData;
  34385. };
  34386. /**
  34387. * Creates the VertexData of the IcoSphere.
  34388. */
  34389. VertexData.CreateIcoSphere = function (options) {
  34390. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34391. var radius = options.radius || 1;
  34392. var flat = (options.flat === undefined) ? true : options.flat;
  34393. var subdivisions = options.subdivisions || 4;
  34394. var radiusX = options.radiusX || radius;
  34395. var radiusY = options.radiusY || radius;
  34396. var radiusZ = options.radiusZ || radius;
  34397. var t = (1 + Math.sqrt(5)) / 2;
  34398. // 12 vertex x,y,z
  34399. var ico_vertices = [
  34400. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34401. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34402. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34403. ];
  34404. // index of 3 vertex makes a face of icopshere
  34405. var ico_indices = [
  34406. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34407. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34408. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34409. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34410. ];
  34411. // vertex for uv have aliased position, not for UV
  34412. var vertices_unalias_id = [
  34413. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34414. // vertex alias
  34415. 0,
  34416. 2,
  34417. 3,
  34418. 3,
  34419. 3,
  34420. 4,
  34421. 7,
  34422. 8,
  34423. 9,
  34424. 9,
  34425. 10,
  34426. 11 // 23: B + 12
  34427. ];
  34428. // uv as integer step (not pixels !)
  34429. var ico_vertexuv = [
  34430. 5, 1, 3, 1, 6, 4, 0, 0,
  34431. 5, 3, 4, 2, 2, 2, 4, 0,
  34432. 2, 0, 1, 1, 6, 0, 6, 2,
  34433. // vertex alias (for same vertex on different faces)
  34434. 0, 4,
  34435. 3, 3,
  34436. 4, 4,
  34437. 3, 1,
  34438. 4, 2,
  34439. 4, 4,
  34440. 0, 2,
  34441. 1, 1,
  34442. 2, 2,
  34443. 3, 3,
  34444. 1, 3,
  34445. 2, 4 // 23: B + 12
  34446. ];
  34447. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34448. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34449. // First island of uv mapping
  34450. // v = 4h 3+ 2
  34451. // v = 3h 9+ 4
  34452. // v = 2h 9+ 5 B
  34453. // v = 1h 9 1 0
  34454. // v = 0h 3 8 7 A
  34455. // u = 0 1 2 3 4 5 6 *a
  34456. // Second island of uv mapping
  34457. // v = 4h 0+ B+ 4+
  34458. // v = 3h A+ 2+
  34459. // v = 2h 7+ 6 3+
  34460. // v = 1h 8+ 3+
  34461. // v = 0h
  34462. // u = 0 1 2 3 4 5 6 *a
  34463. // Face layout on texture UV mapping
  34464. // ============
  34465. // \ 4 /\ 16 / ======
  34466. // \ / \ / /\ 11 /
  34467. // \/ 7 \/ / \ /
  34468. // ======= / 10 \/
  34469. // /\ 17 /\ =======
  34470. // / \ / \ \ 15 /\
  34471. // / 8 \/ 12 \ \ / \
  34472. // ============ \/ 6 \
  34473. // \ 18 /\ ============
  34474. // \ / \ \ 5 /\ 0 /
  34475. // \/ 13 \ \ / \ /
  34476. // ======= \/ 1 \/
  34477. // =============
  34478. // /\ 19 /\ 2 /\
  34479. // / \ / \ / \
  34480. // / 14 \/ 9 \/ 3 \
  34481. // ===================
  34482. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34483. var ustep = 138 / 1024;
  34484. var vstep = 239 / 1024;
  34485. var uoffset = 60 / 1024;
  34486. var voffset = 26 / 1024;
  34487. // Second island should have margin, not to touch the first island
  34488. // avoid any borderline artefact in pixel rounding
  34489. var island_u_offset = -40 / 1024;
  34490. var island_v_offset = +20 / 1024;
  34491. // face is either island 0 or 1 :
  34492. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34493. var island = [
  34494. 0, 0, 0, 0, 1,
  34495. 0, 0, 1, 1, 0,
  34496. 0, 0, 1, 1, 0,
  34497. 0, 1, 1, 1, 0 // 15 - 19
  34498. ];
  34499. var indices = new Array();
  34500. var positions = new Array();
  34501. var normals = new Array();
  34502. var uvs = new Array();
  34503. var current_indice = 0;
  34504. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34505. var face_vertex_pos = new Array(3);
  34506. var face_vertex_uv = new Array(3);
  34507. var v012;
  34508. for (v012 = 0; v012 < 3; v012++) {
  34509. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34510. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34511. }
  34512. // create all with normals
  34513. for (var face = 0; face < 20; face++) {
  34514. // 3 vertex per face
  34515. for (v012 = 0; v012 < 3; v012++) {
  34516. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34517. var v_id = ico_indices[3 * face + v012];
  34518. // vertex have 3D position (x,y,z)
  34519. 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]);
  34520. // Normalize to get normal, then scale to radius
  34521. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34522. // uv Coordinates from vertex ID
  34523. 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);
  34524. }
  34525. // Subdivide the face (interpolate pos, norm, uv)
  34526. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34527. // - norm is linear interpolation of vertex corner normal
  34528. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34529. // - uv is linear interpolation
  34530. //
  34531. // Topology is as below for sub-divide by 2
  34532. // vertex shown as v0,v1,v2
  34533. // interp index is i1 to progress in range [v0,v1[
  34534. // interp index is i2 to progress in range [v0,v2[
  34535. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34536. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34537. //
  34538. //
  34539. // i2 v2
  34540. // ^ ^
  34541. // / / \
  34542. // / / \
  34543. // / / \
  34544. // / / (0,1) \
  34545. // / #---------\
  34546. // / / \ (0,0)'/ \
  34547. // / / \ / \
  34548. // / / \ / \
  34549. // / / (0,0) \ / (1,0) \
  34550. // / #---------#---------\
  34551. // v0 v1
  34552. //
  34553. // --------------------> i1
  34554. //
  34555. // interp of (i1,i2):
  34556. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34557. // along i1 : lerp(x0,x1, i1/(S-i2))
  34558. //
  34559. // centroid of triangle is needed to get help normal computation
  34560. // (c1,c2) are used for centroid location
  34561. var interp_vertex = function (i1, i2, c1, c2) {
  34562. // vertex is interpolated from
  34563. // - face_vertex_pos[0..2]
  34564. // - face_vertex_uv[0..2]
  34565. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34566. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34567. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34568. pos_interp.normalize();
  34569. var vertex_normal;
  34570. if (flat) {
  34571. // in flat mode, recalculate normal as face centroid normal
  34572. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34573. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34574. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34575. }
  34576. else {
  34577. // in smooth mode, recalculate normal from each single vertex position
  34578. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34579. }
  34580. // Vertex normal need correction due to X,Y,Z radius scaling
  34581. vertex_normal.x /= radiusX;
  34582. vertex_normal.y /= radiusY;
  34583. vertex_normal.z /= radiusZ;
  34584. vertex_normal.normalize();
  34585. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34586. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34587. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34588. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34589. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34590. uvs.push(uv_interp.x, uv_interp.y);
  34591. // push each vertex has member of a face
  34592. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34593. indices.push(current_indice);
  34594. current_indice++;
  34595. };
  34596. for (var i2 = 0; i2 < subdivisions; i2++) {
  34597. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34598. // face : (i1,i2) for /\ :
  34599. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34600. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34601. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34602. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34603. if (i1 + i2 + 1 < subdivisions) {
  34604. // face : (i1,i2)' for \/ :
  34605. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34606. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34607. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34608. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34609. }
  34610. }
  34611. }
  34612. }
  34613. // Sides
  34614. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34615. // Result
  34616. var vertexData = new VertexData();
  34617. vertexData.indices = indices;
  34618. vertexData.positions = positions;
  34619. vertexData.normals = normals;
  34620. vertexData.uvs = uvs;
  34621. return vertexData;
  34622. };
  34623. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34624. /**
  34625. * Creates the VertexData of the Polyhedron.
  34626. */
  34627. VertexData.CreatePolyhedron = function (options) {
  34628. // provided polyhedron types :
  34629. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34630. // 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)
  34631. var polyhedra = [];
  34632. 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]] };
  34633. 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]] };
  34634. polyhedra[2] = {
  34635. 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]],
  34636. 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]]
  34637. };
  34638. polyhedra[3] = {
  34639. 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]],
  34640. 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]]
  34641. };
  34642. polyhedra[4] = {
  34643. 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]],
  34644. 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]]
  34645. };
  34646. 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]] };
  34647. 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]] };
  34648. 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]] };
  34649. 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]] };
  34650. 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]] };
  34651. 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]] };
  34652. 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]] };
  34653. 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]] };
  34654. 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]] };
  34655. polyhedra[14] = {
  34656. 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]],
  34657. 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]]
  34658. };
  34659. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34660. var size = options.size;
  34661. var sizeX = options.sizeX || size || 1;
  34662. var sizeY = options.sizeY || size || 1;
  34663. var sizeZ = options.sizeZ || size || 1;
  34664. var data = options.custom || polyhedra[type];
  34665. var nbfaces = data.face.length;
  34666. var faceUV = options.faceUV || new Array(nbfaces);
  34667. var faceColors = options.faceColors;
  34668. var flat = (options.flat === undefined) ? true : options.flat;
  34669. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34670. var positions = new Array();
  34671. var indices = new Array();
  34672. var normals = new Array();
  34673. var uvs = new Array();
  34674. var colors = new Array();
  34675. var index = 0;
  34676. var faceIdx = 0; // face cursor in the array "indexes"
  34677. var indexes = new Array();
  34678. var i = 0;
  34679. var f = 0;
  34680. var u, v, ang, x, y, tmp;
  34681. // default face colors and UV if undefined
  34682. if (flat) {
  34683. for (f = 0; f < nbfaces; f++) {
  34684. if (faceColors && faceColors[f] === undefined) {
  34685. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34686. }
  34687. if (faceUV && faceUV[f] === undefined) {
  34688. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34689. }
  34690. }
  34691. }
  34692. if (!flat) {
  34693. for (i = 0; i < data.vertex.length; i++) {
  34694. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34695. uvs.push(0, 0);
  34696. }
  34697. for (f = 0; f < nbfaces; f++) {
  34698. for (i = 0; i < data.face[f].length - 2; i++) {
  34699. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34700. }
  34701. }
  34702. }
  34703. else {
  34704. for (f = 0; f < nbfaces; f++) {
  34705. var fl = data.face[f].length; // number of vertices of the current face
  34706. ang = 2 * Math.PI / fl;
  34707. x = 0.5 * Math.tan(ang / 2);
  34708. y = 0.5;
  34709. // positions, uvs, colors
  34710. for (i = 0; i < fl; i++) {
  34711. // positions
  34712. 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);
  34713. indexes.push(index);
  34714. index++;
  34715. // uvs
  34716. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34717. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34718. uvs.push(u, v);
  34719. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34720. y = x * Math.sin(ang) + y * Math.cos(ang);
  34721. x = tmp;
  34722. // colors
  34723. if (faceColors) {
  34724. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34725. }
  34726. }
  34727. // indices from indexes
  34728. for (i = 0; i < fl - 2; i++) {
  34729. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34730. }
  34731. faceIdx += fl;
  34732. }
  34733. }
  34734. VertexData.ComputeNormals(positions, indices, normals);
  34735. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34736. var vertexData = new VertexData();
  34737. vertexData.positions = positions;
  34738. vertexData.indices = indices;
  34739. vertexData.normals = normals;
  34740. vertexData.uvs = uvs;
  34741. if (faceColors && flat) {
  34742. vertexData.colors = colors;
  34743. }
  34744. return vertexData;
  34745. };
  34746. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34747. /**
  34748. * Creates the VertexData of the Torus Knot.
  34749. */
  34750. VertexData.CreateTorusKnot = function (options) {
  34751. var indices = new Array();
  34752. var positions = new Array();
  34753. var normals = new Array();
  34754. var uvs = new Array();
  34755. var radius = options.radius || 2;
  34756. var tube = options.tube || 0.5;
  34757. var radialSegments = options.radialSegments || 32;
  34758. var tubularSegments = options.tubularSegments || 32;
  34759. var p = options.p || 2;
  34760. var q = options.q || 3;
  34761. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34762. // Helper
  34763. var getPos = function (angle) {
  34764. var cu = Math.cos(angle);
  34765. var su = Math.sin(angle);
  34766. var quOverP = q / p * angle;
  34767. var cs = Math.cos(quOverP);
  34768. var tx = radius * (2 + cs) * 0.5 * cu;
  34769. var ty = radius * (2 + cs) * su * 0.5;
  34770. var tz = radius * Math.sin(quOverP) * 0.5;
  34771. return new BABYLON.Vector3(tx, ty, tz);
  34772. };
  34773. // Vertices
  34774. var i;
  34775. var j;
  34776. for (i = 0; i <= radialSegments; i++) {
  34777. var modI = i % radialSegments;
  34778. var u = modI / radialSegments * 2 * p * Math.PI;
  34779. var p1 = getPos(u);
  34780. var p2 = getPos(u + 0.01);
  34781. var tang = p2.subtract(p1);
  34782. var n = p2.add(p1);
  34783. var bitan = BABYLON.Vector3.Cross(tang, n);
  34784. n = BABYLON.Vector3.Cross(bitan, tang);
  34785. bitan.normalize();
  34786. n.normalize();
  34787. for (j = 0; j < tubularSegments; j++) {
  34788. var modJ = j % tubularSegments;
  34789. var v = modJ / tubularSegments * 2 * Math.PI;
  34790. var cx = -tube * Math.cos(v);
  34791. var cy = tube * Math.sin(v);
  34792. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34793. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34794. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34795. uvs.push(i / radialSegments);
  34796. uvs.push(j / tubularSegments);
  34797. }
  34798. }
  34799. for (i = 0; i < radialSegments; i++) {
  34800. for (j = 0; j < tubularSegments; j++) {
  34801. var jNext = (j + 1) % tubularSegments;
  34802. var a = i * tubularSegments + j;
  34803. var b = (i + 1) * tubularSegments + j;
  34804. var c = (i + 1) * tubularSegments + jNext;
  34805. var d = i * tubularSegments + jNext;
  34806. indices.push(d);
  34807. indices.push(b);
  34808. indices.push(a);
  34809. indices.push(d);
  34810. indices.push(c);
  34811. indices.push(b);
  34812. }
  34813. }
  34814. // Normals
  34815. VertexData.ComputeNormals(positions, indices, normals);
  34816. // Sides
  34817. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34818. // Result
  34819. var vertexData = new VertexData();
  34820. vertexData.indices = indices;
  34821. vertexData.positions = positions;
  34822. vertexData.normals = normals;
  34823. vertexData.uvs = uvs;
  34824. return vertexData;
  34825. };
  34826. // Tools
  34827. /**
  34828. * @param {any} - positions (number[] or Float32Array)
  34829. * @param {any} - indices (number[] or Uint16Array)
  34830. * @param {any} - normals (number[] or Float32Array)
  34831. * options (optional) :
  34832. * facetPositions : optional array of facet positions (vector3)
  34833. * facetNormals : optional array of facet normals (vector3)
  34834. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34835. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34836. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34837. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34838. * bInfo : optional bounding info, required for facetPartitioning computation
  34839. * useRightHandedSystem: optional boolean to for right handed system computation
  34840. * depthSort : optional boolean to enable the facet depth sort computation
  34841. * distanceTo : optional Vector3 to compute the facet depth from this location
  34842. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34843. */
  34844. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34845. // temporary scalar variables
  34846. var index = 0; // facet index
  34847. var p1p2x = 0.0; // p1p2 vector x coordinate
  34848. var p1p2y = 0.0; // p1p2 vector y coordinate
  34849. var p1p2z = 0.0; // p1p2 vector z coordinate
  34850. var p3p2x = 0.0; // p3p2 vector x coordinate
  34851. var p3p2y = 0.0; // p3p2 vector y coordinate
  34852. var p3p2z = 0.0; // p3p2 vector z coordinate
  34853. var faceNormalx = 0.0; // facet normal x coordinate
  34854. var faceNormaly = 0.0; // facet normal y coordinate
  34855. var faceNormalz = 0.0; // facet normal z coordinate
  34856. var length = 0.0; // facet normal length before normalization
  34857. var v1x = 0; // vector1 x index in the positions array
  34858. var v1y = 0; // vector1 y index in the positions array
  34859. var v1z = 0; // vector1 z index in the positions array
  34860. var v2x = 0; // vector2 x index in the positions array
  34861. var v2y = 0; // vector2 y index in the positions array
  34862. var v2z = 0; // vector2 z index in the positions array
  34863. var v3x = 0; // vector3 x index in the positions array
  34864. var v3y = 0; // vector3 y index in the positions array
  34865. var v3z = 0; // vector3 z index in the positions array
  34866. var computeFacetNormals = false;
  34867. var computeFacetPositions = false;
  34868. var computeFacetPartitioning = false;
  34869. var computeDepthSort = false;
  34870. var faceNormalSign = 1;
  34871. var ratio = 0;
  34872. var distanceTo = null;
  34873. if (options) {
  34874. computeFacetNormals = (options.facetNormals) ? true : false;
  34875. computeFacetPositions = (options.facetPositions) ? true : false;
  34876. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34877. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34878. ratio = options.ratio || 0;
  34879. computeDepthSort = (options.depthSort) ? true : false;
  34880. distanceTo = (options.distanceTo);
  34881. if (computeDepthSort) {
  34882. if (distanceTo === undefined) {
  34883. distanceTo = BABYLON.Vector3.Zero();
  34884. }
  34885. var depthSortedFacets = options.depthSortedFacets;
  34886. }
  34887. }
  34888. // facetPartitioning reinit if needed
  34889. var xSubRatio = 0;
  34890. var ySubRatio = 0;
  34891. var zSubRatio = 0;
  34892. var subSq = 0;
  34893. if (computeFacetPartitioning && options && options.bbSize) {
  34894. var ox = 0; // X partitioning index for facet position
  34895. var oy = 0; // Y partinioning index for facet position
  34896. var oz = 0; // Z partinioning index for facet position
  34897. var b1x = 0; // X partitioning index for facet v1 vertex
  34898. var b1y = 0; // Y partitioning index for facet v1 vertex
  34899. var b1z = 0; // z partitioning index for facet v1 vertex
  34900. var b2x = 0; // X partitioning index for facet v2 vertex
  34901. var b2y = 0; // Y partitioning index for facet v2 vertex
  34902. var b2z = 0; // Z partitioning index for facet v2 vertex
  34903. var b3x = 0; // X partitioning index for facet v3 vertex
  34904. var b3y = 0; // Y partitioning index for facet v3 vertex
  34905. var b3z = 0; // Z partitioning index for facet v3 vertex
  34906. var block_idx_o = 0; // facet barycenter block index
  34907. var block_idx_v1 = 0; // v1 vertex block index
  34908. var block_idx_v2 = 0; // v2 vertex block index
  34909. var block_idx_v3 = 0; // v3 vertex block index
  34910. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34911. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34912. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34913. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34914. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34915. subSq = options.subDiv.max * options.subDiv.max;
  34916. options.facetPartitioning.length = 0;
  34917. }
  34918. // reset the normals
  34919. for (index = 0; index < positions.length; index++) {
  34920. normals[index] = 0.0;
  34921. }
  34922. // Loop : 1 indice triplet = 1 facet
  34923. var nbFaces = (indices.length / 3) | 0;
  34924. for (index = 0; index < nbFaces; index++) {
  34925. // get the indexes of the coordinates of each vertex of the facet
  34926. v1x = indices[index * 3] * 3;
  34927. v1y = v1x + 1;
  34928. v1z = v1x + 2;
  34929. v2x = indices[index * 3 + 1] * 3;
  34930. v2y = v2x + 1;
  34931. v2z = v2x + 2;
  34932. v3x = indices[index * 3 + 2] * 3;
  34933. v3y = v3x + 1;
  34934. v3z = v3x + 2;
  34935. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34936. p1p2y = positions[v1y] - positions[v2y];
  34937. p1p2z = positions[v1z] - positions[v2z];
  34938. p3p2x = positions[v3x] - positions[v2x];
  34939. p3p2y = positions[v3y] - positions[v2y];
  34940. p3p2z = positions[v3z] - positions[v2z];
  34941. // compute the face normal with the cross product
  34942. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34943. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34944. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34945. // normalize this normal and store it in the array facetData
  34946. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34947. length = (length === 0) ? 1.0 : length;
  34948. faceNormalx /= length;
  34949. faceNormaly /= length;
  34950. faceNormalz /= length;
  34951. if (computeFacetNormals && options) {
  34952. options.facetNormals[index].x = faceNormalx;
  34953. options.facetNormals[index].y = faceNormaly;
  34954. options.facetNormals[index].z = faceNormalz;
  34955. }
  34956. if (computeFacetPositions && options) {
  34957. // compute and the facet barycenter coordinates in the array facetPositions
  34958. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34959. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34960. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34961. }
  34962. if (computeFacetPartitioning && options) {
  34963. // store the facet indexes in arrays in the main facetPartitioning array :
  34964. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34965. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34966. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34967. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34968. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34969. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34970. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34971. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34972. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34973. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34974. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34975. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34976. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34977. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34978. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34979. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34980. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34981. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34982. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34983. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34984. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34985. // push each facet index in each block containing the vertex
  34986. options.facetPartitioning[block_idx_v1].push(index);
  34987. if (block_idx_v2 != block_idx_v1) {
  34988. options.facetPartitioning[block_idx_v2].push(index);
  34989. }
  34990. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34991. options.facetPartitioning[block_idx_v3].push(index);
  34992. }
  34993. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34994. options.facetPartitioning[block_idx_o].push(index);
  34995. }
  34996. }
  34997. if (computeDepthSort && options && options.facetPositions) {
  34998. var dsf = depthSortedFacets[index];
  34999. dsf.ind = index * 3;
  35000. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  35001. }
  35002. // compute the normals anyway
  35003. normals[v1x] += faceNormalx; // accumulate all the normals per face
  35004. normals[v1y] += faceNormaly;
  35005. normals[v1z] += faceNormalz;
  35006. normals[v2x] += faceNormalx;
  35007. normals[v2y] += faceNormaly;
  35008. normals[v2z] += faceNormalz;
  35009. normals[v3x] += faceNormalx;
  35010. normals[v3y] += faceNormaly;
  35011. normals[v3z] += faceNormalz;
  35012. }
  35013. // last normalization of each normal
  35014. for (index = 0; index < normals.length / 3; index++) {
  35015. faceNormalx = normals[index * 3];
  35016. faceNormaly = normals[index * 3 + 1];
  35017. faceNormalz = normals[index * 3 + 2];
  35018. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  35019. length = (length === 0) ? 1.0 : length;
  35020. faceNormalx /= length;
  35021. faceNormaly /= length;
  35022. faceNormalz /= length;
  35023. normals[index * 3] = faceNormalx;
  35024. normals[index * 3 + 1] = faceNormaly;
  35025. normals[index * 3 + 2] = faceNormalz;
  35026. }
  35027. };
  35028. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  35029. var li = indices.length;
  35030. var ln = normals.length;
  35031. var i;
  35032. var n;
  35033. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35034. switch (sideOrientation) {
  35035. case BABYLON.Mesh.FRONTSIDE:
  35036. // nothing changed
  35037. break;
  35038. case BABYLON.Mesh.BACKSIDE:
  35039. var tmp;
  35040. // indices
  35041. for (i = 0; i < li; i += 3) {
  35042. tmp = indices[i];
  35043. indices[i] = indices[i + 2];
  35044. indices[i + 2] = tmp;
  35045. }
  35046. // normals
  35047. for (n = 0; n < ln; n++) {
  35048. normals[n] = -normals[n];
  35049. }
  35050. break;
  35051. case BABYLON.Mesh.DOUBLESIDE:
  35052. // positions
  35053. var lp = positions.length;
  35054. var l = lp / 3;
  35055. for (var p = 0; p < lp; p++) {
  35056. positions[lp + p] = positions[p];
  35057. }
  35058. // indices
  35059. for (i = 0; i < li; i += 3) {
  35060. indices[i + li] = indices[i + 2] + l;
  35061. indices[i + 1 + li] = indices[i + 1] + l;
  35062. indices[i + 2 + li] = indices[i] + l;
  35063. }
  35064. // normals
  35065. for (n = 0; n < ln; n++) {
  35066. normals[ln + n] = -normals[n];
  35067. }
  35068. // uvs
  35069. var lu = uvs.length;
  35070. var u = 0;
  35071. for (u = 0; u < lu; u++) {
  35072. uvs[u + lu] = uvs[u];
  35073. }
  35074. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35075. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35076. u = 0;
  35077. for (i = 0; i < lu / 2; i++) {
  35078. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  35079. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  35080. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  35081. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  35082. u += 2;
  35083. }
  35084. break;
  35085. }
  35086. };
  35087. /**
  35088. * Creates a new VertexData from the imported parameters.
  35089. */
  35090. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35091. var vertexData = new VertexData();
  35092. // positions
  35093. var positions = parsedVertexData.positions;
  35094. if (positions) {
  35095. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35096. }
  35097. // normals
  35098. var normals = parsedVertexData.normals;
  35099. if (normals) {
  35100. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35101. }
  35102. // tangents
  35103. var tangents = parsedVertexData.tangents;
  35104. if (tangents) {
  35105. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  35106. }
  35107. // uvs
  35108. var uvs = parsedVertexData.uvs;
  35109. if (uvs) {
  35110. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35111. }
  35112. // uv2s
  35113. var uv2s = parsedVertexData.uv2s;
  35114. if (uv2s) {
  35115. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35116. }
  35117. // uv3s
  35118. var uv3s = parsedVertexData.uv3s;
  35119. if (uv3s) {
  35120. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35121. }
  35122. // uv4s
  35123. var uv4s = parsedVertexData.uv4s;
  35124. if (uv4s) {
  35125. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35126. }
  35127. // uv5s
  35128. var uv5s = parsedVertexData.uv5s;
  35129. if (uv5s) {
  35130. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35131. }
  35132. // uv6s
  35133. var uv6s = parsedVertexData.uv6s;
  35134. if (uv6s) {
  35135. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35136. }
  35137. // colors
  35138. var colors = parsedVertexData.colors;
  35139. if (colors) {
  35140. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35141. }
  35142. // matricesIndices
  35143. var matricesIndices = parsedVertexData.matricesIndices;
  35144. if (matricesIndices) {
  35145. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35146. }
  35147. // matricesWeights
  35148. var matricesWeights = parsedVertexData.matricesWeights;
  35149. if (matricesWeights) {
  35150. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35151. }
  35152. // indices
  35153. var indices = parsedVertexData.indices;
  35154. if (indices) {
  35155. vertexData.indices = indices;
  35156. }
  35157. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35158. };
  35159. return VertexData;
  35160. }());
  35161. BABYLON.VertexData = VertexData;
  35162. })(BABYLON || (BABYLON = {}));
  35163. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35164. "use strict";
  35165. var BABYLON;
  35166. (function (BABYLON) {
  35167. /**
  35168. * Class used to store geometry data (vertex buffers + index buffer)
  35169. */
  35170. var Geometry = /** @class */ (function () {
  35171. /**
  35172. * Creates a new geometry
  35173. * @param id defines the unique ID
  35174. * @param scene defines the hosting scene
  35175. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  35176. * @param updatable defines if geometry must be updatable (false by default)
  35177. * @param mesh defines the mesh that will be associated with the geometry
  35178. */
  35179. function Geometry(id, scene, vertexData, updatable, mesh) {
  35180. if (updatable === void 0) { updatable = false; }
  35181. if (mesh === void 0) { mesh = null; }
  35182. /**
  35183. * Gets the delay loading state of the geometry (none by default which means not delayed)
  35184. */
  35185. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35186. this._totalVertices = 0;
  35187. this._isDisposed = false;
  35188. this._indexBufferIsUpdatable = false;
  35189. this.id = id;
  35190. this._engine = scene.getEngine();
  35191. this._meshes = [];
  35192. this._scene = scene;
  35193. //Init vertex buffer cache
  35194. this._vertexBuffers = {};
  35195. this._indices = [];
  35196. this._updatable = updatable;
  35197. // vertexData
  35198. if (vertexData) {
  35199. this.setAllVerticesData(vertexData, updatable);
  35200. }
  35201. else {
  35202. this._totalVertices = 0;
  35203. this._indices = [];
  35204. }
  35205. if (this._engine.getCaps().vertexArrayObject) {
  35206. this._vertexArrayObjects = {};
  35207. }
  35208. // applyToMesh
  35209. if (mesh) {
  35210. if (mesh.getClassName() === "LinesMesh") {
  35211. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35212. this.updateExtend();
  35213. }
  35214. this.applyToMesh(mesh);
  35215. mesh.computeWorldMatrix(true);
  35216. }
  35217. }
  35218. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35219. /**
  35220. * 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
  35221. */
  35222. get: function () {
  35223. return this._boundingBias;
  35224. },
  35225. /**
  35226. * 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
  35227. */
  35228. set: function (value) {
  35229. if (this._boundingBias && this._boundingBias.equals(value)) {
  35230. return;
  35231. }
  35232. this._boundingBias = value.clone();
  35233. this.updateBoundingInfo(true, null);
  35234. },
  35235. enumerable: true,
  35236. configurable: true
  35237. });
  35238. /**
  35239. * Static function used to attach a new empty geometry to a mesh
  35240. * @param mesh defines the mesh to attach the geometry to
  35241. * @returns the new {BABYLON.Geometry}
  35242. */
  35243. Geometry.CreateGeometryForMesh = function (mesh) {
  35244. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  35245. geometry.applyToMesh(mesh);
  35246. return geometry;
  35247. };
  35248. Object.defineProperty(Geometry.prototype, "extend", {
  35249. /**
  35250. * Gets the current extend of the geometry
  35251. */
  35252. get: function () {
  35253. return this._extend;
  35254. },
  35255. enumerable: true,
  35256. configurable: true
  35257. });
  35258. /**
  35259. * Gets the hosting scene
  35260. * @returns the hosting {BABYLON.Scene}
  35261. */
  35262. Geometry.prototype.getScene = function () {
  35263. return this._scene;
  35264. };
  35265. /**
  35266. * Gets the hosting engine
  35267. * @returns the hosting {BABYLON.Engine}
  35268. */
  35269. Geometry.prototype.getEngine = function () {
  35270. return this._engine;
  35271. };
  35272. /**
  35273. * Defines if the geometry is ready to use
  35274. * @returns true if the geometry is ready to be used
  35275. */
  35276. Geometry.prototype.isReady = function () {
  35277. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35278. };
  35279. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  35280. /**
  35281. * Gets a value indicating that the geometry should not be serialized
  35282. */
  35283. get: function () {
  35284. for (var index = 0; index < this._meshes.length; index++) {
  35285. if (!this._meshes[index].doNotSerialize) {
  35286. return false;
  35287. }
  35288. }
  35289. return true;
  35290. },
  35291. enumerable: true,
  35292. configurable: true
  35293. });
  35294. /** @ignore */
  35295. Geometry.prototype._rebuild = function () {
  35296. if (this._vertexArrayObjects) {
  35297. this._vertexArrayObjects = {};
  35298. }
  35299. // Index buffer
  35300. if (this._meshes.length !== 0 && this._indices) {
  35301. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35302. }
  35303. // Vertex buffers
  35304. for (var key in this._vertexBuffers) {
  35305. var vertexBuffer = this._vertexBuffers[key];
  35306. vertexBuffer._rebuild();
  35307. }
  35308. };
  35309. /**
  35310. * Affects all gemetry data in one call
  35311. * @param vertexData defines the geometry data
  35312. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  35313. */
  35314. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35315. vertexData.applyToGeometry(this, updatable);
  35316. this.notifyUpdate();
  35317. };
  35318. /**
  35319. * Set specific vertex data
  35320. * @param kind defines the data kind (Position, normal, etc...)
  35321. * @param data defines the vertex data to use
  35322. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  35323. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  35324. */
  35325. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35326. if (updatable === void 0) { updatable = false; }
  35327. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35328. this.setVerticesBuffer(buffer);
  35329. };
  35330. /**
  35331. * Removes a specific vertex data
  35332. * @param kind defines the data kind (Position, normal, etc...)
  35333. */
  35334. Geometry.prototype.removeVerticesData = function (kind) {
  35335. if (this._vertexBuffers[kind]) {
  35336. this._vertexBuffers[kind].dispose();
  35337. delete this._vertexBuffers[kind];
  35338. }
  35339. };
  35340. /**
  35341. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  35342. * @param buffer defines the vertex buffer to use
  35343. */
  35344. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35345. var kind = buffer.getKind();
  35346. if (this._vertexBuffers[kind]) {
  35347. this._vertexBuffers[kind].dispose();
  35348. }
  35349. this._vertexBuffers[kind] = buffer;
  35350. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35351. var data = buffer.getData();
  35352. var stride = buffer.getStrideSize();
  35353. this._totalVertices = data.length / stride;
  35354. this.updateExtend(data, stride);
  35355. this._resetPointsArrayCache();
  35356. var meshes = this._meshes;
  35357. var numOfMeshes = meshes.length;
  35358. for (var index = 0; index < numOfMeshes; index++) {
  35359. var mesh = meshes[index];
  35360. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35361. mesh._createGlobalSubMesh(false);
  35362. mesh.computeWorldMatrix(true);
  35363. }
  35364. }
  35365. this.notifyUpdate(kind);
  35366. if (this._vertexArrayObjects) {
  35367. this._disposeVertexArrayObjects();
  35368. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35369. }
  35370. };
  35371. /**
  35372. * Update a specific vertex buffer
  35373. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35374. * It will do nothing if the buffer is not updatable
  35375. * @param kind defines the data kind (Position, normal, etc...)
  35376. * @param data defines the data to use
  35377. * @param offset defines the offset in the target buffer where to store the data
  35378. */
  35379. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35380. var vertexBuffer = this.getVertexBuffer(kind);
  35381. if (!vertexBuffer) {
  35382. return;
  35383. }
  35384. vertexBuffer.updateDirectly(data, offset);
  35385. this.notifyUpdate(kind);
  35386. };
  35387. /**
  35388. * Update a specific vertex buffer
  35389. * This function will create a new buffer if the current one is not updatable
  35390. * @param kind defines the data kind (Position, normal, etc...)
  35391. * @param data defines the data to use
  35392. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35393. */
  35394. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35395. if (updateExtends === void 0) { updateExtends = false; }
  35396. var vertexBuffer = this.getVertexBuffer(kind);
  35397. if (!vertexBuffer) {
  35398. return;
  35399. }
  35400. vertexBuffer.update(data);
  35401. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35402. var stride = vertexBuffer.getStrideSize();
  35403. this._totalVertices = data.length / stride;
  35404. this.updateBoundingInfo(updateExtends, data);
  35405. }
  35406. this.notifyUpdate(kind);
  35407. };
  35408. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35409. if (updateExtends) {
  35410. this.updateExtend(data);
  35411. }
  35412. var meshes = this._meshes;
  35413. var numOfMeshes = meshes.length;
  35414. this._resetPointsArrayCache();
  35415. for (var index = 0; index < numOfMeshes; index++) {
  35416. var mesh = meshes[index];
  35417. if (updateExtends) {
  35418. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35419. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35420. var subMesh = mesh.subMeshes[subIndex];
  35421. subMesh.refreshBoundingInfo();
  35422. }
  35423. }
  35424. }
  35425. };
  35426. /** @ignore */
  35427. Geometry.prototype._bind = function (effect, indexToBind) {
  35428. if (!effect) {
  35429. return;
  35430. }
  35431. if (indexToBind === undefined) {
  35432. indexToBind = this._indexBuffer;
  35433. }
  35434. var vbs = this.getVertexBuffers();
  35435. if (!vbs) {
  35436. return;
  35437. }
  35438. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35439. this._engine.bindBuffers(vbs, indexToBind, effect);
  35440. return;
  35441. }
  35442. // Using VAO
  35443. if (!this._vertexArrayObjects[effect.key]) {
  35444. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35445. }
  35446. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35447. };
  35448. /**
  35449. * Gets total number of vertices
  35450. * @returns the total number of vertices
  35451. */
  35452. Geometry.prototype.getTotalVertices = function () {
  35453. if (!this.isReady()) {
  35454. return 0;
  35455. }
  35456. return this._totalVertices;
  35457. };
  35458. /**
  35459. * Gets a specific vertex data attached to this geometry
  35460. * @param kind defines the data kind (Position, normal, etc...)
  35461. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35462. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35463. * @returns a float array containing vertex data
  35464. */
  35465. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35466. var vertexBuffer = this.getVertexBuffer(kind);
  35467. if (!vertexBuffer) {
  35468. return null;
  35469. }
  35470. var orig = vertexBuffer.getData();
  35471. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35472. return orig;
  35473. }
  35474. else {
  35475. var len = orig.length;
  35476. var copy = [];
  35477. for (var i = 0; i < len; i++) {
  35478. copy.push(orig[i]);
  35479. }
  35480. return copy;
  35481. }
  35482. };
  35483. /**
  35484. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35485. * @param kind defines the data kind (Position, normal, etc...)
  35486. * @returns true if the vertex buffer with the specified kind is updatable
  35487. */
  35488. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35489. var vb = this._vertexBuffers[kind];
  35490. if (!vb) {
  35491. return false;
  35492. }
  35493. return vb.isUpdatable();
  35494. };
  35495. /**
  35496. * Gets a specific vertex buffer
  35497. * @param kind defines the data kind (Position, normal, etc...)
  35498. * @returns a {BABYLON.VertexBuffer}
  35499. */
  35500. Geometry.prototype.getVertexBuffer = function (kind) {
  35501. if (!this.isReady()) {
  35502. return null;
  35503. }
  35504. return this._vertexBuffers[kind];
  35505. };
  35506. /**
  35507. * Returns all vertex buffers
  35508. * @return an object holding all vertex buffers indexed by kind
  35509. */
  35510. Geometry.prototype.getVertexBuffers = function () {
  35511. if (!this.isReady()) {
  35512. return null;
  35513. }
  35514. return this._vertexBuffers;
  35515. };
  35516. /**
  35517. * Gets a boolean indicating if specific vertex buffer is present
  35518. * @param kind defines the data kind (Position, normal, etc...)
  35519. * @returns true if data is present
  35520. */
  35521. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35522. if (!this._vertexBuffers) {
  35523. if (this._delayInfo) {
  35524. return this._delayInfo.indexOf(kind) !== -1;
  35525. }
  35526. return false;
  35527. }
  35528. return this._vertexBuffers[kind] !== undefined;
  35529. };
  35530. /**
  35531. * Gets a list of all attached data kinds (Position, normal, etc...)
  35532. * @returns a list of string containing all kinds
  35533. */
  35534. Geometry.prototype.getVerticesDataKinds = function () {
  35535. var result = [];
  35536. var kind;
  35537. if (!this._vertexBuffers && this._delayInfo) {
  35538. for (kind in this._delayInfo) {
  35539. result.push(kind);
  35540. }
  35541. }
  35542. else {
  35543. for (kind in this._vertexBuffers) {
  35544. result.push(kind);
  35545. }
  35546. }
  35547. return result;
  35548. };
  35549. /**
  35550. * Update index buffer
  35551. * @param indices defines the indices to store in the index buffer
  35552. * @param offset defines the offset in the target buffer where to store the data
  35553. */
  35554. Geometry.prototype.updateIndices = function (indices, offset) {
  35555. if (!this._indexBuffer) {
  35556. return;
  35557. }
  35558. if (!this._indexBufferIsUpdatable) {
  35559. this.setIndices(indices, null, true);
  35560. }
  35561. else {
  35562. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35563. }
  35564. };
  35565. /**
  35566. * Creates a new index buffer
  35567. * @param indices defines the indices to store in the index buffer
  35568. * @param totalVertices defines the total number of vertices (could be null)
  35569. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35570. */
  35571. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35572. if (totalVertices === void 0) { totalVertices = null; }
  35573. if (updatable === void 0) { updatable = false; }
  35574. if (this._indexBuffer) {
  35575. this._engine._releaseBuffer(this._indexBuffer);
  35576. }
  35577. this._disposeVertexArrayObjects();
  35578. this._indices = indices;
  35579. this._indexBufferIsUpdatable = updatable;
  35580. if (this._meshes.length !== 0 && this._indices) {
  35581. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35582. }
  35583. if (totalVertices != undefined) {
  35584. this._totalVertices = totalVertices;
  35585. }
  35586. var meshes = this._meshes;
  35587. var numOfMeshes = meshes.length;
  35588. for (var index = 0; index < numOfMeshes; index++) {
  35589. meshes[index]._createGlobalSubMesh(true);
  35590. }
  35591. this.notifyUpdate();
  35592. };
  35593. /**
  35594. * Return the total number of indices
  35595. * @returns the total number of indices
  35596. */
  35597. Geometry.prototype.getTotalIndices = function () {
  35598. if (!this.isReady()) {
  35599. return 0;
  35600. }
  35601. return this._indices.length;
  35602. };
  35603. /**
  35604. * Gets the index buffer array
  35605. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35606. * @returns the index buffer array
  35607. */
  35608. Geometry.prototype.getIndices = function (copyWhenShared) {
  35609. if (!this.isReady()) {
  35610. return null;
  35611. }
  35612. var orig = this._indices;
  35613. if (!copyWhenShared || this._meshes.length === 1) {
  35614. return orig;
  35615. }
  35616. else {
  35617. var len = orig.length;
  35618. var copy = [];
  35619. for (var i = 0; i < len; i++) {
  35620. copy.push(orig[i]);
  35621. }
  35622. return copy;
  35623. }
  35624. };
  35625. /**
  35626. * Gets the index buffer
  35627. * @return the index buffer
  35628. */
  35629. Geometry.prototype.getIndexBuffer = function () {
  35630. if (!this.isReady()) {
  35631. return null;
  35632. }
  35633. return this._indexBuffer;
  35634. };
  35635. /** @ignore */
  35636. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35637. if (effect === void 0) { effect = null; }
  35638. if (!effect || !this._vertexArrayObjects) {
  35639. return;
  35640. }
  35641. if (this._vertexArrayObjects[effect.key]) {
  35642. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35643. delete this._vertexArrayObjects[effect.key];
  35644. }
  35645. };
  35646. /**
  35647. * Release the associated resources for a specific mesh
  35648. * @param mesh defines the source mesh
  35649. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35650. */
  35651. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35652. var meshes = this._meshes;
  35653. var index = meshes.indexOf(mesh);
  35654. if (index === -1) {
  35655. return;
  35656. }
  35657. meshes.splice(index, 1);
  35658. mesh._geometry = null;
  35659. if (meshes.length === 0 && shouldDispose) {
  35660. this.dispose();
  35661. }
  35662. };
  35663. /**
  35664. * Apply current geometry to a given mesh
  35665. * @param mesh defines the mesh to apply geometry to
  35666. */
  35667. Geometry.prototype.applyToMesh = function (mesh) {
  35668. if (mesh._geometry === this) {
  35669. return;
  35670. }
  35671. var previousGeometry = mesh._geometry;
  35672. if (previousGeometry) {
  35673. previousGeometry.releaseForMesh(mesh);
  35674. }
  35675. var meshes = this._meshes;
  35676. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35677. mesh._geometry = this;
  35678. this._scene.pushGeometry(this);
  35679. meshes.push(mesh);
  35680. if (this.isReady()) {
  35681. this._applyToMesh(mesh);
  35682. }
  35683. else {
  35684. mesh._boundingInfo = this._boundingInfo;
  35685. }
  35686. };
  35687. Geometry.prototype.updateExtend = function (data, stride) {
  35688. if (data === void 0) { data = null; }
  35689. if (!data) {
  35690. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35691. }
  35692. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35693. };
  35694. Geometry.prototype._applyToMesh = function (mesh) {
  35695. var numOfMeshes = this._meshes.length;
  35696. // vertexBuffers
  35697. for (var kind in this._vertexBuffers) {
  35698. if (numOfMeshes === 1) {
  35699. this._vertexBuffers[kind].create();
  35700. }
  35701. var buffer = this._vertexBuffers[kind].getBuffer();
  35702. if (buffer)
  35703. buffer.references = numOfMeshes;
  35704. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35705. if (!this._extend) {
  35706. this.updateExtend(this._vertexBuffers[kind].getData());
  35707. }
  35708. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35709. mesh._createGlobalSubMesh(false);
  35710. //bounding info was just created again, world matrix should be applied again.
  35711. mesh._updateBoundingInfo();
  35712. }
  35713. }
  35714. // indexBuffer
  35715. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35716. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35717. }
  35718. if (this._indexBuffer) {
  35719. this._indexBuffer.references = numOfMeshes;
  35720. }
  35721. };
  35722. Geometry.prototype.notifyUpdate = function (kind) {
  35723. if (this.onGeometryUpdated) {
  35724. this.onGeometryUpdated(this, kind);
  35725. }
  35726. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35727. var mesh = _a[_i];
  35728. mesh._markSubMeshesAsAttributesDirty();
  35729. }
  35730. };
  35731. /**
  35732. * Load the geometry if it was flagged as delay loaded
  35733. * @param scene defines the hosting scene
  35734. * @param onLoaded defines a callback called when the geometry is loaded
  35735. */
  35736. Geometry.prototype.load = function (scene, onLoaded) {
  35737. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35738. return;
  35739. }
  35740. if (this.isReady()) {
  35741. if (onLoaded) {
  35742. onLoaded();
  35743. }
  35744. return;
  35745. }
  35746. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35747. this._queueLoad(scene, onLoaded);
  35748. };
  35749. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35750. var _this = this;
  35751. if (!this.delayLoadingFile) {
  35752. return;
  35753. }
  35754. scene._addPendingData(this);
  35755. scene._loadFile(this.delayLoadingFile, function (data) {
  35756. if (!_this._delayLoadingFunction) {
  35757. return;
  35758. }
  35759. _this._delayLoadingFunction(JSON.parse(data), _this);
  35760. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35761. _this._delayInfo = [];
  35762. scene._removePendingData(_this);
  35763. var meshes = _this._meshes;
  35764. var numOfMeshes = meshes.length;
  35765. for (var index = 0; index < numOfMeshes; index++) {
  35766. _this._applyToMesh(meshes[index]);
  35767. }
  35768. if (onLoaded) {
  35769. onLoaded();
  35770. }
  35771. }, undefined, true);
  35772. };
  35773. /**
  35774. * Invert the geometry to move from a right handed system to a left handed one.
  35775. */
  35776. Geometry.prototype.toLeftHanded = function () {
  35777. // Flip faces
  35778. var tIndices = this.getIndices(false);
  35779. if (tIndices != null && tIndices.length > 0) {
  35780. for (var i = 0; i < tIndices.length; i += 3) {
  35781. var tTemp = tIndices[i + 0];
  35782. tIndices[i + 0] = tIndices[i + 2];
  35783. tIndices[i + 2] = tTemp;
  35784. }
  35785. this.setIndices(tIndices);
  35786. }
  35787. // Negate position.z
  35788. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35789. if (tPositions != null && tPositions.length > 0) {
  35790. for (var i = 0; i < tPositions.length; i += 3) {
  35791. tPositions[i + 2] = -tPositions[i + 2];
  35792. }
  35793. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35794. }
  35795. // Negate normal.z
  35796. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35797. if (tNormals != null && tNormals.length > 0) {
  35798. for (var i = 0; i < tNormals.length; i += 3) {
  35799. tNormals[i + 2] = -tNormals[i + 2];
  35800. }
  35801. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35802. }
  35803. };
  35804. // Cache
  35805. /** @ignore */
  35806. Geometry.prototype._resetPointsArrayCache = function () {
  35807. this._positions = null;
  35808. };
  35809. /** @ignore */
  35810. Geometry.prototype._generatePointsArray = function () {
  35811. if (this._positions)
  35812. return true;
  35813. this._positions = [];
  35814. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35815. if (!data) {
  35816. return false;
  35817. }
  35818. for (var index = 0; index < data.length; index += 3) {
  35819. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35820. }
  35821. return true;
  35822. };
  35823. /**
  35824. * Gets a value indicating if the geometry is disposed
  35825. * @returns true if the geometry was disposed
  35826. */
  35827. Geometry.prototype.isDisposed = function () {
  35828. return this._isDisposed;
  35829. };
  35830. Geometry.prototype._disposeVertexArrayObjects = function () {
  35831. if (this._vertexArrayObjects) {
  35832. for (var kind in this._vertexArrayObjects) {
  35833. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35834. }
  35835. this._vertexArrayObjects = {};
  35836. }
  35837. };
  35838. /**
  35839. * Free all associated resources
  35840. */
  35841. Geometry.prototype.dispose = function () {
  35842. var meshes = this._meshes;
  35843. var numOfMeshes = meshes.length;
  35844. var index;
  35845. for (index = 0; index < numOfMeshes; index++) {
  35846. this.releaseForMesh(meshes[index]);
  35847. }
  35848. this._meshes = [];
  35849. this._disposeVertexArrayObjects();
  35850. for (var kind in this._vertexBuffers) {
  35851. this._vertexBuffers[kind].dispose();
  35852. }
  35853. this._vertexBuffers = {};
  35854. this._totalVertices = 0;
  35855. if (this._indexBuffer) {
  35856. this._engine._releaseBuffer(this._indexBuffer);
  35857. }
  35858. this._indexBuffer = null;
  35859. this._indices = [];
  35860. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35861. this.delayLoadingFile = null;
  35862. this._delayLoadingFunction = null;
  35863. this._delayInfo = [];
  35864. this._boundingInfo = null;
  35865. this._scene.removeGeometry(this);
  35866. this._isDisposed = true;
  35867. };
  35868. /**
  35869. * Clone the current geometry into a new geometry
  35870. * @param id defines the unique ID of the new geometry
  35871. * @returns a new geometry object
  35872. */
  35873. Geometry.prototype.copy = function (id) {
  35874. var vertexData = new BABYLON.VertexData();
  35875. vertexData.indices = [];
  35876. var indices = this.getIndices();
  35877. if (indices) {
  35878. for (var index = 0; index < indices.length; index++) {
  35879. vertexData.indices.push(indices[index]);
  35880. }
  35881. }
  35882. var updatable = false;
  35883. var stopChecking = false;
  35884. var kind;
  35885. for (kind in this._vertexBuffers) {
  35886. // using slice() to make a copy of the array and not just reference it
  35887. var data = this.getVerticesData(kind);
  35888. if (data instanceof Float32Array) {
  35889. vertexData.set(new Float32Array(data), kind);
  35890. }
  35891. else {
  35892. vertexData.set(data.slice(0), kind);
  35893. }
  35894. if (!stopChecking) {
  35895. var vb = this.getVertexBuffer(kind);
  35896. if (vb) {
  35897. updatable = vb.isUpdatable();
  35898. stopChecking = !updatable;
  35899. }
  35900. }
  35901. }
  35902. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35903. geometry.delayLoadState = this.delayLoadState;
  35904. geometry.delayLoadingFile = this.delayLoadingFile;
  35905. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35906. for (kind in this._delayInfo) {
  35907. geometry._delayInfo = geometry._delayInfo || [];
  35908. geometry._delayInfo.push(kind);
  35909. }
  35910. // Bounding info
  35911. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35912. return geometry;
  35913. };
  35914. /**
  35915. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35916. * @return a JSON representation of the current geometry data (without the vertices data)
  35917. */
  35918. Geometry.prototype.serialize = function () {
  35919. var serializationObject = {};
  35920. serializationObject.id = this.id;
  35921. serializationObject.updatable = this._updatable;
  35922. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35923. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35924. }
  35925. return serializationObject;
  35926. };
  35927. Geometry.prototype.toNumberArray = function (origin) {
  35928. if (Array.isArray(origin)) {
  35929. return origin;
  35930. }
  35931. else {
  35932. return Array.prototype.slice.call(origin);
  35933. }
  35934. };
  35935. /**
  35936. * Serialize all vertices data into a JSON oject
  35937. * @returns a JSON representation of the current geometry data
  35938. */
  35939. Geometry.prototype.serializeVerticeData = function () {
  35940. var serializationObject = this.serialize();
  35941. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35942. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35943. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35944. serializationObject.positions._updatable = true;
  35945. }
  35946. }
  35947. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35948. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35949. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35950. serializationObject.normals._updatable = true;
  35951. }
  35952. }
  35953. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35954. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35955. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35956. serializationObject.tangets._updatable = true;
  35957. }
  35958. }
  35959. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35960. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35961. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35962. serializationObject.uvs._updatable = true;
  35963. }
  35964. }
  35965. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35966. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35967. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35968. serializationObject.uv2s._updatable = true;
  35969. }
  35970. }
  35971. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35972. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35973. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35974. serializationObject.uv3s._updatable = true;
  35975. }
  35976. }
  35977. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35978. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35979. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35980. serializationObject.uv4s._updatable = true;
  35981. }
  35982. }
  35983. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35984. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35985. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35986. serializationObject.uv5s._updatable = true;
  35987. }
  35988. }
  35989. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35990. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35991. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35992. serializationObject.uv6s._updatable = true;
  35993. }
  35994. }
  35995. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35996. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35997. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35998. serializationObject.colors._updatable = true;
  35999. }
  36000. }
  36001. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36002. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  36003. serializationObject.matricesIndices._isExpanded = true;
  36004. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36005. serializationObject.matricesIndices._updatable = true;
  36006. }
  36007. }
  36008. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36009. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  36010. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36011. serializationObject.matricesWeights._updatable = true;
  36012. }
  36013. }
  36014. serializationObject.indices = this.toNumberArray(this.getIndices());
  36015. return serializationObject;
  36016. };
  36017. // Statics
  36018. /**
  36019. * Extracts a clone of a mesh geometry
  36020. * @param mesh defines the source mesh
  36021. * @param id defines the unique ID of the new geometry object
  36022. * @returns the new geometry object
  36023. */
  36024. Geometry.ExtractFromMesh = function (mesh, id) {
  36025. var geometry = mesh._geometry;
  36026. if (!geometry) {
  36027. return null;
  36028. }
  36029. return geometry.copy(id);
  36030. };
  36031. /**
  36032. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36033. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36034. * Be aware Math.random() could cause collisions, but:
  36035. * "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"
  36036. * @returns a string containing a new GUID
  36037. */
  36038. Geometry.RandomId = function () {
  36039. return BABYLON.Tools.RandomId();
  36040. };
  36041. /** @ignore */
  36042. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  36043. var scene = mesh.getScene();
  36044. // Geometry
  36045. var geometryId = parsedGeometry.geometryId;
  36046. if (geometryId) {
  36047. var geometry = scene.getGeometryByID(geometryId);
  36048. if (geometry) {
  36049. geometry.applyToMesh(mesh);
  36050. }
  36051. }
  36052. else if (parsedGeometry instanceof ArrayBuffer) {
  36053. var binaryInfo = mesh._binaryInfo;
  36054. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36055. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36056. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36057. }
  36058. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36059. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36060. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36061. }
  36062. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  36063. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  36064. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  36065. }
  36066. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36067. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36068. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36069. }
  36070. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36071. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36072. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36073. }
  36074. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36075. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36076. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36077. }
  36078. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36079. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36080. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36081. }
  36082. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36083. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36084. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36085. }
  36086. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36087. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36088. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36089. }
  36090. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36091. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36092. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36093. }
  36094. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36095. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36096. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36097. }
  36098. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36099. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36100. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36101. }
  36102. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36103. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36104. mesh.setIndices(indicesData, null);
  36105. }
  36106. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36107. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36108. mesh.subMeshes = [];
  36109. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36110. var materialIndex = subMeshesData[(i * 5) + 0];
  36111. var verticesStart = subMeshesData[(i * 5) + 1];
  36112. var verticesCount = subMeshesData[(i * 5) + 2];
  36113. var indexStart = subMeshesData[(i * 5) + 3];
  36114. var indexCount = subMeshesData[(i * 5) + 4];
  36115. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36116. }
  36117. }
  36118. }
  36119. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36120. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  36121. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  36122. if (parsedGeometry.tangents) {
  36123. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  36124. }
  36125. if (parsedGeometry.uvs) {
  36126. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  36127. }
  36128. if (parsedGeometry.uvs2) {
  36129. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  36130. }
  36131. if (parsedGeometry.uvs3) {
  36132. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  36133. }
  36134. if (parsedGeometry.uvs4) {
  36135. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  36136. }
  36137. if (parsedGeometry.uvs5) {
  36138. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  36139. }
  36140. if (parsedGeometry.uvs6) {
  36141. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  36142. }
  36143. if (parsedGeometry.colors) {
  36144. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  36145. }
  36146. if (parsedGeometry.matricesIndices) {
  36147. if (!parsedGeometry.matricesIndices._isExpanded) {
  36148. var floatIndices = [];
  36149. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36150. var matricesIndex = parsedGeometry.matricesIndices[i];
  36151. floatIndices.push(matricesIndex & 0x000000FF);
  36152. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36153. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36154. floatIndices.push(matricesIndex >> 24);
  36155. }
  36156. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  36157. }
  36158. else {
  36159. delete parsedGeometry.matricesIndices._isExpanded;
  36160. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  36161. }
  36162. }
  36163. if (parsedGeometry.matricesIndicesExtra) {
  36164. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36165. var floatIndices = [];
  36166. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36167. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36168. floatIndices.push(matricesIndex & 0x000000FF);
  36169. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36170. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36171. floatIndices.push(matricesIndex >> 24);
  36172. }
  36173. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  36174. }
  36175. else {
  36176. delete parsedGeometry.matricesIndices._isExpanded;
  36177. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  36178. }
  36179. }
  36180. if (parsedGeometry.matricesWeights) {
  36181. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  36182. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  36183. }
  36184. if (parsedGeometry.matricesWeightsExtra) {
  36185. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  36186. }
  36187. mesh.setIndices(parsedGeometry.indices, null);
  36188. }
  36189. // SubMeshes
  36190. if (parsedGeometry.subMeshes) {
  36191. mesh.subMeshes = [];
  36192. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36193. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36194. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36195. }
  36196. }
  36197. // Flat shading
  36198. if (mesh._shouldGenerateFlatShading) {
  36199. mesh.convertToFlatShadedMesh();
  36200. delete mesh._shouldGenerateFlatShading;
  36201. }
  36202. // Update
  36203. mesh.computeWorldMatrix(true);
  36204. // Octree
  36205. var sceneOctree = scene.selectionOctree;
  36206. if (sceneOctree !== undefined && sceneOctree !== null) {
  36207. sceneOctree.addMesh(mesh);
  36208. }
  36209. };
  36210. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  36211. var epsilon = 1e-3;
  36212. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  36213. return;
  36214. }
  36215. var noInfluenceBoneIndex = 0.0;
  36216. if (parsedGeometry.skeletonId > -1) {
  36217. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  36218. if (!skeleton) {
  36219. return;
  36220. }
  36221. noInfluenceBoneIndex = skeleton.bones.length;
  36222. }
  36223. else {
  36224. return;
  36225. }
  36226. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36227. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36228. var matricesWeights = parsedGeometry.matricesWeights;
  36229. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  36230. var influencers = parsedGeometry.numBoneInfluencer;
  36231. var size = matricesWeights.length;
  36232. for (var i = 0; i < size; i += 4) {
  36233. var weight = 0.0;
  36234. var firstZeroWeight = -1;
  36235. for (var j = 0; j < 4; j++) {
  36236. var w = matricesWeights[i + j];
  36237. weight += w;
  36238. if (w < epsilon && firstZeroWeight < 0) {
  36239. firstZeroWeight = j;
  36240. }
  36241. }
  36242. if (matricesWeightsExtra) {
  36243. for (var j = 0; j < 4; j++) {
  36244. var w = matricesWeightsExtra[i + j];
  36245. weight += w;
  36246. if (w < epsilon && firstZeroWeight < 0) {
  36247. firstZeroWeight = j + 4;
  36248. }
  36249. }
  36250. }
  36251. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  36252. firstZeroWeight = influencers - 1;
  36253. }
  36254. if (weight > epsilon) {
  36255. var mweight = 1.0 / weight;
  36256. for (var j = 0; j < 4; j++) {
  36257. matricesWeights[i + j] *= mweight;
  36258. }
  36259. if (matricesWeightsExtra) {
  36260. for (var j = 0; j < 4; j++) {
  36261. matricesWeightsExtra[i + j] *= mweight;
  36262. }
  36263. }
  36264. }
  36265. else {
  36266. if (firstZeroWeight >= 4) {
  36267. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  36268. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  36269. }
  36270. else {
  36271. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  36272. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  36273. }
  36274. }
  36275. }
  36276. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  36277. if (parsedGeometry.matricesWeightsExtra) {
  36278. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  36279. }
  36280. };
  36281. /**
  36282. * Create a new geometry from persisted data (Using .babylon file format)
  36283. * @param parsedVertexData defines the persisted data
  36284. * @param scene defines the hosting scene
  36285. * @param rootUrl defines the root url to use to load assets (like delayed data)
  36286. * @returns the new geometry object
  36287. */
  36288. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36289. if (scene.getGeometryByID(parsedVertexData.id)) {
  36290. return null; // null since geometry could be something else than a box...
  36291. }
  36292. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  36293. if (BABYLON.Tags) {
  36294. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36295. }
  36296. if (parsedVertexData.delayLoadingFile) {
  36297. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36298. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36299. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36300. geometry._delayInfo = [];
  36301. if (parsedVertexData.hasUVs) {
  36302. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36303. }
  36304. if (parsedVertexData.hasUVs2) {
  36305. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36306. }
  36307. if (parsedVertexData.hasUVs3) {
  36308. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36309. }
  36310. if (parsedVertexData.hasUVs4) {
  36311. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36312. }
  36313. if (parsedVertexData.hasUVs5) {
  36314. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36315. }
  36316. if (parsedVertexData.hasUVs6) {
  36317. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36318. }
  36319. if (parsedVertexData.hasColors) {
  36320. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36321. }
  36322. if (parsedVertexData.hasMatricesIndices) {
  36323. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36324. }
  36325. if (parsedVertexData.hasMatricesWeights) {
  36326. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36327. }
  36328. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36329. }
  36330. else {
  36331. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36332. }
  36333. scene.pushGeometry(geometry, true);
  36334. return geometry;
  36335. };
  36336. return Geometry;
  36337. }());
  36338. BABYLON.Geometry = Geometry;
  36339. // Primitives
  36340. /// Abstract class
  36341. /**
  36342. * Abstract class used to provide common services for all typed geometries
  36343. */
  36344. var _PrimitiveGeometry = /** @class */ (function (_super) {
  36345. __extends(_PrimitiveGeometry, _super);
  36346. /**
  36347. * Creates a new typed geometry
  36348. * @param id defines the unique ID of the geometry
  36349. * @param scene defines the hosting scene
  36350. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36351. * @param mesh defines the hosting mesh (can be null)
  36352. */
  36353. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  36354. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  36355. if (mesh === void 0) { mesh = null; }
  36356. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  36357. _this._canBeRegenerated = _canBeRegenerated;
  36358. _this._beingRegenerated = true;
  36359. _this.regenerate();
  36360. _this._beingRegenerated = false;
  36361. return _this;
  36362. }
  36363. /**
  36364. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36365. * @returns true if the geometry can be regenerated
  36366. */
  36367. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36368. return this._canBeRegenerated;
  36369. };
  36370. /**
  36371. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36372. */
  36373. _PrimitiveGeometry.prototype.regenerate = function () {
  36374. if (!this._canBeRegenerated) {
  36375. return;
  36376. }
  36377. this._beingRegenerated = true;
  36378. this.setAllVerticesData(this._regenerateVertexData(), false);
  36379. this._beingRegenerated = false;
  36380. };
  36381. /**
  36382. * Clone the geometry
  36383. * @param id defines the unique ID of the new geometry
  36384. * @returns the new geometry
  36385. */
  36386. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36387. return _super.prototype.copy.call(this, id);
  36388. };
  36389. // overrides
  36390. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36391. if (!this._beingRegenerated) {
  36392. return;
  36393. }
  36394. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36395. };
  36396. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36397. if (!this._beingRegenerated) {
  36398. return;
  36399. }
  36400. _super.prototype.setVerticesData.call(this, kind, data, false);
  36401. };
  36402. // to override
  36403. /** @ignore */
  36404. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36405. throw new Error("Abstract method");
  36406. };
  36407. _PrimitiveGeometry.prototype.copy = function (id) {
  36408. throw new Error("Must be overriden in sub-classes.");
  36409. };
  36410. _PrimitiveGeometry.prototype.serialize = function () {
  36411. var serializationObject = _super.prototype.serialize.call(this);
  36412. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36413. return serializationObject;
  36414. };
  36415. return _PrimitiveGeometry;
  36416. }(Geometry));
  36417. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36418. /**
  36419. * Creates a ribbon geometry
  36420. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36421. */
  36422. var RibbonGeometry = /** @class */ (function (_super) {
  36423. __extends(RibbonGeometry, _super);
  36424. /**
  36425. * Creates a ribbon geometry
  36426. * @param id defines the unique ID of the geometry
  36427. * @param scene defines the hosting scene
  36428. * @param pathArray defines the array of paths to use
  36429. * @param closeArray defines if the last path and the first path must be joined
  36430. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36431. * @param offset defines the offset between points
  36432. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36433. * @param mesh defines the hosting mesh (can be null)
  36434. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36435. */
  36436. function RibbonGeometry(id, scene,
  36437. /**
  36438. * Defines the array of paths to use
  36439. */
  36440. pathArray,
  36441. /**
  36442. * Defines if the last and first points of each path in your pathArray must be joined
  36443. */
  36444. closeArray,
  36445. /**
  36446. * Defines if the last and first points of each path in your pathArray must be joined
  36447. */
  36448. closePath,
  36449. /**
  36450. * Defines the offset between points
  36451. */
  36452. offset, canBeRegenerated, mesh,
  36453. /**
  36454. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36455. */
  36456. side) {
  36457. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36458. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36459. _this.pathArray = pathArray;
  36460. _this.closeArray = closeArray;
  36461. _this.closePath = closePath;
  36462. _this.offset = offset;
  36463. _this.side = side;
  36464. return _this;
  36465. }
  36466. /** @ignore */
  36467. RibbonGeometry.prototype._regenerateVertexData = function () {
  36468. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36469. };
  36470. RibbonGeometry.prototype.copy = function (id) {
  36471. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36472. };
  36473. return RibbonGeometry;
  36474. }(_PrimitiveGeometry));
  36475. BABYLON.RibbonGeometry = RibbonGeometry;
  36476. /**
  36477. * Creates a box geometry
  36478. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36479. */
  36480. var BoxGeometry = /** @class */ (function (_super) {
  36481. __extends(BoxGeometry, _super);
  36482. /**
  36483. * Creates a box geometry
  36484. * @param id defines the unique ID of the geometry
  36485. * @param scene defines the hosting scene
  36486. * @param size defines the zise of the box (width, height and depth are the same)
  36487. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36488. * @param mesh defines the hosting mesh (can be null)
  36489. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36490. */
  36491. function BoxGeometry(id, scene,
  36492. /**
  36493. * Defines the zise of the box (width, height and depth are the same)
  36494. */
  36495. size, canBeRegenerated, mesh,
  36496. /**
  36497. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36498. */
  36499. side) {
  36500. if (mesh === void 0) { mesh = null; }
  36501. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36502. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36503. _this.size = size;
  36504. _this.side = side;
  36505. return _this;
  36506. }
  36507. BoxGeometry.prototype._regenerateVertexData = function () {
  36508. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36509. };
  36510. BoxGeometry.prototype.copy = function (id) {
  36511. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36512. };
  36513. BoxGeometry.prototype.serialize = function () {
  36514. var serializationObject = _super.prototype.serialize.call(this);
  36515. serializationObject.size = this.size;
  36516. return serializationObject;
  36517. };
  36518. BoxGeometry.Parse = function (parsedBox, scene) {
  36519. if (scene.getGeometryByID(parsedBox.id)) {
  36520. return null; // null since geometry could be something else than a box...
  36521. }
  36522. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36523. if (BABYLON.Tags) {
  36524. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36525. }
  36526. scene.pushGeometry(box, true);
  36527. return box;
  36528. };
  36529. return BoxGeometry;
  36530. }(_PrimitiveGeometry));
  36531. BABYLON.BoxGeometry = BoxGeometry;
  36532. /**
  36533. * Creates a sphere geometry
  36534. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36535. */
  36536. var SphereGeometry = /** @class */ (function (_super) {
  36537. __extends(SphereGeometry, _super);
  36538. /**
  36539. * Create a new sphere geometry
  36540. * @param id defines the unique ID of the geometry
  36541. * @param scene defines the hosting scene
  36542. * @param segments defines the number of segments to use to create the sphere
  36543. * @param diameter defines the diameter of the sphere
  36544. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36545. * @param mesh defines the hosting mesh (can be null)
  36546. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36547. */
  36548. function SphereGeometry(id, scene,
  36549. /**
  36550. * Defines the number of segments to use to create the sphere
  36551. */
  36552. segments,
  36553. /**
  36554. * Defines the diameter of the sphere
  36555. */
  36556. diameter, canBeRegenerated, mesh,
  36557. /**
  36558. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36559. */
  36560. side) {
  36561. if (mesh === void 0) { mesh = null; }
  36562. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36563. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36564. _this.segments = segments;
  36565. _this.diameter = diameter;
  36566. _this.side = side;
  36567. return _this;
  36568. }
  36569. SphereGeometry.prototype._regenerateVertexData = function () {
  36570. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36571. };
  36572. SphereGeometry.prototype.copy = function (id) {
  36573. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36574. };
  36575. SphereGeometry.prototype.serialize = function () {
  36576. var serializationObject = _super.prototype.serialize.call(this);
  36577. serializationObject.segments = this.segments;
  36578. serializationObject.diameter = this.diameter;
  36579. return serializationObject;
  36580. };
  36581. SphereGeometry.Parse = function (parsedSphere, scene) {
  36582. if (scene.getGeometryByID(parsedSphere.id)) {
  36583. return null; // null since geometry could be something else than a sphere...
  36584. }
  36585. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36586. if (BABYLON.Tags) {
  36587. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36588. }
  36589. scene.pushGeometry(sphere, true);
  36590. return sphere;
  36591. };
  36592. return SphereGeometry;
  36593. }(_PrimitiveGeometry));
  36594. BABYLON.SphereGeometry = SphereGeometry;
  36595. /**
  36596. * Creates a disc geometry
  36597. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36598. */
  36599. var DiscGeometry = /** @class */ (function (_super) {
  36600. __extends(DiscGeometry, _super);
  36601. /**
  36602. * Creates a new disc geometry
  36603. * @param id defines the unique ID of the geometry
  36604. * @param scene defines the hosting scene
  36605. * @param radius defines the radius of the disc
  36606. * @param tessellation defines the tesselation factor to apply to the disc
  36607. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36608. * @param mesh defines the hosting mesh (can be null)
  36609. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36610. */
  36611. function DiscGeometry(id, scene,
  36612. /**
  36613. * Defines the radius of the disc
  36614. */
  36615. radius,
  36616. /**
  36617. * Defines the tesselation factor to apply to the disc
  36618. */
  36619. tessellation, canBeRegenerated, mesh,
  36620. /**
  36621. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36622. */
  36623. side) {
  36624. if (mesh === void 0) { mesh = null; }
  36625. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36626. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36627. _this.radius = radius;
  36628. _this.tessellation = tessellation;
  36629. _this.side = side;
  36630. return _this;
  36631. }
  36632. DiscGeometry.prototype._regenerateVertexData = function () {
  36633. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36634. };
  36635. DiscGeometry.prototype.copy = function (id) {
  36636. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36637. };
  36638. return DiscGeometry;
  36639. }(_PrimitiveGeometry));
  36640. BABYLON.DiscGeometry = DiscGeometry;
  36641. /**
  36642. * Creates a new cylinder geometry
  36643. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36644. */
  36645. var CylinderGeometry = /** @class */ (function (_super) {
  36646. __extends(CylinderGeometry, _super);
  36647. /**
  36648. * Creates a new cylinder geometry
  36649. * @param id defines the unique ID of the geometry
  36650. * @param scene defines the hosting scene
  36651. * @param height defines the height of the cylinder
  36652. * @param diameterTop defines the diameter of the cylinder's top cap
  36653. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36654. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36655. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36656. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36657. * @param mesh defines the hosting mesh (can be null)
  36658. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36659. */
  36660. function CylinderGeometry(id, scene,
  36661. /**
  36662. * Defines the height of the cylinder
  36663. */
  36664. height,
  36665. /**
  36666. * Defines the diameter of the cylinder's top cap
  36667. */
  36668. diameterTop,
  36669. /**
  36670. * Defines the diameter of the cylinder's bottom cap
  36671. */
  36672. diameterBottom,
  36673. /**
  36674. * Defines the tessellation factor to apply to the cylinder
  36675. */
  36676. tessellation,
  36677. /**
  36678. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36679. */
  36680. subdivisions, canBeRegenerated, mesh,
  36681. /**
  36682. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36683. */
  36684. side) {
  36685. if (subdivisions === void 0) { subdivisions = 1; }
  36686. if (mesh === void 0) { mesh = null; }
  36687. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36688. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36689. _this.height = height;
  36690. _this.diameterTop = diameterTop;
  36691. _this.diameterBottom = diameterBottom;
  36692. _this.tessellation = tessellation;
  36693. _this.subdivisions = subdivisions;
  36694. _this.side = side;
  36695. return _this;
  36696. }
  36697. CylinderGeometry.prototype._regenerateVertexData = function () {
  36698. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36699. };
  36700. CylinderGeometry.prototype.copy = function (id) {
  36701. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36702. };
  36703. CylinderGeometry.prototype.serialize = function () {
  36704. var serializationObject = _super.prototype.serialize.call(this);
  36705. serializationObject.height = this.height;
  36706. serializationObject.diameterTop = this.diameterTop;
  36707. serializationObject.diameterBottom = this.diameterBottom;
  36708. serializationObject.tessellation = this.tessellation;
  36709. return serializationObject;
  36710. };
  36711. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36712. if (scene.getGeometryByID(parsedCylinder.id)) {
  36713. return null; // null since geometry could be something else than a cylinder...
  36714. }
  36715. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36716. if (BABYLON.Tags) {
  36717. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36718. }
  36719. scene.pushGeometry(cylinder, true);
  36720. return cylinder;
  36721. };
  36722. return CylinderGeometry;
  36723. }(_PrimitiveGeometry));
  36724. BABYLON.CylinderGeometry = CylinderGeometry;
  36725. /**
  36726. * Creates a new torus geometry
  36727. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36728. */
  36729. var TorusGeometry = /** @class */ (function (_super) {
  36730. __extends(TorusGeometry, _super);
  36731. /**
  36732. * Creates a new torus geometry
  36733. * @param id defines the unique ID of the geometry
  36734. * @param scene defines the hosting scene
  36735. * @param diameter defines the diameter of the torus
  36736. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36737. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36738. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36739. * @param mesh defines the hosting mesh (can be null)
  36740. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36741. */
  36742. function TorusGeometry(id, scene,
  36743. /**
  36744. * Defines the diameter of the torus
  36745. */
  36746. diameter,
  36747. /**
  36748. * Defines the thickness of the torus (ie. internal diameter)
  36749. */
  36750. thickness,
  36751. /**
  36752. * Defines the tesselation factor to apply to the torus
  36753. */
  36754. tessellation, canBeRegenerated, mesh,
  36755. /**
  36756. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36757. */
  36758. side) {
  36759. if (mesh === void 0) { mesh = null; }
  36760. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36761. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36762. _this.diameter = diameter;
  36763. _this.thickness = thickness;
  36764. _this.tessellation = tessellation;
  36765. _this.side = side;
  36766. return _this;
  36767. }
  36768. TorusGeometry.prototype._regenerateVertexData = function () {
  36769. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36770. };
  36771. TorusGeometry.prototype.copy = function (id) {
  36772. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36773. };
  36774. TorusGeometry.prototype.serialize = function () {
  36775. var serializationObject = _super.prototype.serialize.call(this);
  36776. serializationObject.diameter = this.diameter;
  36777. serializationObject.thickness = this.thickness;
  36778. serializationObject.tessellation = this.tessellation;
  36779. return serializationObject;
  36780. };
  36781. TorusGeometry.Parse = function (parsedTorus, scene) {
  36782. if (scene.getGeometryByID(parsedTorus.id)) {
  36783. return null; // null since geometry could be something else than a torus...
  36784. }
  36785. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36786. if (BABYLON.Tags) {
  36787. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36788. }
  36789. scene.pushGeometry(torus, true);
  36790. return torus;
  36791. };
  36792. return TorusGeometry;
  36793. }(_PrimitiveGeometry));
  36794. BABYLON.TorusGeometry = TorusGeometry;
  36795. /**
  36796. * Creates a new ground geometry
  36797. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36798. */
  36799. var GroundGeometry = /** @class */ (function (_super) {
  36800. __extends(GroundGeometry, _super);
  36801. /**
  36802. * Creates a new ground geometry
  36803. * @param id defines the unique ID of the geometry
  36804. * @param scene defines the hosting scene
  36805. * @param width defines the width of the ground
  36806. * @param height defines the height of the ground
  36807. * @param subdivisions defines the subdivisions to apply to the ground
  36808. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36809. * @param mesh defines the hosting mesh (can be null)
  36810. */
  36811. function GroundGeometry(id, scene,
  36812. /**
  36813. * Defines the width of the ground
  36814. */
  36815. width,
  36816. /**
  36817. * Defines the height of the ground
  36818. */
  36819. height,
  36820. /**
  36821. * Defines the subdivisions to apply to the ground
  36822. */
  36823. subdivisions, canBeRegenerated, mesh) {
  36824. if (mesh === void 0) { mesh = null; }
  36825. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36826. _this.width = width;
  36827. _this.height = height;
  36828. _this.subdivisions = subdivisions;
  36829. return _this;
  36830. }
  36831. GroundGeometry.prototype._regenerateVertexData = function () {
  36832. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36833. };
  36834. GroundGeometry.prototype.copy = function (id) {
  36835. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36836. };
  36837. GroundGeometry.prototype.serialize = function () {
  36838. var serializationObject = _super.prototype.serialize.call(this);
  36839. serializationObject.width = this.width;
  36840. serializationObject.height = this.height;
  36841. serializationObject.subdivisions = this.subdivisions;
  36842. return serializationObject;
  36843. };
  36844. GroundGeometry.Parse = function (parsedGround, scene) {
  36845. if (scene.getGeometryByID(parsedGround.id)) {
  36846. return null; // null since geometry could be something else than a ground...
  36847. }
  36848. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36849. if (BABYLON.Tags) {
  36850. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36851. }
  36852. scene.pushGeometry(ground, true);
  36853. return ground;
  36854. };
  36855. return GroundGeometry;
  36856. }(_PrimitiveGeometry));
  36857. BABYLON.GroundGeometry = GroundGeometry;
  36858. /**
  36859. * Creates a tiled ground geometry
  36860. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36861. */
  36862. var TiledGroundGeometry = /** @class */ (function (_super) {
  36863. __extends(TiledGroundGeometry, _super);
  36864. /**
  36865. * Creates a tiled ground geometry
  36866. * @param id defines the unique ID of the geometry
  36867. * @param scene defines the hosting scene
  36868. * @param xmin defines the minimum value on X axis
  36869. * @param zmin defines the minimum value on Z axis
  36870. * @param xmax defines the maximum value on X axis
  36871. * @param zmax defines the maximum value on Z axis
  36872. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36873. * @param precision defines the precision to use when computing the tiles
  36874. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36875. * @param mesh defines the hosting mesh (can be null)
  36876. */
  36877. function TiledGroundGeometry(id, scene,
  36878. /**
  36879. * Defines the minimum value on X axis
  36880. */
  36881. xmin,
  36882. /**
  36883. * Defines the minimum value on Z axis
  36884. */
  36885. zmin,
  36886. /**
  36887. * Defines the maximum value on X axis
  36888. */
  36889. xmax,
  36890. /**
  36891. * Defines the maximum value on Z axis
  36892. */
  36893. zmax,
  36894. /**
  36895. * Defines the subdivisions to apply to the ground
  36896. */
  36897. subdivisions,
  36898. /**
  36899. * Defines the precision to use when computing the tiles
  36900. */
  36901. precision, canBeRegenerated, mesh) {
  36902. if (mesh === void 0) { mesh = null; }
  36903. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36904. _this.xmin = xmin;
  36905. _this.zmin = zmin;
  36906. _this.xmax = xmax;
  36907. _this.zmax = zmax;
  36908. _this.subdivisions = subdivisions;
  36909. _this.precision = precision;
  36910. return _this;
  36911. }
  36912. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36913. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36914. };
  36915. TiledGroundGeometry.prototype.copy = function (id) {
  36916. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36917. };
  36918. return TiledGroundGeometry;
  36919. }(_PrimitiveGeometry));
  36920. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36921. /**
  36922. * Creates a plane geometry
  36923. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36924. */
  36925. var PlaneGeometry = /** @class */ (function (_super) {
  36926. __extends(PlaneGeometry, _super);
  36927. /**
  36928. * Creates a plane geometry
  36929. * @param id defines the unique ID of the geometry
  36930. * @param scene defines the hosting scene
  36931. * @param size defines the size of the plane (width === height)
  36932. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36933. * @param mesh defines the hosting mesh (can be null)
  36934. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36935. */
  36936. function PlaneGeometry(id, scene,
  36937. /**
  36938. * Defines the size of the plane (width === height)
  36939. */
  36940. size, canBeRegenerated, mesh,
  36941. /**
  36942. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36943. */
  36944. side) {
  36945. if (mesh === void 0) { mesh = null; }
  36946. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36947. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36948. _this.size = size;
  36949. _this.side = side;
  36950. return _this;
  36951. }
  36952. PlaneGeometry.prototype._regenerateVertexData = function () {
  36953. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36954. };
  36955. PlaneGeometry.prototype.copy = function (id) {
  36956. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36957. };
  36958. PlaneGeometry.prototype.serialize = function () {
  36959. var serializationObject = _super.prototype.serialize.call(this);
  36960. serializationObject.size = this.size;
  36961. return serializationObject;
  36962. };
  36963. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36964. if (scene.getGeometryByID(parsedPlane.id)) {
  36965. return null; // null since geometry could be something else than a ground...
  36966. }
  36967. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36968. if (BABYLON.Tags) {
  36969. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36970. }
  36971. scene.pushGeometry(plane, true);
  36972. return plane;
  36973. };
  36974. return PlaneGeometry;
  36975. }(_PrimitiveGeometry));
  36976. BABYLON.PlaneGeometry = PlaneGeometry;
  36977. /**
  36978. * Creates a torus knot geometry
  36979. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36980. */
  36981. var TorusKnotGeometry = /** @class */ (function (_super) {
  36982. __extends(TorusKnotGeometry, _super);
  36983. /**
  36984. * Creates a torus knot geometry
  36985. * @param id defines the unique ID of the geometry
  36986. * @param scene defines the hosting scene
  36987. * @param radius defines the radius of the torus knot
  36988. * @param tube defines the thickness of the torus knot tube
  36989. * @param radialSegments defines the number of radial segments
  36990. * @param tubularSegments defines the number of tubular segments
  36991. * @param p defines the first number of windings
  36992. * @param q defines the second number of windings
  36993. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36994. * @param mesh defines the hosting mesh (can be null)
  36995. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36996. */
  36997. function TorusKnotGeometry(id, scene,
  36998. /**
  36999. * Defines the radius of the torus knot
  37000. */
  37001. radius,
  37002. /**
  37003. * Defines the thickness of the torus knot tube
  37004. */
  37005. tube,
  37006. /**
  37007. * Defines the number of radial segments
  37008. */
  37009. radialSegments,
  37010. /**
  37011. * Defines the number of tubular segments
  37012. */
  37013. tubularSegments,
  37014. /**
  37015. * Defines the first number of windings
  37016. */
  37017. p,
  37018. /**
  37019. * Defines the second number of windings
  37020. */
  37021. q, canBeRegenerated, mesh,
  37022. /**
  37023. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37024. */
  37025. side) {
  37026. if (mesh === void 0) { mesh = null; }
  37027. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37028. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37029. _this.radius = radius;
  37030. _this.tube = tube;
  37031. _this.radialSegments = radialSegments;
  37032. _this.tubularSegments = tubularSegments;
  37033. _this.p = p;
  37034. _this.q = q;
  37035. _this.side = side;
  37036. return _this;
  37037. }
  37038. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  37039. 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 });
  37040. };
  37041. TorusKnotGeometry.prototype.copy = function (id) {
  37042. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37043. };
  37044. TorusKnotGeometry.prototype.serialize = function () {
  37045. var serializationObject = _super.prototype.serialize.call(this);
  37046. serializationObject.radius = this.radius;
  37047. serializationObject.tube = this.tube;
  37048. serializationObject.radialSegments = this.radialSegments;
  37049. serializationObject.tubularSegments = this.tubularSegments;
  37050. serializationObject.p = this.p;
  37051. serializationObject.q = this.q;
  37052. return serializationObject;
  37053. };
  37054. ;
  37055. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  37056. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37057. return null; // null since geometry could be something else than a ground...
  37058. }
  37059. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37060. if (BABYLON.Tags) {
  37061. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37062. }
  37063. scene.pushGeometry(torusKnot, true);
  37064. return torusKnot;
  37065. };
  37066. return TorusKnotGeometry;
  37067. }(_PrimitiveGeometry));
  37068. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  37069. //}
  37070. })(BABYLON || (BABYLON = {}));
  37071. //# sourceMappingURL=babylon.geometry.js.map
  37072. "use strict";
  37073. var BABYLON;
  37074. (function (BABYLON) {
  37075. /**
  37076. * PostProcessManager is used to manage one or more post processes or post process pipelines
  37077. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  37078. */
  37079. var PostProcessManager = /** @class */ (function () {
  37080. /**
  37081. * Creates a new instance of @see PostProcess
  37082. * @param scene The scene that the post process is associated with.
  37083. */
  37084. function PostProcessManager(scene) {
  37085. this._vertexBuffers = {};
  37086. this._scene = scene;
  37087. }
  37088. PostProcessManager.prototype._prepareBuffers = function () {
  37089. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  37090. return;
  37091. }
  37092. // VBO
  37093. var vertices = [];
  37094. vertices.push(1, 1);
  37095. vertices.push(-1, 1);
  37096. vertices.push(-1, -1);
  37097. vertices.push(1, -1);
  37098. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37099. this._buildIndexBuffer();
  37100. };
  37101. PostProcessManager.prototype._buildIndexBuffer = function () {
  37102. // Indices
  37103. var indices = [];
  37104. indices.push(0);
  37105. indices.push(1);
  37106. indices.push(2);
  37107. indices.push(0);
  37108. indices.push(2);
  37109. indices.push(3);
  37110. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37111. };
  37112. /**
  37113. * Rebuilds the vertex buffers of the manager.
  37114. */
  37115. PostProcessManager.prototype._rebuild = function () {
  37116. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37117. if (!vb) {
  37118. return;
  37119. }
  37120. vb._rebuild();
  37121. this._buildIndexBuffer();
  37122. };
  37123. // Methods
  37124. /**
  37125. * Prepares a frame to be run through a post process.
  37126. * @param sourceTexture The input texture to the post procesess. (default: null)
  37127. * @param postProcesses An array of post processes to be run. (default: null)
  37128. * @returns True if the post processes were able to be run.
  37129. */
  37130. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  37131. if (sourceTexture === void 0) { sourceTexture = null; }
  37132. if (postProcesses === void 0) { postProcesses = null; }
  37133. var camera = this._scene.activeCamera;
  37134. if (!camera) {
  37135. return false;
  37136. }
  37137. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37138. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37139. return false;
  37140. }
  37141. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  37142. return true;
  37143. };
  37144. /**
  37145. * Manually render a set of post processes to a texture.
  37146. * @param postProcesses An array of post processes to be run.
  37147. * @param targetTexture The target texture to render to.
  37148. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  37149. */
  37150. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  37151. if (targetTexture === void 0) { targetTexture = null; }
  37152. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37153. var engine = this._scene.getEngine();
  37154. for (var index = 0; index < postProcesses.length; index++) {
  37155. if (index < postProcesses.length - 1) {
  37156. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37157. }
  37158. else {
  37159. if (targetTexture) {
  37160. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  37161. }
  37162. else {
  37163. engine.restoreDefaultFramebuffer();
  37164. }
  37165. }
  37166. var pp = postProcesses[index];
  37167. var effect = pp.apply();
  37168. if (effect) {
  37169. pp.onBeforeRenderObservable.notifyObservers(effect);
  37170. // VBOs
  37171. this._prepareBuffers();
  37172. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37173. // Draw order
  37174. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37175. pp.onAfterRenderObservable.notifyObservers(effect);
  37176. }
  37177. }
  37178. // Restore depth buffer
  37179. engine.setDepthBuffer(true);
  37180. engine.setDepthWrite(true);
  37181. };
  37182. /**
  37183. * Finalize the result of the output of the postprocesses.
  37184. * @param doNotPresent If true the result will not be displayed to the screen.
  37185. * @param targetTexture The target texture to render to.
  37186. * @param faceIndex The index of the face to bind the target texture to.
  37187. * @param postProcesses The array of post processes to render.
  37188. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  37189. */
  37190. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  37191. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37192. var camera = this._scene.activeCamera;
  37193. if (!camera) {
  37194. return;
  37195. }
  37196. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37197. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37198. return;
  37199. }
  37200. var engine = this._scene.getEngine();
  37201. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37202. var pp = postProcesses[index];
  37203. if (index < len - 1) {
  37204. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  37205. }
  37206. else {
  37207. if (targetTexture) {
  37208. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  37209. }
  37210. else {
  37211. engine.restoreDefaultFramebuffer();
  37212. }
  37213. }
  37214. if (doNotPresent) {
  37215. break;
  37216. }
  37217. var effect = pp.apply();
  37218. if (effect) {
  37219. pp.onBeforeRenderObservable.notifyObservers(effect);
  37220. // VBOs
  37221. this._prepareBuffers();
  37222. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37223. // Draw order
  37224. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37225. pp.onAfterRenderObservable.notifyObservers(effect);
  37226. }
  37227. }
  37228. // Restore states
  37229. engine.setDepthBuffer(true);
  37230. engine.setDepthWrite(true);
  37231. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37232. };
  37233. /**
  37234. * Disposes of the post process manager.
  37235. */
  37236. PostProcessManager.prototype.dispose = function () {
  37237. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37238. if (buffer) {
  37239. buffer.dispose();
  37240. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37241. }
  37242. if (this._indexBuffer) {
  37243. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37244. this._indexBuffer = null;
  37245. }
  37246. };
  37247. return PostProcessManager;
  37248. }());
  37249. BABYLON.PostProcessManager = PostProcessManager;
  37250. })(BABYLON || (BABYLON = {}));
  37251. //# sourceMappingURL=babylon.postProcessManager.js.map
  37252. "use strict";
  37253. var BABYLON;
  37254. (function (BABYLON) {
  37255. /**
  37256. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  37257. */
  37258. var PerformanceMonitor = /** @class */ (function () {
  37259. /**
  37260. * constructor
  37261. * @param frameSampleSize The number of samples required to saturate the sliding window
  37262. */
  37263. function PerformanceMonitor(frameSampleSize) {
  37264. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  37265. this._enabled = true;
  37266. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  37267. }
  37268. /**
  37269. * Samples current frame
  37270. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  37271. */
  37272. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  37273. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  37274. if (!this._enabled)
  37275. return;
  37276. if (this._lastFrameTimeMs != null) {
  37277. var dt = timeMs - this._lastFrameTimeMs;
  37278. this._rollingFrameTime.add(dt);
  37279. }
  37280. this._lastFrameTimeMs = timeMs;
  37281. };
  37282. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  37283. /**
  37284. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37285. * @return Average frame time in milliseconds
  37286. */
  37287. get: function () {
  37288. return this._rollingFrameTime.average;
  37289. },
  37290. enumerable: true,
  37291. configurable: true
  37292. });
  37293. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  37294. /**
  37295. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37296. * @return Frame time variance in milliseconds squared
  37297. */
  37298. get: function () {
  37299. return this._rollingFrameTime.variance;
  37300. },
  37301. enumerable: true,
  37302. configurable: true
  37303. });
  37304. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  37305. /**
  37306. * Returns the frame time of the most recent frame
  37307. * @return Frame time in milliseconds
  37308. */
  37309. get: function () {
  37310. return this._rollingFrameTime.history(0);
  37311. },
  37312. enumerable: true,
  37313. configurable: true
  37314. });
  37315. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  37316. /**
  37317. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  37318. * @return Framerate in frames per second
  37319. */
  37320. get: function () {
  37321. return 1000.0 / this._rollingFrameTime.average;
  37322. },
  37323. enumerable: true,
  37324. configurable: true
  37325. });
  37326. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  37327. /**
  37328. * Returns the average framerate in frames per second using the most recent frame time
  37329. * @return Framerate in frames per second
  37330. */
  37331. get: function () {
  37332. var history = this._rollingFrameTime.history(0);
  37333. if (history === 0) {
  37334. return 0;
  37335. }
  37336. return 1000.0 / history;
  37337. },
  37338. enumerable: true,
  37339. configurable: true
  37340. });
  37341. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  37342. /**
  37343. * Returns true if enough samples have been taken to completely fill the sliding window
  37344. * @return true if saturated
  37345. */
  37346. get: function () {
  37347. return this._rollingFrameTime.isSaturated();
  37348. },
  37349. enumerable: true,
  37350. configurable: true
  37351. });
  37352. /**
  37353. * Enables contributions to the sliding window sample set
  37354. */
  37355. PerformanceMonitor.prototype.enable = function () {
  37356. this._enabled = true;
  37357. };
  37358. /**
  37359. * Disables contributions to the sliding window sample set
  37360. * Samples will not be interpolated over the disabled period
  37361. */
  37362. PerformanceMonitor.prototype.disable = function () {
  37363. this._enabled = false;
  37364. //clear last sample to avoid interpolating over the disabled period when next enabled
  37365. this._lastFrameTimeMs = null;
  37366. };
  37367. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37368. /**
  37369. * Returns true if sampling is enabled
  37370. * @return true if enabled
  37371. */
  37372. get: function () {
  37373. return this._enabled;
  37374. },
  37375. enumerable: true,
  37376. configurable: true
  37377. });
  37378. /**
  37379. * Resets performance monitor
  37380. */
  37381. PerformanceMonitor.prototype.reset = function () {
  37382. //clear last sample to avoid interpolating over the disabled period when next enabled
  37383. this._lastFrameTimeMs = null;
  37384. //wipe record
  37385. this._rollingFrameTime.reset();
  37386. };
  37387. return PerformanceMonitor;
  37388. }());
  37389. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37390. /**
  37391. * RollingAverage
  37392. *
  37393. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37394. */
  37395. var RollingAverage = /** @class */ (function () {
  37396. /**
  37397. * constructor
  37398. * @param length The number of samples required to saturate the sliding window
  37399. */
  37400. function RollingAverage(length) {
  37401. this._samples = new Array(length);
  37402. this.reset();
  37403. }
  37404. /**
  37405. * Adds a sample to the sample set
  37406. * @param v The sample value
  37407. */
  37408. RollingAverage.prototype.add = function (v) {
  37409. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37410. var delta;
  37411. //we need to check if we've already wrapped round
  37412. if (this.isSaturated()) {
  37413. //remove bottom of stack from mean
  37414. var bottomValue = this._samples[this._pos];
  37415. delta = bottomValue - this.average;
  37416. this.average -= delta / (this._sampleCount - 1);
  37417. this._m2 -= delta * (bottomValue - this.average);
  37418. }
  37419. else {
  37420. this._sampleCount++;
  37421. }
  37422. //add new value to mean
  37423. delta = v - this.average;
  37424. this.average += delta / (this._sampleCount);
  37425. this._m2 += delta * (v - this.average);
  37426. //set the new variance
  37427. this.variance = this._m2 / (this._sampleCount - 1);
  37428. this._samples[this._pos] = v;
  37429. this._pos++;
  37430. this._pos %= this._samples.length; //positive wrap around
  37431. };
  37432. /**
  37433. * Returns previously added values or null if outside of history or outside the sliding window domain
  37434. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37435. * @return Value previously recorded with add() or null if outside of range
  37436. */
  37437. RollingAverage.prototype.history = function (i) {
  37438. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37439. return 0;
  37440. }
  37441. var i0 = this._wrapPosition(this._pos - 1.0);
  37442. return this._samples[this._wrapPosition(i0 - i)];
  37443. };
  37444. /**
  37445. * Returns true if enough samples have been taken to completely fill the sliding window
  37446. * @return true if sample-set saturated
  37447. */
  37448. RollingAverage.prototype.isSaturated = function () {
  37449. return this._sampleCount >= this._samples.length;
  37450. };
  37451. /**
  37452. * Resets the rolling average (equivalent to 0 samples taken so far)
  37453. */
  37454. RollingAverage.prototype.reset = function () {
  37455. this.average = 0;
  37456. this.variance = 0;
  37457. this._sampleCount = 0;
  37458. this._pos = 0;
  37459. this._m2 = 0;
  37460. };
  37461. /**
  37462. * Wraps a value around the sample range boundaries
  37463. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37464. * @return Wrapped position in sample range
  37465. */
  37466. RollingAverage.prototype._wrapPosition = function (i) {
  37467. var max = this._samples.length;
  37468. return ((i % max) + max) % max;
  37469. };
  37470. return RollingAverage;
  37471. }());
  37472. BABYLON.RollingAverage = RollingAverage;
  37473. })(BABYLON || (BABYLON = {}));
  37474. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37475. "use strict";
  37476. var BABYLON;
  37477. (function (BABYLON) {
  37478. /**
  37479. * This groups together the common properties used for image processing either in direct forward pass
  37480. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37481. * or not.
  37482. */
  37483. var ImageProcessingConfiguration = /** @class */ (function () {
  37484. function ImageProcessingConfiguration() {
  37485. /**
  37486. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37487. */
  37488. this.colorCurves = new BABYLON.ColorCurves();
  37489. this._colorCurvesEnabled = false;
  37490. this._colorGradingEnabled = false;
  37491. this._colorGradingWithGreenDepth = true;
  37492. this._colorGradingBGR = true;
  37493. this._exposure = 1.0;
  37494. this._toneMappingEnabled = false;
  37495. this._contrast = 1.0;
  37496. /**
  37497. * Vignette stretch size.
  37498. */
  37499. this.vignetteStretch = 0;
  37500. /**
  37501. * Vignette centre X Offset.
  37502. */
  37503. this.vignetteCentreX = 0;
  37504. /**
  37505. * Vignette centre Y Offset.
  37506. */
  37507. this.vignetteCentreY = 0;
  37508. /**
  37509. * Vignette weight or intensity of the vignette effect.
  37510. */
  37511. this.vignetteWeight = 1.5;
  37512. /**
  37513. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37514. * if vignetteEnabled is set to true.
  37515. */
  37516. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37517. /**
  37518. * Camera field of view used by the Vignette effect.
  37519. */
  37520. this.vignetteCameraFov = 0.5;
  37521. this._grainEnabled = false;
  37522. this._grainIntensity = 30;
  37523. this._grainAnimated = false;
  37524. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37525. this._vignetteEnabled = false;
  37526. this._applyByPostProcess = false;
  37527. this._isEnabled = true;
  37528. /**
  37529. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37530. * @type {BABYLON.Observable}
  37531. */
  37532. this.onUpdateParameters = new BABYLON.Observable();
  37533. }
  37534. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37535. /**
  37536. * Gets wether the color curves effect is enabled.
  37537. */
  37538. get: function () {
  37539. return this._colorCurvesEnabled;
  37540. },
  37541. /**
  37542. * Sets wether the color curves effect is enabled.
  37543. */
  37544. set: function (value) {
  37545. if (this._colorCurvesEnabled === value) {
  37546. return;
  37547. }
  37548. this._colorCurvesEnabled = value;
  37549. this._updateParameters();
  37550. },
  37551. enumerable: true,
  37552. configurable: true
  37553. });
  37554. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37555. /**
  37556. * Gets wether the color grading effect is enabled.
  37557. */
  37558. get: function () {
  37559. return this._colorGradingEnabled;
  37560. },
  37561. /**
  37562. * Sets wether the color grading effect is enabled.
  37563. */
  37564. set: function (value) {
  37565. if (this._colorGradingEnabled === value) {
  37566. return;
  37567. }
  37568. this._colorGradingEnabled = value;
  37569. this._updateParameters();
  37570. },
  37571. enumerable: true,
  37572. configurable: true
  37573. });
  37574. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37575. /**
  37576. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37577. */
  37578. get: function () {
  37579. return this._colorGradingWithGreenDepth;
  37580. },
  37581. /**
  37582. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37583. */
  37584. set: function (value) {
  37585. if (this._colorGradingWithGreenDepth === value) {
  37586. return;
  37587. }
  37588. this._colorGradingWithGreenDepth = value;
  37589. this._updateParameters();
  37590. },
  37591. enumerable: true,
  37592. configurable: true
  37593. });
  37594. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37595. /**
  37596. * Gets wether the color grading texture contains BGR values.
  37597. */
  37598. get: function () {
  37599. return this._colorGradingBGR;
  37600. },
  37601. /**
  37602. * Sets wether the color grading texture contains BGR values.
  37603. */
  37604. set: function (value) {
  37605. if (this._colorGradingBGR === value) {
  37606. return;
  37607. }
  37608. this._colorGradingBGR = value;
  37609. this._updateParameters();
  37610. },
  37611. enumerable: true,
  37612. configurable: true
  37613. });
  37614. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37615. /**
  37616. * Gets the Exposure used in the effect.
  37617. */
  37618. get: function () {
  37619. return this._exposure;
  37620. },
  37621. /**
  37622. * Sets the Exposure used in the effect.
  37623. */
  37624. set: function (value) {
  37625. if (this._exposure === value) {
  37626. return;
  37627. }
  37628. this._exposure = value;
  37629. this._updateParameters();
  37630. },
  37631. enumerable: true,
  37632. configurable: true
  37633. });
  37634. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37635. /**
  37636. * Gets wether the tone mapping effect is enabled.
  37637. */
  37638. get: function () {
  37639. return this._toneMappingEnabled;
  37640. },
  37641. /**
  37642. * Sets wether the tone mapping effect is enabled.
  37643. */
  37644. set: function (value) {
  37645. if (this._toneMappingEnabled === value) {
  37646. return;
  37647. }
  37648. this._toneMappingEnabled = value;
  37649. this._updateParameters();
  37650. },
  37651. enumerable: true,
  37652. configurable: true
  37653. });
  37654. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37655. /**
  37656. * Gets the contrast used in the effect.
  37657. */
  37658. get: function () {
  37659. return this._contrast;
  37660. },
  37661. /**
  37662. * Sets the contrast used in the effect.
  37663. */
  37664. set: function (value) {
  37665. if (this._contrast === value) {
  37666. return;
  37667. }
  37668. this._contrast = value;
  37669. this._updateParameters();
  37670. },
  37671. enumerable: true,
  37672. configurable: true
  37673. });
  37674. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37675. /**
  37676. * If the grain effect should be enabled.
  37677. */
  37678. get: function () {
  37679. return this._grainEnabled;
  37680. },
  37681. set: function (value) {
  37682. if (this._grainEnabled === value) {
  37683. return;
  37684. }
  37685. this._grainEnabled = value;
  37686. this._updateParameters();
  37687. },
  37688. enumerable: true,
  37689. configurable: true
  37690. });
  37691. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37692. /**
  37693. * Amount of grain to be applied by the grain effect.
  37694. */
  37695. get: function () {
  37696. return this._grainIntensity;
  37697. },
  37698. set: function (value) {
  37699. if (this._grainIntensity === value) {
  37700. return;
  37701. }
  37702. this._grainIntensity = value;
  37703. },
  37704. enumerable: true,
  37705. configurable: true
  37706. });
  37707. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37708. /**
  37709. * If the grain effect should be animated.
  37710. */
  37711. get: function () {
  37712. return this._grainAnimated;
  37713. },
  37714. set: function (value) {
  37715. if (this._grainAnimated === value) {
  37716. return;
  37717. }
  37718. this._grainAnimated = value;
  37719. this._updateParameters();
  37720. },
  37721. enumerable: true,
  37722. configurable: true
  37723. });
  37724. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37725. /**
  37726. * Gets the vignette blend mode allowing different kind of effect.
  37727. */
  37728. get: function () {
  37729. return this._vignetteBlendMode;
  37730. },
  37731. /**
  37732. * Sets the vignette blend mode allowing different kind of effect.
  37733. */
  37734. set: function (value) {
  37735. if (this._vignetteBlendMode === value) {
  37736. return;
  37737. }
  37738. this._vignetteBlendMode = value;
  37739. this._updateParameters();
  37740. },
  37741. enumerable: true,
  37742. configurable: true
  37743. });
  37744. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37745. /**
  37746. * Gets wether the vignette effect is enabled.
  37747. */
  37748. get: function () {
  37749. return this._vignetteEnabled;
  37750. },
  37751. /**
  37752. * Sets wether the vignette effect is enabled.
  37753. */
  37754. set: function (value) {
  37755. if (this._vignetteEnabled === value) {
  37756. return;
  37757. }
  37758. this._vignetteEnabled = value;
  37759. this._updateParameters();
  37760. },
  37761. enumerable: true,
  37762. configurable: true
  37763. });
  37764. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37765. /**
  37766. * Gets wether the image processing is applied through a post process or not.
  37767. */
  37768. get: function () {
  37769. return this._applyByPostProcess;
  37770. },
  37771. /**
  37772. * Sets wether the image processing is applied through a post process or not.
  37773. */
  37774. set: function (value) {
  37775. if (this._applyByPostProcess === value) {
  37776. return;
  37777. }
  37778. this._applyByPostProcess = value;
  37779. this._updateParameters();
  37780. },
  37781. enumerable: true,
  37782. configurable: true
  37783. });
  37784. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37785. /**
  37786. * Gets wether the image processing is enabled or not.
  37787. */
  37788. get: function () {
  37789. return this._isEnabled;
  37790. },
  37791. /**
  37792. * Sets wether the image processing is enabled or not.
  37793. */
  37794. set: function (value) {
  37795. if (this._isEnabled === value) {
  37796. return;
  37797. }
  37798. this._isEnabled = value;
  37799. this._updateParameters();
  37800. },
  37801. enumerable: true,
  37802. configurable: true
  37803. });
  37804. /**
  37805. * Method called each time the image processing information changes requires to recompile the effect.
  37806. */
  37807. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37808. this.onUpdateParameters.notifyObservers(this);
  37809. };
  37810. ImageProcessingConfiguration.prototype.getClassName = function () {
  37811. return "ImageProcessingConfiguration";
  37812. };
  37813. /**
  37814. * Prepare the list of uniforms associated with the Image Processing effects.
  37815. * @param uniformsList The list of uniforms used in the effect
  37816. * @param defines the list of defines currently in use
  37817. */
  37818. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37819. if (defines.EXPOSURE) {
  37820. uniforms.push("exposureLinear");
  37821. }
  37822. if (defines.CONTRAST) {
  37823. uniforms.push("contrast");
  37824. }
  37825. if (defines.COLORGRADING) {
  37826. uniforms.push("colorTransformSettings");
  37827. }
  37828. if (defines.VIGNETTE) {
  37829. uniforms.push("vInverseScreenSize");
  37830. uniforms.push("vignetteSettings1");
  37831. uniforms.push("vignetteSettings2");
  37832. }
  37833. if (defines.COLORCURVES) {
  37834. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37835. }
  37836. if (defines.GRAIN) {
  37837. uniforms.push("grainVarianceAmount");
  37838. uniforms.push("grainAnimatedSeed");
  37839. }
  37840. };
  37841. /**
  37842. * Prepare the list of samplers associated with the Image Processing effects.
  37843. * @param uniformsList The list of uniforms used in the effect
  37844. * @param defines the list of defines currently in use
  37845. */
  37846. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37847. if (defines.COLORGRADING) {
  37848. samplersList.push("txColorTransform");
  37849. }
  37850. };
  37851. /**
  37852. * Prepare the list of defines associated to the shader.
  37853. * @param defines the list of defines to complete
  37854. */
  37855. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37856. if (forPostProcess === void 0) { forPostProcess = false; }
  37857. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37858. defines.VIGNETTE = false;
  37859. defines.TONEMAPPING = false;
  37860. defines.CONTRAST = false;
  37861. defines.EXPOSURE = false;
  37862. defines.COLORCURVES = false;
  37863. defines.COLORGRADING = false;
  37864. defines.COLORGRADING3D = false;
  37865. defines.IMAGEPROCESSING = false;
  37866. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37867. return;
  37868. }
  37869. defines.VIGNETTE = this.vignetteEnabled;
  37870. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37871. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37872. defines.TONEMAPPING = this.toneMappingEnabled;
  37873. defines.CONTRAST = (this.contrast !== 1.0);
  37874. defines.EXPOSURE = (this.exposure !== 1.0);
  37875. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37876. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37877. if (defines.COLORGRADING) {
  37878. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37879. }
  37880. else {
  37881. defines.COLORGRADING3D = false;
  37882. }
  37883. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37884. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37885. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37886. defines.GRAIN = this.grainEnabled;
  37887. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37888. };
  37889. /**
  37890. * Returns true if all the image processing information are ready.
  37891. */
  37892. ImageProcessingConfiguration.prototype.isReady = function () {
  37893. // Color Grading texure can not be none blocking.
  37894. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37895. };
  37896. /**
  37897. * Binds the image processing to the shader.
  37898. * @param effect The effect to bind to
  37899. */
  37900. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37901. if (aspectRatio === void 0) { aspectRatio = 1; }
  37902. // Color Curves
  37903. if (this._colorCurvesEnabled && this.colorCurves) {
  37904. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37905. }
  37906. // Vignette
  37907. if (this._vignetteEnabled) {
  37908. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37909. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37910. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37911. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37912. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37913. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37914. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37915. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37916. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37917. var vignettePower = -2.0 * this.vignetteWeight;
  37918. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37919. }
  37920. // Exposure
  37921. effect.setFloat("exposureLinear", this.exposure);
  37922. // Contrast
  37923. effect.setFloat("contrast", this.contrast);
  37924. // Color transform settings
  37925. if (this.colorGradingTexture) {
  37926. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37927. var textureSize = this.colorGradingTexture.getSize().height;
  37928. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37929. 0.5 / textureSize, // textureOffset
  37930. textureSize, // textureSize
  37931. this.colorGradingTexture.level // weight
  37932. );
  37933. }
  37934. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37935. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37936. };
  37937. /**
  37938. * Clones the current image processing instance.
  37939. * @return The cloned image processing
  37940. */
  37941. ImageProcessingConfiguration.prototype.clone = function () {
  37942. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37943. };
  37944. /**
  37945. * Serializes the current image processing instance to a json representation.
  37946. * @return a JSON representation
  37947. */
  37948. ImageProcessingConfiguration.prototype.serialize = function () {
  37949. return BABYLON.SerializationHelper.Serialize(this);
  37950. };
  37951. /**
  37952. * Parses the image processing from a json representation.
  37953. * @param source the JSON source to parse
  37954. * @return The parsed image processing
  37955. */
  37956. ImageProcessingConfiguration.Parse = function (source) {
  37957. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37958. };
  37959. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37960. /**
  37961. * Used to apply the vignette as a mix with the pixel color.
  37962. */
  37963. get: function () {
  37964. return this._VIGNETTEMODE_MULTIPLY;
  37965. },
  37966. enumerable: true,
  37967. configurable: true
  37968. });
  37969. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37970. /**
  37971. * Used to apply the vignette as a replacement of the pixel color.
  37972. */
  37973. get: function () {
  37974. return this._VIGNETTEMODE_OPAQUE;
  37975. },
  37976. enumerable: true,
  37977. configurable: true
  37978. });
  37979. // Static constants associated to the image processing.
  37980. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37981. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37982. __decorate([
  37983. BABYLON.serializeAsColorCurves()
  37984. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37985. __decorate([
  37986. BABYLON.serialize()
  37987. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37988. __decorate([
  37989. BABYLON.serializeAsTexture()
  37990. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37991. __decorate([
  37992. BABYLON.serialize()
  37993. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37994. __decorate([
  37995. BABYLON.serialize()
  37996. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37997. __decorate([
  37998. BABYLON.serialize()
  37999. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  38000. __decorate([
  38001. BABYLON.serialize()
  38002. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  38003. __decorate([
  38004. BABYLON.serialize()
  38005. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  38006. __decorate([
  38007. BABYLON.serialize()
  38008. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  38009. __decorate([
  38010. BABYLON.serialize()
  38011. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  38012. __decorate([
  38013. BABYLON.serialize()
  38014. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  38015. __decorate([
  38016. BABYLON.serialize()
  38017. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  38018. __decorate([
  38019. BABYLON.serialize()
  38020. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  38021. __decorate([
  38022. BABYLON.serializeAsColor4()
  38023. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  38024. __decorate([
  38025. BABYLON.serialize()
  38026. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  38027. __decorate([
  38028. BABYLON.serialize()
  38029. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  38030. __decorate([
  38031. BABYLON.serialize()
  38032. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  38033. __decorate([
  38034. BABYLON.serialize()
  38035. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  38036. __decorate([
  38037. BABYLON.serialize()
  38038. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  38039. __decorate([
  38040. BABYLON.serialize()
  38041. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  38042. __decorate([
  38043. BABYLON.serialize()
  38044. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  38045. __decorate([
  38046. BABYLON.serialize()
  38047. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  38048. return ImageProcessingConfiguration;
  38049. }());
  38050. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  38051. })(BABYLON || (BABYLON = {}));
  38052. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  38053. "use strict";
  38054. var BABYLON;
  38055. (function (BABYLON) {
  38056. /**
  38057. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  38058. * It can help converting any input color in a desired output one. This can then be used to create effects
  38059. * from sepia, black and white to sixties or futuristic rendering...
  38060. *
  38061. * The only supported format is currently 3dl.
  38062. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  38063. */
  38064. var ColorGradingTexture = /** @class */ (function (_super) {
  38065. __extends(ColorGradingTexture, _super);
  38066. /**
  38067. * Instantiates a ColorGradingTexture from the following parameters.
  38068. *
  38069. * @param url The location of the color gradind data (currently only supporting 3dl)
  38070. * @param scene The scene the texture will be used in
  38071. */
  38072. function ColorGradingTexture(url, scene) {
  38073. var _this = _super.call(this, scene) || this;
  38074. if (!url) {
  38075. return _this;
  38076. }
  38077. _this._engine = scene.getEngine();
  38078. _this._textureMatrix = BABYLON.Matrix.Identity();
  38079. _this.name = url;
  38080. _this.url = url;
  38081. _this.hasAlpha = false;
  38082. _this.isCube = false;
  38083. _this.is3D = _this._engine.webGLVersion > 1;
  38084. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38085. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38086. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38087. _this.anisotropicFilteringLevel = 1;
  38088. _this._texture = _this._getFromCache(url, true);
  38089. if (!_this._texture) {
  38090. if (!scene.useDelayedTextureLoading) {
  38091. _this.loadTexture();
  38092. }
  38093. else {
  38094. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38095. }
  38096. }
  38097. return _this;
  38098. }
  38099. /**
  38100. * Returns the texture matrix used in most of the material.
  38101. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38102. */
  38103. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38104. return this._textureMatrix;
  38105. };
  38106. /**
  38107. * Occurs when the file being loaded is a .3dl LUT file.
  38108. */
  38109. ColorGradingTexture.prototype.load3dlTexture = function () {
  38110. var engine = this._engine;
  38111. var texture;
  38112. if (engine.webGLVersion === 1) {
  38113. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38114. }
  38115. else {
  38116. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38117. }
  38118. this._texture = texture;
  38119. var callback = function (text) {
  38120. if (typeof text !== "string") {
  38121. return;
  38122. }
  38123. var data = null;
  38124. var tempData = null;
  38125. var line;
  38126. var lines = text.split('\n');
  38127. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38128. var maxColor = 0;
  38129. for (var i = 0; i < lines.length; i++) {
  38130. line = lines[i];
  38131. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38132. continue;
  38133. if (line.indexOf('#') === 0)
  38134. continue;
  38135. var words = line.split(" ");
  38136. if (size === 0) {
  38137. // Number of space + one
  38138. size = words.length;
  38139. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38140. tempData = new Float32Array(size * size * size * 4);
  38141. continue;
  38142. }
  38143. if (size != 0) {
  38144. var r = Math.max(parseInt(words[0]), 0);
  38145. var g = Math.max(parseInt(words[1]), 0);
  38146. var b = Math.max(parseInt(words[2]), 0);
  38147. maxColor = Math.max(r, maxColor);
  38148. maxColor = Math.max(g, maxColor);
  38149. maxColor = Math.max(b, maxColor);
  38150. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38151. if (tempData) {
  38152. tempData[pixelStorageIndex + 0] = r;
  38153. tempData[pixelStorageIndex + 1] = g;
  38154. tempData[pixelStorageIndex + 2] = b;
  38155. }
  38156. pixelIndexSlice++;
  38157. if (pixelIndexSlice % size == 0) {
  38158. pixelIndexH++;
  38159. pixelIndexSlice = 0;
  38160. if (pixelIndexH % size == 0) {
  38161. pixelIndexW++;
  38162. pixelIndexH = 0;
  38163. }
  38164. }
  38165. }
  38166. }
  38167. if (tempData && data) {
  38168. for (var i = 0; i < tempData.length; i++) {
  38169. if (i > 0 && (i + 1) % 4 === 0) {
  38170. data[i] = 255;
  38171. }
  38172. else {
  38173. var value = tempData[i];
  38174. data[i] = (value / maxColor * 255);
  38175. }
  38176. }
  38177. }
  38178. if (texture.is3D) {
  38179. texture.updateSize(size, size, size);
  38180. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38181. }
  38182. else {
  38183. texture.updateSize(size * size, size);
  38184. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38185. }
  38186. };
  38187. var scene = this.getScene();
  38188. if (scene) {
  38189. scene._loadFile(this.url, callback);
  38190. }
  38191. else {
  38192. this._engine._loadFile(this.url, callback);
  38193. }
  38194. return this._texture;
  38195. };
  38196. /**
  38197. * Starts the loading process of the texture.
  38198. */
  38199. ColorGradingTexture.prototype.loadTexture = function () {
  38200. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38201. this.load3dlTexture();
  38202. }
  38203. };
  38204. /**
  38205. * Clones the color gradind texture.
  38206. */
  38207. ColorGradingTexture.prototype.clone = function () {
  38208. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38209. // Base texture
  38210. newTexture.level = this.level;
  38211. return newTexture;
  38212. };
  38213. /**
  38214. * Called during delayed load for textures.
  38215. */
  38216. ColorGradingTexture.prototype.delayLoad = function () {
  38217. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38218. return;
  38219. }
  38220. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38221. this._texture = this._getFromCache(this.url, true);
  38222. if (!this._texture) {
  38223. this.loadTexture();
  38224. }
  38225. };
  38226. /**
  38227. * Parses a color grading texture serialized by Babylon.
  38228. * @param parsedTexture The texture information being parsedTexture
  38229. * @param scene The scene to load the texture in
  38230. * @param rootUrl The root url of the data assets to load
  38231. * @return A color gradind texture
  38232. */
  38233. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38234. var texture = null;
  38235. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38236. texture = new ColorGradingTexture(parsedTexture.name, scene);
  38237. texture.name = parsedTexture.name;
  38238. texture.level = parsedTexture.level;
  38239. }
  38240. return texture;
  38241. };
  38242. /**
  38243. * Serializes the LUT texture to json format.
  38244. */
  38245. ColorGradingTexture.prototype.serialize = function () {
  38246. if (!this.name) {
  38247. return null;
  38248. }
  38249. var serializationObject = {};
  38250. serializationObject.name = this.name;
  38251. serializationObject.level = this.level;
  38252. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38253. return serializationObject;
  38254. };
  38255. /**
  38256. * Empty line regex stored for GC.
  38257. */
  38258. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38259. return ColorGradingTexture;
  38260. }(BABYLON.BaseTexture));
  38261. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38262. })(BABYLON || (BABYLON = {}));
  38263. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38264. "use strict";
  38265. var BABYLON;
  38266. (function (BABYLON) {
  38267. /**
  38268. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38269. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38270. * 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;
  38271. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38272. */
  38273. var ColorCurves = /** @class */ (function () {
  38274. function ColorCurves() {
  38275. this._dirty = true;
  38276. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38277. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38278. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38279. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38280. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38281. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38282. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38283. this._globalHue = 30;
  38284. this._globalDensity = 0;
  38285. this._globalSaturation = 0;
  38286. this._globalExposure = 0;
  38287. this._highlightsHue = 30;
  38288. this._highlightsDensity = 0;
  38289. this._highlightsSaturation = 0;
  38290. this._highlightsExposure = 0;
  38291. this._midtonesHue = 30;
  38292. this._midtonesDensity = 0;
  38293. this._midtonesSaturation = 0;
  38294. this._midtonesExposure = 0;
  38295. this._shadowsHue = 30;
  38296. this._shadowsDensity = 0;
  38297. this._shadowsSaturation = 0;
  38298. this._shadowsExposure = 0;
  38299. }
  38300. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38301. /**
  38302. * Gets the global Hue value.
  38303. * 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).
  38304. */
  38305. get: function () {
  38306. return this._globalHue;
  38307. },
  38308. /**
  38309. * Sets the global Hue value.
  38310. * 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).
  38311. */
  38312. set: function (value) {
  38313. this._globalHue = value;
  38314. this._dirty = true;
  38315. },
  38316. enumerable: true,
  38317. configurable: true
  38318. });
  38319. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38320. /**
  38321. * Gets the global Density value.
  38322. * 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.
  38323. * Values less than zero provide a filter of opposite hue.
  38324. */
  38325. get: function () {
  38326. return this._globalDensity;
  38327. },
  38328. /**
  38329. * Sets the global Density value.
  38330. * 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.
  38331. * Values less than zero provide a filter of opposite hue.
  38332. */
  38333. set: function (value) {
  38334. this._globalDensity = value;
  38335. this._dirty = true;
  38336. },
  38337. enumerable: true,
  38338. configurable: true
  38339. });
  38340. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38341. /**
  38342. * Gets the global Saturation value.
  38343. * 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.
  38344. */
  38345. get: function () {
  38346. return this._globalSaturation;
  38347. },
  38348. /**
  38349. * Sets the global Saturation value.
  38350. * 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.
  38351. */
  38352. set: function (value) {
  38353. this._globalSaturation = value;
  38354. this._dirty = true;
  38355. },
  38356. enumerable: true,
  38357. configurable: true
  38358. });
  38359. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38360. /**
  38361. * Gets the highlights Hue value.
  38362. * 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).
  38363. */
  38364. get: function () {
  38365. return this._highlightsHue;
  38366. },
  38367. /**
  38368. * Sets the highlights Hue value.
  38369. * 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).
  38370. */
  38371. set: function (value) {
  38372. this._highlightsHue = value;
  38373. this._dirty = true;
  38374. },
  38375. enumerable: true,
  38376. configurable: true
  38377. });
  38378. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38379. /**
  38380. * Gets the highlights Density value.
  38381. * 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.
  38382. * Values less than zero provide a filter of opposite hue.
  38383. */
  38384. get: function () {
  38385. return this._highlightsDensity;
  38386. },
  38387. /**
  38388. * Sets the highlights Density value.
  38389. * 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.
  38390. * Values less than zero provide a filter of opposite hue.
  38391. */
  38392. set: function (value) {
  38393. this._highlightsDensity = value;
  38394. this._dirty = true;
  38395. },
  38396. enumerable: true,
  38397. configurable: true
  38398. });
  38399. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38400. /**
  38401. * Gets the highlights Saturation value.
  38402. * 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.
  38403. */
  38404. get: function () {
  38405. return this._highlightsSaturation;
  38406. },
  38407. /**
  38408. * Sets the highlights Saturation value.
  38409. * 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.
  38410. */
  38411. set: function (value) {
  38412. this._highlightsSaturation = value;
  38413. this._dirty = true;
  38414. },
  38415. enumerable: true,
  38416. configurable: true
  38417. });
  38418. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38419. /**
  38420. * Gets the highlights Exposure value.
  38421. * 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.
  38422. */
  38423. get: function () {
  38424. return this._highlightsExposure;
  38425. },
  38426. /**
  38427. * Sets the highlights Exposure value.
  38428. * 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.
  38429. */
  38430. set: function (value) {
  38431. this._highlightsExposure = value;
  38432. this._dirty = true;
  38433. },
  38434. enumerable: true,
  38435. configurable: true
  38436. });
  38437. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38438. /**
  38439. * Gets the midtones Hue value.
  38440. * 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).
  38441. */
  38442. get: function () {
  38443. return this._midtonesHue;
  38444. },
  38445. /**
  38446. * Sets the midtones Hue value.
  38447. * 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).
  38448. */
  38449. set: function (value) {
  38450. this._midtonesHue = value;
  38451. this._dirty = true;
  38452. },
  38453. enumerable: true,
  38454. configurable: true
  38455. });
  38456. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38457. /**
  38458. * Gets the midtones Density value.
  38459. * 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.
  38460. * Values less than zero provide a filter of opposite hue.
  38461. */
  38462. get: function () {
  38463. return this._midtonesDensity;
  38464. },
  38465. /**
  38466. * Sets the midtones Density value.
  38467. * 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.
  38468. * Values less than zero provide a filter of opposite hue.
  38469. */
  38470. set: function (value) {
  38471. this._midtonesDensity = value;
  38472. this._dirty = true;
  38473. },
  38474. enumerable: true,
  38475. configurable: true
  38476. });
  38477. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38478. /**
  38479. * Gets the midtones Saturation value.
  38480. * 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.
  38481. */
  38482. get: function () {
  38483. return this._midtonesSaturation;
  38484. },
  38485. /**
  38486. * Sets the midtones Saturation value.
  38487. * 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.
  38488. */
  38489. set: function (value) {
  38490. this._midtonesSaturation = value;
  38491. this._dirty = true;
  38492. },
  38493. enumerable: true,
  38494. configurable: true
  38495. });
  38496. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38497. /**
  38498. * Gets the midtones Exposure value.
  38499. * 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.
  38500. */
  38501. get: function () {
  38502. return this._midtonesExposure;
  38503. },
  38504. /**
  38505. * Sets the midtones Exposure value.
  38506. * 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.
  38507. */
  38508. set: function (value) {
  38509. this._midtonesExposure = value;
  38510. this._dirty = true;
  38511. },
  38512. enumerable: true,
  38513. configurable: true
  38514. });
  38515. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38516. /**
  38517. * Gets the shadows Hue value.
  38518. * 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).
  38519. */
  38520. get: function () {
  38521. return this._shadowsHue;
  38522. },
  38523. /**
  38524. * Sets the shadows Hue value.
  38525. * 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).
  38526. */
  38527. set: function (value) {
  38528. this._shadowsHue = value;
  38529. this._dirty = true;
  38530. },
  38531. enumerable: true,
  38532. configurable: true
  38533. });
  38534. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38535. /**
  38536. * Gets the shadows Density value.
  38537. * 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.
  38538. * Values less than zero provide a filter of opposite hue.
  38539. */
  38540. get: function () {
  38541. return this._shadowsDensity;
  38542. },
  38543. /**
  38544. * Sets the shadows Density value.
  38545. * 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.
  38546. * Values less than zero provide a filter of opposite hue.
  38547. */
  38548. set: function (value) {
  38549. this._shadowsDensity = value;
  38550. this._dirty = true;
  38551. },
  38552. enumerable: true,
  38553. configurable: true
  38554. });
  38555. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38556. /**
  38557. * Gets the shadows Saturation value.
  38558. * 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.
  38559. */
  38560. get: function () {
  38561. return this._shadowsSaturation;
  38562. },
  38563. /**
  38564. * Sets the shadows Saturation value.
  38565. * 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.
  38566. */
  38567. set: function (value) {
  38568. this._shadowsSaturation = value;
  38569. this._dirty = true;
  38570. },
  38571. enumerable: true,
  38572. configurable: true
  38573. });
  38574. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38575. /**
  38576. * Gets the shadows Exposure value.
  38577. * 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.
  38578. */
  38579. get: function () {
  38580. return this._shadowsExposure;
  38581. },
  38582. /**
  38583. * Sets the shadows Exposure value.
  38584. * 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.
  38585. */
  38586. set: function (value) {
  38587. this._shadowsExposure = value;
  38588. this._dirty = true;
  38589. },
  38590. enumerable: true,
  38591. configurable: true
  38592. });
  38593. ColorCurves.prototype.getClassName = function () {
  38594. return "ColorCurves";
  38595. };
  38596. /**
  38597. * Binds the color curves to the shader.
  38598. * @param colorCurves The color curve to bind
  38599. * @param effect The effect to bind to
  38600. */
  38601. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38602. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38603. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38604. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38605. if (colorCurves._dirty) {
  38606. colorCurves._dirty = false;
  38607. // Fill in global info.
  38608. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38609. // Compute highlights info.
  38610. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38611. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38612. // Compute midtones info.
  38613. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38614. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38615. // Compute shadows info.
  38616. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38617. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38618. // Compute deltas (neutral is midtones).
  38619. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38620. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38621. }
  38622. if (effect) {
  38623. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38624. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38625. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38626. }
  38627. };
  38628. /**
  38629. * Prepare the list of uniforms associated with the ColorCurves effects.
  38630. * @param uniformsList The list of uniforms used in the effect
  38631. */
  38632. ColorCurves.PrepareUniforms = function (uniformsList) {
  38633. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38634. };
  38635. /**
  38636. * Returns color grading data based on a hue, density, saturation and exposure value.
  38637. * @param filterHue The hue of the color filter.
  38638. * @param filterDensity The density of the color filter.
  38639. * @param saturation The saturation.
  38640. * @param exposure The exposure.
  38641. * @param result The result data container.
  38642. */
  38643. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38644. if (hue == null) {
  38645. return;
  38646. }
  38647. hue = ColorCurves.clamp(hue, 0, 360);
  38648. density = ColorCurves.clamp(density, -100, 100);
  38649. saturation = ColorCurves.clamp(saturation, -100, 100);
  38650. exposure = ColorCurves.clamp(exposure, -100, 100);
  38651. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38652. // so that the maximum filter density is only 50% control. This provides fine control
  38653. // for small values and reasonable range.
  38654. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38655. density *= 0.5;
  38656. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38657. if (density < 0) {
  38658. density *= -1;
  38659. hue = (hue + 180) % 360;
  38660. }
  38661. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38662. result.scaleToRef(2, result);
  38663. result.a = 1 + 0.01 * saturation;
  38664. };
  38665. /**
  38666. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38667. * @param value The input slider value in range [-100,100].
  38668. * @returns Adjusted value.
  38669. */
  38670. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38671. value /= 100;
  38672. var x = Math.abs(value);
  38673. x = Math.pow(x, 2);
  38674. if (value < 0) {
  38675. x *= -1;
  38676. }
  38677. x *= 100;
  38678. return x;
  38679. };
  38680. /**
  38681. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38682. * @param hue The hue (H) input.
  38683. * @param saturation The saturation (S) input.
  38684. * @param brightness The brightness (B) input.
  38685. * @result An RGBA color represented as Vector4.
  38686. */
  38687. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38688. var h = ColorCurves.clamp(hue, 0, 360);
  38689. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38690. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38691. if (s === 0) {
  38692. result.r = v;
  38693. result.g = v;
  38694. result.b = v;
  38695. }
  38696. else {
  38697. // sector 0 to 5
  38698. h /= 60;
  38699. var i = Math.floor(h);
  38700. // fractional part of h
  38701. var f = h - i;
  38702. var p = v * (1 - s);
  38703. var q = v * (1 - s * f);
  38704. var t = v * (1 - s * (1 - f));
  38705. switch (i) {
  38706. case 0:
  38707. result.r = v;
  38708. result.g = t;
  38709. result.b = p;
  38710. break;
  38711. case 1:
  38712. result.r = q;
  38713. result.g = v;
  38714. result.b = p;
  38715. break;
  38716. case 2:
  38717. result.r = p;
  38718. result.g = v;
  38719. result.b = t;
  38720. break;
  38721. case 3:
  38722. result.r = p;
  38723. result.g = q;
  38724. result.b = v;
  38725. break;
  38726. case 4:
  38727. result.r = t;
  38728. result.g = p;
  38729. result.b = v;
  38730. break;
  38731. default:// case 5:
  38732. result.r = v;
  38733. result.g = p;
  38734. result.b = q;
  38735. break;
  38736. }
  38737. }
  38738. result.a = 1;
  38739. };
  38740. /**
  38741. * Returns a value clamped between min and max
  38742. * @param value The value to clamp
  38743. * @param min The minimum of value
  38744. * @param max The maximum of value
  38745. * @returns The clamped value.
  38746. */
  38747. ColorCurves.clamp = function (value, min, max) {
  38748. return Math.min(Math.max(value, min), max);
  38749. };
  38750. /**
  38751. * Clones the current color curve instance.
  38752. * @return The cloned curves
  38753. */
  38754. ColorCurves.prototype.clone = function () {
  38755. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38756. };
  38757. /**
  38758. * Serializes the current color curve instance to a json representation.
  38759. * @return a JSON representation
  38760. */
  38761. ColorCurves.prototype.serialize = function () {
  38762. return BABYLON.SerializationHelper.Serialize(this);
  38763. };
  38764. /**
  38765. * Parses the color curve from a json representation.
  38766. * @param source the JSON source to parse
  38767. * @return The parsed curves
  38768. */
  38769. ColorCurves.Parse = function (source) {
  38770. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38771. };
  38772. __decorate([
  38773. BABYLON.serialize()
  38774. ], ColorCurves.prototype, "_globalHue", void 0);
  38775. __decorate([
  38776. BABYLON.serialize()
  38777. ], ColorCurves.prototype, "_globalDensity", void 0);
  38778. __decorate([
  38779. BABYLON.serialize()
  38780. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38781. __decorate([
  38782. BABYLON.serialize()
  38783. ], ColorCurves.prototype, "_globalExposure", void 0);
  38784. __decorate([
  38785. BABYLON.serialize()
  38786. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38787. __decorate([
  38788. BABYLON.serialize()
  38789. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38790. __decorate([
  38791. BABYLON.serialize()
  38792. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38793. __decorate([
  38794. BABYLON.serialize()
  38795. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38796. __decorate([
  38797. BABYLON.serialize()
  38798. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38799. __decorate([
  38800. BABYLON.serialize()
  38801. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38802. __decorate([
  38803. BABYLON.serialize()
  38804. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38805. __decorate([
  38806. BABYLON.serialize()
  38807. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38808. return ColorCurves;
  38809. }());
  38810. BABYLON.ColorCurves = ColorCurves;
  38811. })(BABYLON || (BABYLON = {}));
  38812. //# sourceMappingURL=babylon.colorCurves.js.map
  38813. "use strict";
  38814. //# sourceMappingURL=babylon.behavior.js.map
  38815. "use strict";
  38816. var BABYLON;
  38817. (function (BABYLON) {
  38818. /**
  38819. * "Static Class" containing the most commonly used helper while dealing with material for
  38820. * rendering purpose.
  38821. *
  38822. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38823. *
  38824. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38825. */
  38826. var MaterialHelper = /** @class */ (function () {
  38827. function MaterialHelper() {
  38828. }
  38829. /**
  38830. * Bind the current view position to an effect.
  38831. * @param effect The effect to be bound
  38832. * @param scene The scene the eyes position is used from
  38833. */
  38834. MaterialHelper.BindEyePosition = function (effect, scene) {
  38835. if (scene._forcedViewPosition) {
  38836. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38837. return;
  38838. }
  38839. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38840. };
  38841. /**
  38842. * Helps preparing the defines values about the UVs in used in the effect.
  38843. * UVs are shared as much as we can accross chanels in the shaders.
  38844. * @param texture The texture we are preparing the UVs for
  38845. * @param defines The defines to update
  38846. * @param key The chanel key "diffuse", "specular"... used in the shader
  38847. */
  38848. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38849. defines._needUVs = true;
  38850. defines[key] = true;
  38851. if (texture.getTextureMatrix().isIdentity(true)) {
  38852. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38853. if (texture.coordinatesIndex === 0) {
  38854. defines["MAINUV1"] = true;
  38855. }
  38856. else {
  38857. defines["MAINUV2"] = true;
  38858. }
  38859. }
  38860. else {
  38861. defines[key + "DIRECTUV"] = 0;
  38862. }
  38863. };
  38864. /**
  38865. * Binds a texture matrix value to its corrsponding uniform
  38866. * @param texture The texture to bind the matrix for
  38867. * @param uniformBuffer The uniform buffer receivin the data
  38868. * @param key The chanel key "diffuse", "specular"... used in the shader
  38869. */
  38870. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38871. var matrix = texture.getTextureMatrix();
  38872. if (!matrix.isIdentity(true)) {
  38873. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38874. }
  38875. };
  38876. /**
  38877. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38878. * @param mesh defines the current mesh
  38879. * @param scene defines the current scene
  38880. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38881. * @param pointsCloud defines if point cloud rendering has to be turned on
  38882. * @param fogEnabled defines if fog has to be turned on
  38883. * @param alphaTest defines if alpha testing has to be turned on
  38884. * @param defines defines the current list of defines
  38885. */
  38886. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38887. if (defines._areMiscDirty) {
  38888. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38889. defines["POINTSIZE"] = pointsCloud;
  38890. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38891. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38892. defines["ALPHATEST"] = alphaTest;
  38893. }
  38894. };
  38895. /**
  38896. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38897. * @param scene defines the current scene
  38898. * @param engine defines the current engine
  38899. * @param defines specifies the list of active defines
  38900. * @param useInstances defines if instances have to be turned on
  38901. * @param useClipPlane defines if clip plane have to be turned on
  38902. */
  38903. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38904. if (useClipPlane === void 0) { useClipPlane = null; }
  38905. var changed = false;
  38906. if (useClipPlane == null) {
  38907. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38908. }
  38909. if (defines["CLIPPLANE"] !== useClipPlane) {
  38910. defines["CLIPPLANE"] = useClipPlane;
  38911. changed = true;
  38912. }
  38913. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38914. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38915. changed = true;
  38916. }
  38917. if (defines["INSTANCES"] !== useInstances) {
  38918. defines["INSTANCES"] = useInstances;
  38919. changed = true;
  38920. }
  38921. if (changed) {
  38922. defines.markAsUnprocessed();
  38923. }
  38924. };
  38925. /**
  38926. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38927. * @param mesh The mesh containing the geometry data we will draw
  38928. * @param defines The defines to update
  38929. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38930. * @param useBones Precise whether bones should be used or not (override mesh info)
  38931. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38932. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38933. * @returns false if defines are considered not dirty and have not been checked
  38934. */
  38935. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38936. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38937. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38938. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38939. return false;
  38940. }
  38941. defines._normals = defines._needNormals;
  38942. defines._uvs = defines._needUVs;
  38943. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38944. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38945. defines["TANGENT"] = true;
  38946. }
  38947. if (defines._needUVs) {
  38948. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38949. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38950. }
  38951. else {
  38952. defines["UV1"] = false;
  38953. defines["UV2"] = false;
  38954. }
  38955. if (useVertexColor) {
  38956. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38957. defines["VERTEXCOLOR"] = hasVertexColors;
  38958. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38959. }
  38960. if (useBones) {
  38961. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38962. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38963. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38964. }
  38965. else {
  38966. defines["NUM_BONE_INFLUENCERS"] = 0;
  38967. defines["BonesPerMesh"] = 0;
  38968. }
  38969. }
  38970. if (useMorphTargets) {
  38971. var manager = mesh.morphTargetManager;
  38972. if (manager) {
  38973. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38974. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38975. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38976. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38977. }
  38978. else {
  38979. defines["MORPHTARGETS_TANGENT"] = false;
  38980. defines["MORPHTARGETS_NORMAL"] = false;
  38981. defines["MORPHTARGETS"] = false;
  38982. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38983. }
  38984. }
  38985. return true;
  38986. };
  38987. /**
  38988. * Prepares the defines related to the light information passed in parameter
  38989. * @param scene The scene we are intending to draw
  38990. * @param mesh The mesh the effect is compiling for
  38991. * @param defines The defines to update
  38992. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38993. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38994. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38995. * @returns true if normals will be required for the rest of the effect
  38996. */
  38997. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38998. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38999. if (disableLighting === void 0) { disableLighting = false; }
  39000. if (!defines._areLightsDirty) {
  39001. return defines._needNormals;
  39002. }
  39003. var lightIndex = 0;
  39004. var needNormals = false;
  39005. var needRebuild = false;
  39006. var lightmapMode = false;
  39007. var shadowEnabled = false;
  39008. var specularEnabled = false;
  39009. if (scene.lightsEnabled && !disableLighting) {
  39010. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  39011. var light = _a[_i];
  39012. needNormals = true;
  39013. if (defines["LIGHT" + lightIndex] === undefined) {
  39014. needRebuild = true;
  39015. }
  39016. defines["LIGHT" + lightIndex] = true;
  39017. defines["SPOTLIGHT" + lightIndex] = false;
  39018. defines["HEMILIGHT" + lightIndex] = false;
  39019. defines["POINTLIGHT" + lightIndex] = false;
  39020. defines["DIRLIGHT" + lightIndex] = false;
  39021. var type;
  39022. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  39023. type = "SPOTLIGHT" + lightIndex;
  39024. var spotLight = light;
  39025. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  39026. }
  39027. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  39028. type = "HEMILIGHT" + lightIndex;
  39029. }
  39030. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  39031. type = "POINTLIGHT" + lightIndex;
  39032. }
  39033. else {
  39034. type = "DIRLIGHT" + lightIndex;
  39035. }
  39036. defines[type] = true;
  39037. // Specular
  39038. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  39039. specularEnabled = true;
  39040. }
  39041. // Shadows
  39042. defines["SHADOW" + lightIndex] = false;
  39043. defines["SHADOWPCF" + lightIndex] = false;
  39044. defines["SHADOWPCSS" + lightIndex] = false;
  39045. defines["SHADOWPOISSON" + lightIndex] = false;
  39046. defines["SHADOWESM" + lightIndex] = false;
  39047. defines["SHADOWCUBE" + lightIndex] = false;
  39048. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  39049. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  39050. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  39051. var shadowGenerator = light.getShadowGenerator();
  39052. if (shadowGenerator) {
  39053. shadowEnabled = true;
  39054. shadowGenerator.prepareDefines(defines, lightIndex);
  39055. }
  39056. }
  39057. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  39058. lightmapMode = true;
  39059. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  39060. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  39061. }
  39062. else {
  39063. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  39064. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  39065. }
  39066. lightIndex++;
  39067. if (lightIndex === maxSimultaneousLights)
  39068. break;
  39069. }
  39070. }
  39071. defines["SPECULARTERM"] = specularEnabled;
  39072. defines["SHADOWS"] = shadowEnabled;
  39073. // Resetting all other lights if any
  39074. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  39075. if (defines["LIGHT" + index] !== undefined) {
  39076. defines["LIGHT" + index] = false;
  39077. defines["HEMILIGHT" + lightIndex] = false;
  39078. defines["POINTLIGHT" + lightIndex] = false;
  39079. defines["DIRLIGHT" + lightIndex] = false;
  39080. defines["SPOTLIGHT" + lightIndex] = false;
  39081. defines["SHADOW" + lightIndex] = false;
  39082. }
  39083. }
  39084. var caps = scene.getEngine().getCaps();
  39085. if (defines["SHADOWFLOAT"] === undefined) {
  39086. needRebuild = true;
  39087. }
  39088. defines["SHADOWFLOAT"] = shadowEnabled &&
  39089. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  39090. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  39091. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  39092. if (needRebuild) {
  39093. defines.rebuild();
  39094. }
  39095. return needNormals;
  39096. };
  39097. /**
  39098. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  39099. * that won t be acctive due to defines being turned off.
  39100. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  39101. * @param samplersList The samplers list
  39102. * @param defines The defines helping in the list generation
  39103. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  39104. */
  39105. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  39106. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39107. var uniformsList;
  39108. var uniformBuffersList = null;
  39109. if (uniformsListOrOptions.uniformsNames) {
  39110. var options = uniformsListOrOptions;
  39111. uniformsList = options.uniformsNames;
  39112. uniformBuffersList = options.uniformBuffersNames;
  39113. samplersList = options.samplers;
  39114. defines = options.defines;
  39115. maxSimultaneousLights = options.maxSimultaneousLights;
  39116. }
  39117. else {
  39118. uniformsList = uniformsListOrOptions;
  39119. if (!samplersList) {
  39120. samplersList = [];
  39121. }
  39122. }
  39123. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39124. if (!defines["LIGHT" + lightIndex]) {
  39125. break;
  39126. }
  39127. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  39128. if (uniformBuffersList) {
  39129. uniformBuffersList.push("Light" + lightIndex);
  39130. }
  39131. samplersList.push("shadowSampler" + lightIndex);
  39132. samplersList.push("depthSampler" + lightIndex);
  39133. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  39134. samplersList.push("projectionLightSampler" + lightIndex);
  39135. uniformsList.push("textureProjectionMatrix" + lightIndex);
  39136. }
  39137. }
  39138. if (defines["NUM_MORPH_INFLUENCERS"]) {
  39139. uniformsList.push("morphTargetInfluences");
  39140. }
  39141. };
  39142. /**
  39143. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  39144. * @param defines The defines to update while falling back
  39145. * @param fallbacks The authorized effect fallbacks
  39146. * @param maxSimultaneousLights The maximum number of lights allowed
  39147. * @param rank the current rank of the Effect
  39148. * @returns The newly affected rank
  39149. */
  39150. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  39151. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39152. if (rank === void 0) { rank = 0; }
  39153. var lightFallbackRank = 0;
  39154. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39155. if (!defines["LIGHT" + lightIndex]) {
  39156. break;
  39157. }
  39158. if (lightIndex > 0) {
  39159. lightFallbackRank = rank + lightIndex;
  39160. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  39161. }
  39162. if (!defines["SHADOWS"]) {
  39163. if (defines["SHADOW" + lightIndex]) {
  39164. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  39165. }
  39166. if (defines["SHADOWPCF" + lightIndex]) {
  39167. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  39168. }
  39169. if (defines["SHADOWPCSS" + lightIndex]) {
  39170. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  39171. }
  39172. if (defines["SHADOWPOISSON" + lightIndex]) {
  39173. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  39174. }
  39175. if (defines["SHADOWESM" + lightIndex]) {
  39176. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  39177. }
  39178. }
  39179. }
  39180. return lightFallbackRank++;
  39181. };
  39182. /**
  39183. * Prepares the list of attributes required for morph targets according to the effect defines.
  39184. * @param attribs The current list of supported attribs
  39185. * @param mesh The mesh to prepare the morph targets attributes for
  39186. * @param defines The current Defines of the effect
  39187. */
  39188. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  39189. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  39190. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  39191. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  39192. var manager = mesh.morphTargetManager;
  39193. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  39194. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  39195. for (var index = 0; index < influencers; index++) {
  39196. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  39197. if (normal) {
  39198. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  39199. }
  39200. if (tangent) {
  39201. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  39202. }
  39203. if (attribs.length > maxAttributesCount) {
  39204. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  39205. }
  39206. }
  39207. }
  39208. };
  39209. /**
  39210. * Prepares the list of attributes required for bones according to the effect defines.
  39211. * @param attribs The current list of supported attribs
  39212. * @param mesh The mesh to prepare the bones attributes for
  39213. * @param defines The current Defines of the effect
  39214. * @param fallbacks The current efffect fallback strategy
  39215. */
  39216. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  39217. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  39218. fallbacks.addCPUSkinningFallback(0, mesh);
  39219. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39220. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39221. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  39222. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39223. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39224. }
  39225. }
  39226. };
  39227. /**
  39228. * Prepares the list of attributes required for instances according to the effect defines.
  39229. * @param attribs The current list of supported attribs
  39230. * @param defines The current Defines of the effect
  39231. */
  39232. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  39233. if (defines["INSTANCES"]) {
  39234. attribs.push("world0");
  39235. attribs.push("world1");
  39236. attribs.push("world2");
  39237. attribs.push("world3");
  39238. }
  39239. };
  39240. /**
  39241. * Binds the light shadow information to the effect for the given mesh.
  39242. * @param light The light containing the generator
  39243. * @param scene The scene the lights belongs to
  39244. * @param mesh The mesh we are binding the information to render
  39245. * @param lightIndex The light index in the effect used to render the mesh
  39246. * @param effect The effect we are binding the data to
  39247. */
  39248. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  39249. if (light.shadowEnabled && mesh.receiveShadows) {
  39250. var shadowGenerator = light.getShadowGenerator();
  39251. if (shadowGenerator) {
  39252. shadowGenerator.bindShadowLight(lightIndex, effect);
  39253. }
  39254. }
  39255. };
  39256. /**
  39257. * Binds the light information to the effect.
  39258. * @param light The light containing the generator
  39259. * @param effect The effect we are binding the data to
  39260. * @param lightIndex The light index in the effect used to render
  39261. */
  39262. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  39263. light.transferToEffect(effect, lightIndex + "");
  39264. };
  39265. /**
  39266. * Binds the lights information from the scene to the effect for the given mesh.
  39267. * @param scene The scene the lights belongs to
  39268. * @param mesh The mesh we are binding the information to render
  39269. * @param effect The effect we are binding the data to
  39270. * @param defines The generated defines for the effect
  39271. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  39272. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  39273. */
  39274. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  39275. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39276. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  39277. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  39278. for (var i = 0; i < len; i++) {
  39279. var light = mesh._lightSources[i];
  39280. var iAsString = i.toString();
  39281. var scaledIntensity = light.getScaledIntensity();
  39282. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  39283. MaterialHelper.BindLightProperties(light, effect, i);
  39284. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  39285. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  39286. if (defines["SPECULARTERM"]) {
  39287. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  39288. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  39289. }
  39290. // Shadows
  39291. if (scene.shadowsEnabled) {
  39292. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  39293. }
  39294. light._uniformBuffer.update();
  39295. }
  39296. };
  39297. /**
  39298. * Binds the fog information from the scene to the effect for the given mesh.
  39299. * @param scene The scene the lights belongs to
  39300. * @param mesh The mesh we are binding the information to render
  39301. * @param effect The effect we are binding the data to
  39302. */
  39303. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  39304. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  39305. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  39306. effect.setColor3("vFogColor", scene.fogColor);
  39307. }
  39308. };
  39309. /**
  39310. * Binds the bones information from the mesh to the effect.
  39311. * @param mesh The mesh we are binding the information to render
  39312. * @param effect The effect we are binding the data to
  39313. */
  39314. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  39315. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39316. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  39317. if (matrices && effect) {
  39318. effect.setMatrices("mBones", matrices);
  39319. }
  39320. }
  39321. };
  39322. /**
  39323. * Binds the morph targets information from the mesh to the effect.
  39324. * @param abstractMesh The mesh we are binding the information to render
  39325. * @param effect The effect we are binding the data to
  39326. */
  39327. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  39328. var manager = abstractMesh.morphTargetManager;
  39329. if (!abstractMesh || !manager) {
  39330. return;
  39331. }
  39332. effect.setFloatArray("morphTargetInfluences", manager.influences);
  39333. };
  39334. /**
  39335. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  39336. * @param defines The generated defines used in the effect
  39337. * @param effect The effect we are binding the data to
  39338. * @param scene The scene we are willing to render with logarithmic scale for
  39339. */
  39340. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  39341. if (defines["LOGARITHMICDEPTH"]) {
  39342. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  39343. }
  39344. };
  39345. /**
  39346. * Binds the clip plane information from the scene to the effect.
  39347. * @param scene The scene the clip plane information are extracted from
  39348. * @param effect The effect we are binding the data to
  39349. */
  39350. MaterialHelper.BindClipPlane = function (effect, scene) {
  39351. if (scene.clipPlane) {
  39352. var clipPlane = scene.clipPlane;
  39353. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39354. }
  39355. };
  39356. return MaterialHelper;
  39357. }());
  39358. BABYLON.MaterialHelper = MaterialHelper;
  39359. })(BABYLON || (BABYLON = {}));
  39360. //# sourceMappingURL=babylon.materialHelper.js.map
  39361. "use strict";
  39362. var BABYLON;
  39363. (function (BABYLON) {
  39364. var PushMaterial = /** @class */ (function (_super) {
  39365. __extends(PushMaterial, _super);
  39366. function PushMaterial(name, scene) {
  39367. var _this = _super.call(this, name, scene) || this;
  39368. _this._normalMatrix = new BABYLON.Matrix();
  39369. _this.storeEffectOnSubMeshes = true;
  39370. return _this;
  39371. }
  39372. PushMaterial.prototype.getEffect = function () {
  39373. return this._activeEffect;
  39374. };
  39375. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  39376. if (!mesh) {
  39377. return false;
  39378. }
  39379. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  39380. return true;
  39381. }
  39382. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39383. };
  39384. /**
  39385. * Binds the given world matrix to the active effect
  39386. *
  39387. * @param world the matrix to bind
  39388. */
  39389. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39390. this._activeEffect.setMatrix("world", world);
  39391. };
  39392. /**
  39393. * Binds the given normal matrix to the active effect
  39394. *
  39395. * @param normalMatrix the matrix to bind
  39396. */
  39397. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39398. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39399. };
  39400. PushMaterial.prototype.bind = function (world, mesh) {
  39401. if (!mesh) {
  39402. return;
  39403. }
  39404. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39405. };
  39406. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39407. if (effect === void 0) { effect = null; }
  39408. _super.prototype._afterBind.call(this, mesh);
  39409. this.getScene()._cachedEffect = effect;
  39410. };
  39411. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39412. if (visibility === void 0) { visibility = 1; }
  39413. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39414. };
  39415. return PushMaterial;
  39416. }(BABYLON.Material));
  39417. BABYLON.PushMaterial = PushMaterial;
  39418. })(BABYLON || (BABYLON = {}));
  39419. //# sourceMappingURL=babylon.pushMaterial.js.map
  39420. "use strict";
  39421. var BABYLON;
  39422. (function (BABYLON) {
  39423. /** @ignore */
  39424. var StandardMaterialDefines = /** @class */ (function (_super) {
  39425. __extends(StandardMaterialDefines, _super);
  39426. function StandardMaterialDefines() {
  39427. var _this = _super.call(this) || this;
  39428. _this.MAINUV1 = false;
  39429. _this.MAINUV2 = false;
  39430. _this.DIFFUSE = false;
  39431. _this.DIFFUSEDIRECTUV = 0;
  39432. _this.AMBIENT = false;
  39433. _this.AMBIENTDIRECTUV = 0;
  39434. _this.OPACITY = false;
  39435. _this.OPACITYDIRECTUV = 0;
  39436. _this.OPACITYRGB = false;
  39437. _this.REFLECTION = false;
  39438. _this.EMISSIVE = false;
  39439. _this.EMISSIVEDIRECTUV = 0;
  39440. _this.SPECULAR = false;
  39441. _this.SPECULARDIRECTUV = 0;
  39442. _this.BUMP = false;
  39443. _this.BUMPDIRECTUV = 0;
  39444. _this.PARALLAX = false;
  39445. _this.PARALLAXOCCLUSION = false;
  39446. _this.SPECULAROVERALPHA = false;
  39447. _this.CLIPPLANE = false;
  39448. _this.ALPHATEST = false;
  39449. _this.DEPTHPREPASS = false;
  39450. _this.ALPHAFROMDIFFUSE = false;
  39451. _this.POINTSIZE = false;
  39452. _this.FOG = false;
  39453. _this.SPECULARTERM = false;
  39454. _this.DIFFUSEFRESNEL = false;
  39455. _this.OPACITYFRESNEL = false;
  39456. _this.REFLECTIONFRESNEL = false;
  39457. _this.REFRACTIONFRESNEL = false;
  39458. _this.EMISSIVEFRESNEL = false;
  39459. _this.FRESNEL = false;
  39460. _this.NORMAL = false;
  39461. _this.UV1 = false;
  39462. _this.UV2 = false;
  39463. _this.VERTEXCOLOR = false;
  39464. _this.VERTEXALPHA = false;
  39465. _this.NUM_BONE_INFLUENCERS = 0;
  39466. _this.BonesPerMesh = 0;
  39467. _this.INSTANCES = false;
  39468. _this.GLOSSINESS = false;
  39469. _this.ROUGHNESS = false;
  39470. _this.EMISSIVEASILLUMINATION = false;
  39471. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39472. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39473. _this.LIGHTMAP = false;
  39474. _this.LIGHTMAPDIRECTUV = 0;
  39475. _this.OBJECTSPACE_NORMALMAP = false;
  39476. _this.USELIGHTMAPASSHADOWMAP = false;
  39477. _this.REFLECTIONMAP_3D = false;
  39478. _this.REFLECTIONMAP_SPHERICAL = false;
  39479. _this.REFLECTIONMAP_PLANAR = false;
  39480. _this.REFLECTIONMAP_CUBIC = false;
  39481. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39482. _this.REFLECTIONMAP_PROJECTION = false;
  39483. _this.REFLECTIONMAP_SKYBOX = false;
  39484. _this.REFLECTIONMAP_EXPLICIT = false;
  39485. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39486. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39487. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39488. _this.INVERTCUBICMAP = false;
  39489. _this.LOGARITHMICDEPTH = false;
  39490. _this.REFRACTION = false;
  39491. _this.REFRACTIONMAP_3D = false;
  39492. _this.REFLECTIONOVERALPHA = false;
  39493. _this.TWOSIDEDLIGHTING = false;
  39494. _this.SHADOWFLOAT = false;
  39495. _this.MORPHTARGETS = false;
  39496. _this.MORPHTARGETS_NORMAL = false;
  39497. _this.MORPHTARGETS_TANGENT = false;
  39498. _this.NUM_MORPH_INFLUENCERS = 0;
  39499. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39500. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39501. _this.IMAGEPROCESSING = false;
  39502. _this.VIGNETTE = false;
  39503. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39504. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39505. _this.TONEMAPPING = false;
  39506. _this.CONTRAST = false;
  39507. _this.COLORCURVES = false;
  39508. _this.COLORGRADING = false;
  39509. _this.COLORGRADING3D = false;
  39510. _this.SAMPLER3DGREENDEPTH = false;
  39511. _this.SAMPLER3DBGRMAP = false;
  39512. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39513. _this.EXPOSURE = false;
  39514. _this.GRAIN = false;
  39515. _this.rebuild();
  39516. return _this;
  39517. }
  39518. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39519. var modes = [
  39520. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39521. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39522. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39523. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39524. ];
  39525. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39526. var mode = modes_1[_i];
  39527. this[mode] = (mode === modeToEnable);
  39528. }
  39529. };
  39530. return StandardMaterialDefines;
  39531. }(BABYLON.MaterialDefines));
  39532. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39533. var StandardMaterial = /** @class */ (function (_super) {
  39534. __extends(StandardMaterial, _super);
  39535. function StandardMaterial(name, scene) {
  39536. var _this = _super.call(this, name, scene) || this;
  39537. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39538. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39539. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39540. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39541. _this.specularPower = 64;
  39542. _this._useAlphaFromDiffuseTexture = false;
  39543. _this._useEmissiveAsIllumination = false;
  39544. _this._linkEmissiveWithDiffuse = false;
  39545. _this._useSpecularOverAlpha = false;
  39546. _this._useReflectionOverAlpha = false;
  39547. _this._disableLighting = false;
  39548. _this._useObjectSpaceNormalMap = false;
  39549. _this._useParallax = false;
  39550. _this._useParallaxOcclusion = false;
  39551. _this.parallaxScaleBias = 0.05;
  39552. _this._roughness = 0;
  39553. _this.indexOfRefraction = 0.98;
  39554. _this.invertRefractionY = true;
  39555. _this._useLightmapAsShadowmap = false;
  39556. _this._useReflectionFresnelFromSpecular = false;
  39557. _this._useGlossinessFromSpecularMapAlpha = false;
  39558. _this._maxSimultaneousLights = 4;
  39559. /**
  39560. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39561. */
  39562. _this._invertNormalMapX = false;
  39563. /**
  39564. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39565. */
  39566. _this._invertNormalMapY = false;
  39567. /**
  39568. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39569. */
  39570. _this._twoSidedLighting = false;
  39571. _this._renderTargets = new BABYLON.SmartArray(16);
  39572. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39573. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39574. // Setup the default processing configuration to the scene.
  39575. _this._attachImageProcessingConfiguration(null);
  39576. _this.getRenderTargetTextures = function () {
  39577. _this._renderTargets.reset();
  39578. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39579. _this._renderTargets.push(_this._reflectionTexture);
  39580. }
  39581. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39582. _this._renderTargets.push(_this._refractionTexture);
  39583. }
  39584. return _this._renderTargets;
  39585. };
  39586. return _this;
  39587. }
  39588. ;
  39589. ;
  39590. ;
  39591. ;
  39592. ;
  39593. ;
  39594. ;
  39595. ;
  39596. ;
  39597. ;
  39598. ;
  39599. ;
  39600. ;
  39601. ;
  39602. ;
  39603. ;
  39604. ;
  39605. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39606. /**
  39607. * Gets the image processing configuration used either in this material.
  39608. */
  39609. get: function () {
  39610. return this._imageProcessingConfiguration;
  39611. },
  39612. /**
  39613. * Sets the Default image processing configuration used either in the this material.
  39614. *
  39615. * If sets to null, the scene one is in use.
  39616. */
  39617. set: function (value) {
  39618. this._attachImageProcessingConfiguration(value);
  39619. // Ensure the effect will be rebuilt.
  39620. this._markAllSubMeshesAsTexturesDirty();
  39621. },
  39622. enumerable: true,
  39623. configurable: true
  39624. });
  39625. /**
  39626. * Attaches a new image processing configuration to the Standard Material.
  39627. * @param configuration
  39628. */
  39629. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39630. var _this = this;
  39631. if (configuration === this._imageProcessingConfiguration) {
  39632. return;
  39633. }
  39634. // Detaches observer.
  39635. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39636. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39637. }
  39638. // Pick the scene configuration if needed.
  39639. if (!configuration) {
  39640. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39641. }
  39642. else {
  39643. this._imageProcessingConfiguration = configuration;
  39644. }
  39645. // Attaches observer.
  39646. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39647. _this._markAllSubMeshesAsImageProcessingDirty();
  39648. });
  39649. };
  39650. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39651. /**
  39652. * Gets wether the color curves effect is enabled.
  39653. */
  39654. get: function () {
  39655. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39656. },
  39657. /**
  39658. * Sets wether the color curves effect is enabled.
  39659. */
  39660. set: function (value) {
  39661. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39662. },
  39663. enumerable: true,
  39664. configurable: true
  39665. });
  39666. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39667. /**
  39668. * Gets wether the color grading effect is enabled.
  39669. */
  39670. get: function () {
  39671. return this.imageProcessingConfiguration.colorGradingEnabled;
  39672. },
  39673. /**
  39674. * Gets wether the color grading effect is enabled.
  39675. */
  39676. set: function (value) {
  39677. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39678. },
  39679. enumerable: true,
  39680. configurable: true
  39681. });
  39682. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39683. /**
  39684. * Gets wether tonemapping is enabled or not.
  39685. */
  39686. get: function () {
  39687. return this._imageProcessingConfiguration.toneMappingEnabled;
  39688. },
  39689. /**
  39690. * Sets wether tonemapping is enabled or not
  39691. */
  39692. set: function (value) {
  39693. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39694. },
  39695. enumerable: true,
  39696. configurable: true
  39697. });
  39698. ;
  39699. ;
  39700. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39701. /**
  39702. * The camera exposure used on this material.
  39703. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39704. * This corresponds to a photographic exposure.
  39705. */
  39706. get: function () {
  39707. return this._imageProcessingConfiguration.exposure;
  39708. },
  39709. /**
  39710. * The camera exposure used on this material.
  39711. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39712. * This corresponds to a photographic exposure.
  39713. */
  39714. set: function (value) {
  39715. this._imageProcessingConfiguration.exposure = value;
  39716. },
  39717. enumerable: true,
  39718. configurable: true
  39719. });
  39720. ;
  39721. ;
  39722. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39723. /**
  39724. * Gets The camera contrast used on this material.
  39725. */
  39726. get: function () {
  39727. return this._imageProcessingConfiguration.contrast;
  39728. },
  39729. /**
  39730. * Sets The camera contrast used on this material.
  39731. */
  39732. set: function (value) {
  39733. this._imageProcessingConfiguration.contrast = value;
  39734. },
  39735. enumerable: true,
  39736. configurable: true
  39737. });
  39738. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39739. /**
  39740. * Gets the Color Grading 2D Lookup Texture.
  39741. */
  39742. get: function () {
  39743. return this._imageProcessingConfiguration.colorGradingTexture;
  39744. },
  39745. /**
  39746. * Sets the Color Grading 2D Lookup Texture.
  39747. */
  39748. set: function (value) {
  39749. this._imageProcessingConfiguration.colorGradingTexture = value;
  39750. },
  39751. enumerable: true,
  39752. configurable: true
  39753. });
  39754. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39755. /**
  39756. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39757. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39758. * 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;
  39759. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39760. */
  39761. get: function () {
  39762. return this._imageProcessingConfiguration.colorCurves;
  39763. },
  39764. /**
  39765. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39766. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39767. * 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;
  39768. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39769. */
  39770. set: function (value) {
  39771. this._imageProcessingConfiguration.colorCurves = value;
  39772. },
  39773. enumerable: true,
  39774. configurable: true
  39775. });
  39776. StandardMaterial.prototype.getClassName = function () {
  39777. return "StandardMaterial";
  39778. };
  39779. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39780. get: function () {
  39781. return this._useLogarithmicDepth;
  39782. },
  39783. set: function (value) {
  39784. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39785. this._markAllSubMeshesAsMiscDirty();
  39786. },
  39787. enumerable: true,
  39788. configurable: true
  39789. });
  39790. StandardMaterial.prototype.needAlphaBlending = function () {
  39791. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39792. };
  39793. StandardMaterial.prototype.needAlphaTesting = function () {
  39794. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39795. };
  39796. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39797. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39798. };
  39799. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39800. return this._diffuseTexture;
  39801. };
  39802. /**
  39803. * Child classes can use it to update shaders
  39804. */
  39805. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39806. if (useInstances === void 0) { useInstances = false; }
  39807. if (subMesh.effect && this.isFrozen) {
  39808. if (this._wasPreviouslyReady && subMesh.effect) {
  39809. return true;
  39810. }
  39811. }
  39812. if (!subMesh._materialDefines) {
  39813. subMesh._materialDefines = new StandardMaterialDefines();
  39814. }
  39815. var scene = this.getScene();
  39816. var defines = subMesh._materialDefines;
  39817. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39818. if (defines._renderId === scene.getRenderId()) {
  39819. return true;
  39820. }
  39821. }
  39822. var engine = scene.getEngine();
  39823. // Lights
  39824. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39825. // Textures
  39826. if (defines._areTexturesDirty) {
  39827. defines._needUVs = false;
  39828. defines.MAINUV1 = false;
  39829. defines.MAINUV2 = false;
  39830. if (scene.texturesEnabled) {
  39831. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39832. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39833. return false;
  39834. }
  39835. else {
  39836. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39837. }
  39838. }
  39839. else {
  39840. defines.DIFFUSE = false;
  39841. }
  39842. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39843. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39844. return false;
  39845. }
  39846. else {
  39847. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39848. }
  39849. }
  39850. else {
  39851. defines.AMBIENT = false;
  39852. }
  39853. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39854. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39855. return false;
  39856. }
  39857. else {
  39858. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39859. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39860. }
  39861. }
  39862. else {
  39863. defines.OPACITY = false;
  39864. }
  39865. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39866. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39867. return false;
  39868. }
  39869. else {
  39870. defines._needNormals = true;
  39871. defines.REFLECTION = true;
  39872. defines.ROUGHNESS = (this._roughness > 0);
  39873. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39874. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39875. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39876. switch (this._reflectionTexture.coordinatesMode) {
  39877. case BABYLON.Texture.CUBIC_MODE:
  39878. case BABYLON.Texture.INVCUBIC_MODE:
  39879. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39880. break;
  39881. case BABYLON.Texture.EXPLICIT_MODE:
  39882. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39883. break;
  39884. case BABYLON.Texture.PLANAR_MODE:
  39885. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39886. break;
  39887. case BABYLON.Texture.PROJECTION_MODE:
  39888. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39889. break;
  39890. case BABYLON.Texture.SKYBOX_MODE:
  39891. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39892. break;
  39893. case BABYLON.Texture.SPHERICAL_MODE:
  39894. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39895. break;
  39896. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39897. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39898. break;
  39899. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39900. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39901. break;
  39902. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39903. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39904. break;
  39905. }
  39906. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39907. }
  39908. }
  39909. else {
  39910. defines.REFLECTION = false;
  39911. }
  39912. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39913. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39914. return false;
  39915. }
  39916. else {
  39917. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39918. }
  39919. }
  39920. else {
  39921. defines.EMISSIVE = false;
  39922. }
  39923. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39924. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39925. return false;
  39926. }
  39927. else {
  39928. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39929. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39930. }
  39931. }
  39932. else {
  39933. defines.LIGHTMAP = false;
  39934. }
  39935. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39936. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39937. return false;
  39938. }
  39939. else {
  39940. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39941. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39942. }
  39943. }
  39944. else {
  39945. defines.SPECULAR = false;
  39946. }
  39947. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39948. // Bump texure can not be not blocking.
  39949. if (!this._bumpTexture.isReady()) {
  39950. return false;
  39951. }
  39952. else {
  39953. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39954. defines.PARALLAX = this._useParallax;
  39955. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39956. }
  39957. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39958. }
  39959. else {
  39960. defines.BUMP = false;
  39961. }
  39962. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39963. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39964. return false;
  39965. }
  39966. else {
  39967. defines._needUVs = true;
  39968. defines.REFRACTION = true;
  39969. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39970. }
  39971. }
  39972. else {
  39973. defines.REFRACTION = false;
  39974. }
  39975. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39976. }
  39977. else {
  39978. defines.DIFFUSE = false;
  39979. defines.AMBIENT = false;
  39980. defines.OPACITY = false;
  39981. defines.REFLECTION = false;
  39982. defines.EMISSIVE = false;
  39983. defines.LIGHTMAP = false;
  39984. defines.BUMP = false;
  39985. defines.REFRACTION = false;
  39986. }
  39987. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39988. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39989. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39990. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39991. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39992. }
  39993. if (defines._areImageProcessingDirty) {
  39994. if (!this._imageProcessingConfiguration.isReady()) {
  39995. return false;
  39996. }
  39997. this._imageProcessingConfiguration.prepareDefines(defines);
  39998. }
  39999. if (defines._areFresnelDirty) {
  40000. if (StandardMaterial.FresnelEnabled) {
  40001. // Fresnel
  40002. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  40003. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  40004. this._reflectionFresnelParameters) {
  40005. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  40006. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  40007. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  40008. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  40009. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  40010. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  40011. defines._needNormals = true;
  40012. defines.FRESNEL = true;
  40013. }
  40014. }
  40015. else {
  40016. defines.FRESNEL = false;
  40017. }
  40018. }
  40019. // Misc.
  40020. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  40021. // Attribs
  40022. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  40023. // Values that need to be evaluated on every frame
  40024. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  40025. // Get correct effect
  40026. if (defines.isDirty) {
  40027. defines.markAsProcessed();
  40028. scene.resetCachedMaterial();
  40029. // Fallbacks
  40030. var fallbacks = new BABYLON.EffectFallbacks();
  40031. if (defines.REFLECTION) {
  40032. fallbacks.addFallback(0, "REFLECTION");
  40033. }
  40034. if (defines.SPECULAR) {
  40035. fallbacks.addFallback(0, "SPECULAR");
  40036. }
  40037. if (defines.BUMP) {
  40038. fallbacks.addFallback(0, "BUMP");
  40039. }
  40040. if (defines.PARALLAX) {
  40041. fallbacks.addFallback(1, "PARALLAX");
  40042. }
  40043. if (defines.PARALLAXOCCLUSION) {
  40044. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  40045. }
  40046. if (defines.SPECULAROVERALPHA) {
  40047. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  40048. }
  40049. if (defines.FOG) {
  40050. fallbacks.addFallback(1, "FOG");
  40051. }
  40052. if (defines.POINTSIZE) {
  40053. fallbacks.addFallback(0, "POINTSIZE");
  40054. }
  40055. if (defines.LOGARITHMICDEPTH) {
  40056. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  40057. }
  40058. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  40059. if (defines.SPECULARTERM) {
  40060. fallbacks.addFallback(0, "SPECULARTERM");
  40061. }
  40062. if (defines.DIFFUSEFRESNEL) {
  40063. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  40064. }
  40065. if (defines.OPACITYFRESNEL) {
  40066. fallbacks.addFallback(2, "OPACITYFRESNEL");
  40067. }
  40068. if (defines.REFLECTIONFRESNEL) {
  40069. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  40070. }
  40071. if (defines.EMISSIVEFRESNEL) {
  40072. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  40073. }
  40074. if (defines.FRESNEL) {
  40075. fallbacks.addFallback(4, "FRESNEL");
  40076. }
  40077. //Attributes
  40078. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40079. if (defines.NORMAL) {
  40080. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40081. }
  40082. if (defines.UV1) {
  40083. attribs.push(BABYLON.VertexBuffer.UVKind);
  40084. }
  40085. if (defines.UV2) {
  40086. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40087. }
  40088. if (defines.VERTEXCOLOR) {
  40089. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40090. }
  40091. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40092. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40093. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40094. var shaderName = "default";
  40095. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  40096. "vFogInfos", "vFogColor", "pointSize",
  40097. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40098. "mBones",
  40099. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  40100. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  40101. "vReflectionPosition", "vReflectionSize",
  40102. "logarithmicDepthConstant", "vTangentSpaceParams"
  40103. ];
  40104. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  40105. var uniformBuffers = ["Material", "Scene"];
  40106. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40107. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40108. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40109. uniformsNames: uniforms,
  40110. uniformBuffersNames: uniformBuffers,
  40111. samplers: samplers,
  40112. defines: defines,
  40113. maxSimultaneousLights: this._maxSimultaneousLights
  40114. });
  40115. if (this.customShaderNameResolve) {
  40116. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  40117. }
  40118. var join = defines.toString();
  40119. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  40120. attributes: attribs,
  40121. uniformsNames: uniforms,
  40122. uniformBuffersNames: uniformBuffers,
  40123. samplers: samplers,
  40124. defines: join,
  40125. fallbacks: fallbacks,
  40126. onCompiled: this.onCompiled,
  40127. onError: this.onError,
  40128. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40129. }, engine), defines);
  40130. this.buildUniformLayout();
  40131. }
  40132. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40133. return false;
  40134. }
  40135. defines._renderId = scene.getRenderId();
  40136. this._wasPreviouslyReady = true;
  40137. return true;
  40138. };
  40139. StandardMaterial.prototype.buildUniformLayout = function () {
  40140. // Order is important !
  40141. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  40142. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  40143. this._uniformBuffer.addUniform("opacityParts", 4);
  40144. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  40145. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  40146. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  40147. this._uniformBuffer.addUniform("refractionRightColor", 4);
  40148. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  40149. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  40150. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  40151. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  40152. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40153. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40154. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40155. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40156. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40157. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40158. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  40159. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40160. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  40161. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40162. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40163. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40164. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40165. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40166. this._uniformBuffer.addUniform("specularMatrix", 16);
  40167. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40168. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40169. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40170. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40171. this._uniformBuffer.addUniform("vSpecularColor", 4);
  40172. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40173. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  40174. this._uniformBuffer.addUniform("pointSize", 1);
  40175. this._uniformBuffer.create();
  40176. };
  40177. StandardMaterial.prototype.unbind = function () {
  40178. if (this._activeEffect) {
  40179. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40180. this._activeEffect.setTexture("reflection2DSampler", null);
  40181. }
  40182. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40183. this._activeEffect.setTexture("refraction2DSampler", null);
  40184. }
  40185. }
  40186. _super.prototype.unbind.call(this);
  40187. };
  40188. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40189. var scene = this.getScene();
  40190. var defines = subMesh._materialDefines;
  40191. if (!defines) {
  40192. return;
  40193. }
  40194. var effect = subMesh.effect;
  40195. if (!effect) {
  40196. return;
  40197. }
  40198. this._activeEffect = effect;
  40199. // Matrices
  40200. this.bindOnlyWorldMatrix(world);
  40201. // Normal Matrix
  40202. if (defines.OBJECTSPACE_NORMALMAP) {
  40203. world.toNormalMatrix(this._normalMatrix);
  40204. this.bindOnlyNormalMatrix(this._normalMatrix);
  40205. }
  40206. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40207. // Bones
  40208. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40209. if (mustRebind) {
  40210. this._uniformBuffer.bindToEffect(effect, "Material");
  40211. this.bindViewProjection(effect);
  40212. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40213. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40214. // Fresnel
  40215. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40216. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40217. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40218. }
  40219. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40220. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40221. }
  40222. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40223. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40224. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40225. }
  40226. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40227. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40228. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40229. }
  40230. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40231. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40232. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  40233. }
  40234. }
  40235. // Textures
  40236. if (scene.texturesEnabled) {
  40237. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40238. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  40239. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  40240. }
  40241. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40242. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  40243. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40244. }
  40245. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40246. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40247. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40248. }
  40249. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40250. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  40251. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  40252. if (this._reflectionTexture.boundingBoxSize) {
  40253. var cubeTexture = this._reflectionTexture;
  40254. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40255. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40256. }
  40257. }
  40258. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40259. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40260. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40261. }
  40262. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40263. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40264. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40265. }
  40266. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40267. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  40268. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  40269. }
  40270. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40271. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  40272. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40273. if (scene._mirroredCameraPosition) {
  40274. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40275. }
  40276. else {
  40277. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40278. }
  40279. }
  40280. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40281. var depth = 1.0;
  40282. if (!this._refractionTexture.isCube) {
  40283. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  40284. if (this._refractionTexture.depth) {
  40285. depth = this._refractionTexture.depth;
  40286. }
  40287. }
  40288. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  40289. }
  40290. }
  40291. // Point size
  40292. if (this.pointsCloud) {
  40293. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40294. }
  40295. if (defines.SPECULARTERM) {
  40296. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  40297. }
  40298. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  40299. // Diffuse
  40300. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  40301. }
  40302. // Textures
  40303. if (scene.texturesEnabled) {
  40304. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40305. effect.setTexture("diffuseSampler", this._diffuseTexture);
  40306. }
  40307. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40308. effect.setTexture("ambientSampler", this._ambientTexture);
  40309. }
  40310. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40311. effect.setTexture("opacitySampler", this._opacityTexture);
  40312. }
  40313. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40314. if (this._reflectionTexture.isCube) {
  40315. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  40316. }
  40317. else {
  40318. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  40319. }
  40320. }
  40321. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40322. effect.setTexture("emissiveSampler", this._emissiveTexture);
  40323. }
  40324. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40325. effect.setTexture("lightmapSampler", this._lightmapTexture);
  40326. }
  40327. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40328. effect.setTexture("specularSampler", this._specularTexture);
  40329. }
  40330. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40331. effect.setTexture("bumpSampler", this._bumpTexture);
  40332. }
  40333. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40334. var depth = 1.0;
  40335. if (this._refractionTexture.isCube) {
  40336. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  40337. }
  40338. else {
  40339. effect.setTexture("refraction2DSampler", this._refractionTexture);
  40340. }
  40341. }
  40342. }
  40343. // Clip plane
  40344. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  40345. // Colors
  40346. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  40347. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  40348. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40349. }
  40350. if (mustRebind || !this.isFrozen) {
  40351. // Lights
  40352. if (scene.lightsEnabled && !this._disableLighting) {
  40353. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  40354. }
  40355. // View
  40356. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  40357. this.bindView(effect);
  40358. }
  40359. // Fog
  40360. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  40361. // Morph targets
  40362. if (defines.NUM_MORPH_INFLUENCERS) {
  40363. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  40364. }
  40365. // Log. depth
  40366. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  40367. // image processing
  40368. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  40369. this._imageProcessingConfiguration.bind(this._activeEffect);
  40370. }
  40371. }
  40372. this._uniformBuffer.update();
  40373. this._afterBind(mesh, this._activeEffect);
  40374. };
  40375. StandardMaterial.prototype.getAnimatables = function () {
  40376. var results = [];
  40377. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  40378. results.push(this._diffuseTexture);
  40379. }
  40380. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40381. results.push(this._ambientTexture);
  40382. }
  40383. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40384. results.push(this._opacityTexture);
  40385. }
  40386. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40387. results.push(this._reflectionTexture);
  40388. }
  40389. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40390. results.push(this._emissiveTexture);
  40391. }
  40392. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40393. results.push(this._specularTexture);
  40394. }
  40395. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40396. results.push(this._bumpTexture);
  40397. }
  40398. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40399. results.push(this._lightmapTexture);
  40400. }
  40401. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40402. results.push(this._refractionTexture);
  40403. }
  40404. return results;
  40405. };
  40406. StandardMaterial.prototype.getActiveTextures = function () {
  40407. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40408. if (this._diffuseTexture) {
  40409. activeTextures.push(this._diffuseTexture);
  40410. }
  40411. if (this._ambientTexture) {
  40412. activeTextures.push(this._ambientTexture);
  40413. }
  40414. if (this._opacityTexture) {
  40415. activeTextures.push(this._opacityTexture);
  40416. }
  40417. if (this._reflectionTexture) {
  40418. activeTextures.push(this._reflectionTexture);
  40419. }
  40420. if (this._emissiveTexture) {
  40421. activeTextures.push(this._emissiveTexture);
  40422. }
  40423. if (this._specularTexture) {
  40424. activeTextures.push(this._specularTexture);
  40425. }
  40426. if (this._bumpTexture) {
  40427. activeTextures.push(this._bumpTexture);
  40428. }
  40429. if (this._lightmapTexture) {
  40430. activeTextures.push(this._lightmapTexture);
  40431. }
  40432. if (this._refractionTexture) {
  40433. activeTextures.push(this._refractionTexture);
  40434. }
  40435. return activeTextures;
  40436. };
  40437. StandardMaterial.prototype.hasTexture = function (texture) {
  40438. if (_super.prototype.hasTexture.call(this, texture)) {
  40439. return true;
  40440. }
  40441. if (this._diffuseTexture === texture) {
  40442. return true;
  40443. }
  40444. if (this._ambientTexture === texture) {
  40445. return true;
  40446. }
  40447. if (this._opacityTexture === texture) {
  40448. return true;
  40449. }
  40450. if (this._reflectionTexture === texture) {
  40451. return true;
  40452. }
  40453. if (this._emissiveTexture === texture) {
  40454. return true;
  40455. }
  40456. if (this._specularTexture === texture) {
  40457. return true;
  40458. }
  40459. if (this._bumpTexture === texture) {
  40460. return true;
  40461. }
  40462. if (this._lightmapTexture === texture) {
  40463. return true;
  40464. }
  40465. if (this._refractionTexture === texture) {
  40466. return true;
  40467. }
  40468. return false;
  40469. };
  40470. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40471. if (forceDisposeTextures) {
  40472. if (this._diffuseTexture) {
  40473. this._diffuseTexture.dispose();
  40474. }
  40475. if (this._ambientTexture) {
  40476. this._ambientTexture.dispose();
  40477. }
  40478. if (this._opacityTexture) {
  40479. this._opacityTexture.dispose();
  40480. }
  40481. if (this._reflectionTexture) {
  40482. this._reflectionTexture.dispose();
  40483. }
  40484. if (this._emissiveTexture) {
  40485. this._emissiveTexture.dispose();
  40486. }
  40487. if (this._specularTexture) {
  40488. this._specularTexture.dispose();
  40489. }
  40490. if (this._bumpTexture) {
  40491. this._bumpTexture.dispose();
  40492. }
  40493. if (this._lightmapTexture) {
  40494. this._lightmapTexture.dispose();
  40495. }
  40496. if (this._refractionTexture) {
  40497. this._refractionTexture.dispose();
  40498. }
  40499. }
  40500. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40501. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40502. }
  40503. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40504. };
  40505. StandardMaterial.prototype.clone = function (name) {
  40506. var _this = this;
  40507. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40508. result.name = name;
  40509. result.id = name;
  40510. return result;
  40511. };
  40512. StandardMaterial.prototype.serialize = function () {
  40513. return BABYLON.SerializationHelper.Serialize(this);
  40514. };
  40515. // Statics
  40516. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40517. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40518. };
  40519. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40520. get: function () {
  40521. return StandardMaterial._DiffuseTextureEnabled;
  40522. },
  40523. set: function (value) {
  40524. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40525. return;
  40526. }
  40527. StandardMaterial._DiffuseTextureEnabled = value;
  40528. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40529. },
  40530. enumerable: true,
  40531. configurable: true
  40532. });
  40533. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40534. get: function () {
  40535. return StandardMaterial._AmbientTextureEnabled;
  40536. },
  40537. set: function (value) {
  40538. if (StandardMaterial._AmbientTextureEnabled === value) {
  40539. return;
  40540. }
  40541. StandardMaterial._AmbientTextureEnabled = value;
  40542. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40543. },
  40544. enumerable: true,
  40545. configurable: true
  40546. });
  40547. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40548. get: function () {
  40549. return StandardMaterial._OpacityTextureEnabled;
  40550. },
  40551. set: function (value) {
  40552. if (StandardMaterial._OpacityTextureEnabled === value) {
  40553. return;
  40554. }
  40555. StandardMaterial._OpacityTextureEnabled = value;
  40556. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40557. },
  40558. enumerable: true,
  40559. configurable: true
  40560. });
  40561. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40562. get: function () {
  40563. return StandardMaterial._ReflectionTextureEnabled;
  40564. },
  40565. set: function (value) {
  40566. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40567. return;
  40568. }
  40569. StandardMaterial._ReflectionTextureEnabled = value;
  40570. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40571. },
  40572. enumerable: true,
  40573. configurable: true
  40574. });
  40575. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40576. get: function () {
  40577. return StandardMaterial._EmissiveTextureEnabled;
  40578. },
  40579. set: function (value) {
  40580. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40581. return;
  40582. }
  40583. StandardMaterial._EmissiveTextureEnabled = value;
  40584. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40585. },
  40586. enumerable: true,
  40587. configurable: true
  40588. });
  40589. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40590. get: function () {
  40591. return StandardMaterial._SpecularTextureEnabled;
  40592. },
  40593. set: function (value) {
  40594. if (StandardMaterial._SpecularTextureEnabled === value) {
  40595. return;
  40596. }
  40597. StandardMaterial._SpecularTextureEnabled = value;
  40598. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40599. },
  40600. enumerable: true,
  40601. configurable: true
  40602. });
  40603. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40604. get: function () {
  40605. return StandardMaterial._BumpTextureEnabled;
  40606. },
  40607. set: function (value) {
  40608. if (StandardMaterial._BumpTextureEnabled === value) {
  40609. return;
  40610. }
  40611. StandardMaterial._BumpTextureEnabled = value;
  40612. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40613. },
  40614. enumerable: true,
  40615. configurable: true
  40616. });
  40617. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40618. get: function () {
  40619. return StandardMaterial._LightmapTextureEnabled;
  40620. },
  40621. set: function (value) {
  40622. if (StandardMaterial._LightmapTextureEnabled === value) {
  40623. return;
  40624. }
  40625. StandardMaterial._LightmapTextureEnabled = value;
  40626. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40627. },
  40628. enumerable: true,
  40629. configurable: true
  40630. });
  40631. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40632. get: function () {
  40633. return StandardMaterial._RefractionTextureEnabled;
  40634. },
  40635. set: function (value) {
  40636. if (StandardMaterial._RefractionTextureEnabled === value) {
  40637. return;
  40638. }
  40639. StandardMaterial._RefractionTextureEnabled = value;
  40640. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40641. },
  40642. enumerable: true,
  40643. configurable: true
  40644. });
  40645. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40646. get: function () {
  40647. return StandardMaterial._ColorGradingTextureEnabled;
  40648. },
  40649. set: function (value) {
  40650. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40651. return;
  40652. }
  40653. StandardMaterial._ColorGradingTextureEnabled = value;
  40654. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40655. },
  40656. enumerable: true,
  40657. configurable: true
  40658. });
  40659. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40660. get: function () {
  40661. return StandardMaterial._FresnelEnabled;
  40662. },
  40663. set: function (value) {
  40664. if (StandardMaterial._FresnelEnabled === value) {
  40665. return;
  40666. }
  40667. StandardMaterial._FresnelEnabled = value;
  40668. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40669. },
  40670. enumerable: true,
  40671. configurable: true
  40672. });
  40673. // Flags used to enable or disable a type of texture for all Standard Materials
  40674. StandardMaterial._DiffuseTextureEnabled = true;
  40675. StandardMaterial._AmbientTextureEnabled = true;
  40676. StandardMaterial._OpacityTextureEnabled = true;
  40677. StandardMaterial._ReflectionTextureEnabled = true;
  40678. StandardMaterial._EmissiveTextureEnabled = true;
  40679. StandardMaterial._SpecularTextureEnabled = true;
  40680. StandardMaterial._BumpTextureEnabled = true;
  40681. StandardMaterial._LightmapTextureEnabled = true;
  40682. StandardMaterial._RefractionTextureEnabled = true;
  40683. StandardMaterial._ColorGradingTextureEnabled = true;
  40684. StandardMaterial._FresnelEnabled = true;
  40685. __decorate([
  40686. BABYLON.serializeAsTexture("diffuseTexture")
  40687. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40688. __decorate([
  40689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40690. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40691. __decorate([
  40692. BABYLON.serializeAsTexture("ambientTexture")
  40693. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40694. __decorate([
  40695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40696. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40697. __decorate([
  40698. BABYLON.serializeAsTexture("opacityTexture")
  40699. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40700. __decorate([
  40701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40702. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40703. __decorate([
  40704. BABYLON.serializeAsTexture("reflectionTexture")
  40705. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40706. __decorate([
  40707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40708. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40709. __decorate([
  40710. BABYLON.serializeAsTexture("emissiveTexture")
  40711. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40712. __decorate([
  40713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40714. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40715. __decorate([
  40716. BABYLON.serializeAsTexture("specularTexture")
  40717. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40718. __decorate([
  40719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40720. ], StandardMaterial.prototype, "specularTexture", void 0);
  40721. __decorate([
  40722. BABYLON.serializeAsTexture("bumpTexture")
  40723. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40724. __decorate([
  40725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40726. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40727. __decorate([
  40728. BABYLON.serializeAsTexture("lightmapTexture")
  40729. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40730. __decorate([
  40731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40732. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40733. __decorate([
  40734. BABYLON.serializeAsTexture("refractionTexture")
  40735. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40736. __decorate([
  40737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40738. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40739. __decorate([
  40740. BABYLON.serializeAsColor3("ambient")
  40741. ], StandardMaterial.prototype, "ambientColor", void 0);
  40742. __decorate([
  40743. BABYLON.serializeAsColor3("diffuse")
  40744. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40745. __decorate([
  40746. BABYLON.serializeAsColor3("specular")
  40747. ], StandardMaterial.prototype, "specularColor", void 0);
  40748. __decorate([
  40749. BABYLON.serializeAsColor3("emissive")
  40750. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40751. __decorate([
  40752. BABYLON.serialize()
  40753. ], StandardMaterial.prototype, "specularPower", void 0);
  40754. __decorate([
  40755. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40756. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40757. __decorate([
  40758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40759. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40760. __decorate([
  40761. BABYLON.serialize("useEmissiveAsIllumination")
  40762. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40763. __decorate([
  40764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40765. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40766. __decorate([
  40767. BABYLON.serialize("linkEmissiveWithDiffuse")
  40768. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40769. __decorate([
  40770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40771. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40772. __decorate([
  40773. BABYLON.serialize("useSpecularOverAlpha")
  40774. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40775. __decorate([
  40776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40777. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40778. __decorate([
  40779. BABYLON.serialize("useReflectionOverAlpha")
  40780. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40781. __decorate([
  40782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40783. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40784. __decorate([
  40785. BABYLON.serialize("disableLighting")
  40786. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40787. __decorate([
  40788. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40789. ], StandardMaterial.prototype, "disableLighting", void 0);
  40790. __decorate([
  40791. BABYLON.serialize("useObjectSpaceNormalMap")
  40792. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40793. __decorate([
  40794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40795. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40796. __decorate([
  40797. BABYLON.serialize("useParallax")
  40798. ], StandardMaterial.prototype, "_useParallax", void 0);
  40799. __decorate([
  40800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40801. ], StandardMaterial.prototype, "useParallax", void 0);
  40802. __decorate([
  40803. BABYLON.serialize("useParallaxOcclusion")
  40804. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40805. __decorate([
  40806. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40807. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40808. __decorate([
  40809. BABYLON.serialize()
  40810. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40811. __decorate([
  40812. BABYLON.serialize("roughness")
  40813. ], StandardMaterial.prototype, "_roughness", void 0);
  40814. __decorate([
  40815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40816. ], StandardMaterial.prototype, "roughness", void 0);
  40817. __decorate([
  40818. BABYLON.serialize()
  40819. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40820. __decorate([
  40821. BABYLON.serialize()
  40822. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40823. __decorate([
  40824. BABYLON.serialize("useLightmapAsShadowmap")
  40825. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40826. __decorate([
  40827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40828. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40829. __decorate([
  40830. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40831. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40832. __decorate([
  40833. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40834. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40835. __decorate([
  40836. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40837. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40838. __decorate([
  40839. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40840. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40841. __decorate([
  40842. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40843. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40844. __decorate([
  40845. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40846. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40847. __decorate([
  40848. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40849. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40850. __decorate([
  40851. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40852. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40853. __decorate([
  40854. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40855. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40856. __decorate([
  40857. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40858. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40859. __decorate([
  40860. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40861. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40862. __decorate([
  40863. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40864. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40865. __decorate([
  40866. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40867. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40868. __decorate([
  40869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40870. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40871. __decorate([
  40872. BABYLON.serialize("maxSimultaneousLights")
  40873. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40874. __decorate([
  40875. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40876. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40877. __decorate([
  40878. BABYLON.serialize("invertNormalMapX")
  40879. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40880. __decorate([
  40881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40882. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40883. __decorate([
  40884. BABYLON.serialize("invertNormalMapY")
  40885. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40886. __decorate([
  40887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40888. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40889. __decorate([
  40890. BABYLON.serialize("twoSidedLighting")
  40891. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40892. __decorate([
  40893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40894. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40895. __decorate([
  40896. BABYLON.serialize()
  40897. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40898. return StandardMaterial;
  40899. }(BABYLON.PushMaterial));
  40900. BABYLON.StandardMaterial = StandardMaterial;
  40901. })(BABYLON || (BABYLON = {}));
  40902. //# sourceMappingURL=babylon.standardMaterial.js.map
  40903. "use strict";
  40904. var BABYLON;
  40905. (function (BABYLON) {
  40906. /**
  40907. * Manages the defines for the PBR Material.
  40908. */
  40909. var PBRMaterialDefines = /** @class */ (function (_super) {
  40910. __extends(PBRMaterialDefines, _super);
  40911. /**
  40912. * Initializes the PBR Material defines.
  40913. */
  40914. function PBRMaterialDefines() {
  40915. var _this = _super.call(this) || this;
  40916. _this.PBR = true;
  40917. _this.MAINUV1 = false;
  40918. _this.MAINUV2 = false;
  40919. _this.UV1 = false;
  40920. _this.UV2 = false;
  40921. _this.ALBEDO = false;
  40922. _this.ALBEDODIRECTUV = 0;
  40923. _this.VERTEXCOLOR = false;
  40924. _this.AMBIENT = false;
  40925. _this.AMBIENTDIRECTUV = 0;
  40926. _this.AMBIENTINGRAYSCALE = false;
  40927. _this.OPACITY = false;
  40928. _this.VERTEXALPHA = false;
  40929. _this.OPACITYDIRECTUV = 0;
  40930. _this.OPACITYRGB = false;
  40931. _this.ALPHATEST = false;
  40932. _this.DEPTHPREPASS = false;
  40933. _this.ALPHABLEND = false;
  40934. _this.ALPHAFROMALBEDO = false;
  40935. _this.ALPHATESTVALUE = "0.5";
  40936. _this.SPECULAROVERALPHA = false;
  40937. _this.RADIANCEOVERALPHA = false;
  40938. _this.ALPHAFRESNEL = false;
  40939. _this.LINEARALPHAFRESNEL = false;
  40940. _this.PREMULTIPLYALPHA = false;
  40941. _this.EMISSIVE = false;
  40942. _this.EMISSIVEDIRECTUV = 0;
  40943. _this.REFLECTIVITY = false;
  40944. _this.REFLECTIVITYDIRECTUV = 0;
  40945. _this.SPECULARTERM = false;
  40946. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40947. _this.MICROSURFACEAUTOMATIC = false;
  40948. _this.LODBASEDMICROSFURACE = false;
  40949. _this.MICROSURFACEMAP = false;
  40950. _this.MICROSURFACEMAPDIRECTUV = 0;
  40951. _this.METALLICWORKFLOW = false;
  40952. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40953. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40954. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40955. _this.AOSTOREINMETALMAPRED = false;
  40956. _this.ENVIRONMENTBRDF = false;
  40957. _this.NORMAL = false;
  40958. _this.TANGENT = false;
  40959. _this.BUMP = false;
  40960. _this.BUMPDIRECTUV = 0;
  40961. _this.OBJECTSPACE_NORMALMAP = false;
  40962. _this.PARALLAX = false;
  40963. _this.PARALLAXOCCLUSION = false;
  40964. _this.NORMALXYSCALE = true;
  40965. _this.LIGHTMAP = false;
  40966. _this.LIGHTMAPDIRECTUV = 0;
  40967. _this.USELIGHTMAPASSHADOWMAP = false;
  40968. _this.GAMMALIGHTMAP = false;
  40969. _this.REFLECTION = false;
  40970. _this.REFLECTIONMAP_3D = false;
  40971. _this.REFLECTIONMAP_SPHERICAL = false;
  40972. _this.REFLECTIONMAP_PLANAR = false;
  40973. _this.REFLECTIONMAP_CUBIC = false;
  40974. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40975. _this.REFLECTIONMAP_PROJECTION = false;
  40976. _this.REFLECTIONMAP_SKYBOX = false;
  40977. _this.REFLECTIONMAP_EXPLICIT = false;
  40978. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40979. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40980. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40981. _this.INVERTCUBICMAP = false;
  40982. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40983. _this.USESPHERICALINVERTEX = false;
  40984. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40985. _this.LODINREFLECTIONALPHA = false;
  40986. _this.GAMMAREFLECTION = false;
  40987. _this.RADIANCEOCCLUSION = false;
  40988. _this.HORIZONOCCLUSION = false;
  40989. _this.REFRACTION = false;
  40990. _this.REFRACTIONMAP_3D = false;
  40991. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40992. _this.LODINREFRACTIONALPHA = false;
  40993. _this.GAMMAREFRACTION = false;
  40994. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40995. _this.INSTANCES = false;
  40996. _this.NUM_BONE_INFLUENCERS = 0;
  40997. _this.BonesPerMesh = 0;
  40998. _this.NONUNIFORMSCALING = false;
  40999. _this.MORPHTARGETS = false;
  41000. _this.MORPHTARGETS_NORMAL = false;
  41001. _this.MORPHTARGETS_TANGENT = false;
  41002. _this.NUM_MORPH_INFLUENCERS = 0;
  41003. _this.IMAGEPROCESSING = false;
  41004. _this.VIGNETTE = false;
  41005. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41006. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41007. _this.TONEMAPPING = false;
  41008. _this.CONTRAST = false;
  41009. _this.COLORCURVES = false;
  41010. _this.COLORGRADING = false;
  41011. _this.COLORGRADING3D = false;
  41012. _this.SAMPLER3DGREENDEPTH = false;
  41013. _this.SAMPLER3DBGRMAP = false;
  41014. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41015. _this.EXPOSURE = false;
  41016. _this.GRAIN = false;
  41017. _this.USEPHYSICALLIGHTFALLOFF = false;
  41018. _this.TWOSIDEDLIGHTING = false;
  41019. _this.SHADOWFLOAT = false;
  41020. _this.CLIPPLANE = false;
  41021. _this.POINTSIZE = false;
  41022. _this.FOG = false;
  41023. _this.LOGARITHMICDEPTH = false;
  41024. _this.FORCENORMALFORWARD = false;
  41025. _this.UNLIT = false;
  41026. _this.rebuild();
  41027. return _this;
  41028. }
  41029. /**
  41030. * Resets the PBR Material defines.
  41031. */
  41032. PBRMaterialDefines.prototype.reset = function () {
  41033. _super.prototype.reset.call(this);
  41034. this.ALPHATESTVALUE = "0.5";
  41035. this.PBR = true;
  41036. };
  41037. return PBRMaterialDefines;
  41038. }(BABYLON.MaterialDefines));
  41039. /**
  41040. * The Physically based material base class of BJS.
  41041. *
  41042. * This offers the main features of a standard PBR material.
  41043. * For more information, please refer to the documentation :
  41044. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41045. */
  41046. var PBRBaseMaterial = /** @class */ (function (_super) {
  41047. __extends(PBRBaseMaterial, _super);
  41048. /**
  41049. * Instantiates a new PBRMaterial instance.
  41050. *
  41051. * @param name The material name
  41052. * @param scene The scene the material will be use in.
  41053. */
  41054. function PBRBaseMaterial(name, scene) {
  41055. var _this = _super.call(this, name, scene) || this;
  41056. /**
  41057. * Intensity of the direct lights e.g. the four lights available in your scene.
  41058. * This impacts both the direct diffuse and specular highlights.
  41059. */
  41060. _this._directIntensity = 1.0;
  41061. /**
  41062. * Intensity of the emissive part of the material.
  41063. * This helps controlling the emissive effect without modifying the emissive color.
  41064. */
  41065. _this._emissiveIntensity = 1.0;
  41066. /**
  41067. * Intensity of the environment e.g. how much the environment will light the object
  41068. * either through harmonics for rough material or through the refelction for shiny ones.
  41069. */
  41070. _this._environmentIntensity = 1.0;
  41071. /**
  41072. * This is a special control allowing the reduction of the specular highlights coming from the
  41073. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41074. */
  41075. _this._specularIntensity = 1.0;
  41076. /**
  41077. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  41078. */
  41079. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  41080. /**
  41081. * Debug Control allowing disabling the bump map on this material.
  41082. */
  41083. _this._disableBumpMap = false;
  41084. /**
  41085. * AKA Occlusion Texture Intensity in other nomenclature.
  41086. */
  41087. _this._ambientTextureStrength = 1.0;
  41088. /**
  41089. * The color of a material in ambient lighting.
  41090. */
  41091. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  41092. /**
  41093. * AKA Diffuse Color in other nomenclature.
  41094. */
  41095. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  41096. /**
  41097. * AKA Specular Color in other nomenclature.
  41098. */
  41099. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41100. /**
  41101. * The color applied when light is reflected from a material.
  41102. */
  41103. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  41104. /**
  41105. * The color applied when light is emitted from a material.
  41106. */
  41107. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  41108. /**
  41109. * AKA Glossiness in other nomenclature.
  41110. */
  41111. _this._microSurface = 0.9;
  41112. /**
  41113. * source material index of refraction (IOR)' / 'destination material IOR.
  41114. */
  41115. _this._indexOfRefraction = 0.66;
  41116. /**
  41117. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41118. */
  41119. _this._invertRefractionY = false;
  41120. /**
  41121. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41122. * Materials half opaque for instance using refraction could benefit from this control.
  41123. */
  41124. _this._linkRefractionWithTransparency = false;
  41125. /**
  41126. * Specifies that the material will use the light map as a show map.
  41127. */
  41128. _this._useLightmapAsShadowmap = false;
  41129. /**
  41130. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41131. * makes the reflect vector face the model (under horizon).
  41132. */
  41133. _this._useHorizonOcclusion = true;
  41134. /**
  41135. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41136. * too much the area relying on ambient texture to define their ambient occlusion.
  41137. */
  41138. _this._useRadianceOcclusion = true;
  41139. /**
  41140. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41141. */
  41142. _this._useAlphaFromAlbedoTexture = false;
  41143. /**
  41144. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41145. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41146. */
  41147. _this._useSpecularOverAlpha = true;
  41148. /**
  41149. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41150. */
  41151. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  41152. /**
  41153. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41154. */
  41155. _this._useRoughnessFromMetallicTextureAlpha = true;
  41156. /**
  41157. * Specifies if the metallic texture contains the roughness information in its green channel.
  41158. */
  41159. _this._useRoughnessFromMetallicTextureGreen = false;
  41160. /**
  41161. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41162. */
  41163. _this._useMetallnessFromMetallicTextureBlue = false;
  41164. /**
  41165. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41166. */
  41167. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  41168. /**
  41169. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41170. */
  41171. _this._useAmbientInGrayScale = false;
  41172. /**
  41173. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41174. * The material will try to infer what glossiness each pixel should be.
  41175. */
  41176. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  41177. /**
  41178. * BJS is using an harcoded light falloff based on a manually sets up range.
  41179. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41180. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41181. */
  41182. _this._usePhysicalLightFalloff = true;
  41183. /**
  41184. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41185. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41186. */
  41187. _this._useRadianceOverAlpha = true;
  41188. /**
  41189. * Allows using an object space normal map (instead of tangent space).
  41190. */
  41191. _this._useObjectSpaceNormalMap = false;
  41192. /**
  41193. * Allows using the bump map in parallax mode.
  41194. */
  41195. _this._useParallax = false;
  41196. /**
  41197. * Allows using the bump map in parallax occlusion mode.
  41198. */
  41199. _this._useParallaxOcclusion = false;
  41200. /**
  41201. * Controls the scale bias of the parallax mode.
  41202. */
  41203. _this._parallaxScaleBias = 0.05;
  41204. /**
  41205. * If sets to true, disables all the lights affecting the material.
  41206. */
  41207. _this._disableLighting = false;
  41208. /**
  41209. * Number of Simultaneous lights allowed on the material.
  41210. */
  41211. _this._maxSimultaneousLights = 4;
  41212. /**
  41213. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  41214. */
  41215. _this._invertNormalMapX = false;
  41216. /**
  41217. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  41218. */
  41219. _this._invertNormalMapY = false;
  41220. /**
  41221. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41222. */
  41223. _this._twoSidedLighting = false;
  41224. /**
  41225. * Defines the alpha limits in alpha test mode.
  41226. */
  41227. _this._alphaCutOff = 0.4;
  41228. /**
  41229. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41230. */
  41231. _this._forceAlphaTest = false;
  41232. /**
  41233. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41234. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41235. */
  41236. _this._useAlphaFresnel = false;
  41237. /**
  41238. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41239. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41240. */
  41241. _this._useLinearAlphaFresnel = false;
  41242. /**
  41243. * The transparency mode of the material.
  41244. */
  41245. _this._transparencyMode = null;
  41246. /**
  41247. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  41248. * from cos thetav and roughness:
  41249. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  41250. */
  41251. _this._environmentBRDFTexture = null;
  41252. /**
  41253. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41254. */
  41255. _this._forceIrradianceInFragment = false;
  41256. /**
  41257. * Force normal to face away from face.
  41258. */
  41259. _this._forceNormalForward = false;
  41260. /**
  41261. * Stores the available render targets.
  41262. */
  41263. _this._renderTargets = new BABYLON.SmartArray(16);
  41264. /**
  41265. * Sets the global ambient color for the material used in lighting calculations.
  41266. */
  41267. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41268. /**
  41269. * If set to true, no lighting calculations will be applied.
  41270. */
  41271. _this._unlit = false;
  41272. // Setup the default processing configuration to the scene.
  41273. _this._attachImageProcessingConfiguration(null);
  41274. _this.getRenderTargetTextures = function () {
  41275. _this._renderTargets.reset();
  41276. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41277. _this._renderTargets.push(_this._reflectionTexture);
  41278. }
  41279. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41280. _this._renderTargets.push(_this._refractionTexture);
  41281. }
  41282. return _this._renderTargets;
  41283. };
  41284. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41285. return _this;
  41286. }
  41287. /**
  41288. * Attaches a new image processing configuration to the PBR Material.
  41289. * @param configuration
  41290. */
  41291. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41292. var _this = this;
  41293. if (configuration === this._imageProcessingConfiguration) {
  41294. return;
  41295. }
  41296. // Detaches observer.
  41297. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41298. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41299. }
  41300. // Pick the scene configuration if needed.
  41301. if (!configuration) {
  41302. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41303. }
  41304. else {
  41305. this._imageProcessingConfiguration = configuration;
  41306. }
  41307. // Attaches observer.
  41308. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41309. _this._markAllSubMeshesAsImageProcessingDirty();
  41310. });
  41311. };
  41312. /**
  41313. * Gets the name of the material class.
  41314. */
  41315. PBRBaseMaterial.prototype.getClassName = function () {
  41316. return "PBRBaseMaterial";
  41317. };
  41318. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  41319. /**
  41320. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41321. */
  41322. get: function () {
  41323. return this._useLogarithmicDepth;
  41324. },
  41325. /**
  41326. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41327. */
  41328. set: function (value) {
  41329. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41330. },
  41331. enumerable: true,
  41332. configurable: true
  41333. });
  41334. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  41335. /**
  41336. * Gets the current transparency mode.
  41337. */
  41338. get: function () {
  41339. return this._transparencyMode;
  41340. },
  41341. /**
  41342. * Sets the transparency mode of the material.
  41343. */
  41344. set: function (value) {
  41345. if (this._transparencyMode === value) {
  41346. return;
  41347. }
  41348. this._transparencyMode = value;
  41349. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  41350. this._markAllSubMeshesAsTexturesAndMiscDirty();
  41351. },
  41352. enumerable: true,
  41353. configurable: true
  41354. });
  41355. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  41356. /**
  41357. * Returns true if alpha blending should be disabled.
  41358. */
  41359. get: function () {
  41360. return (this._linkRefractionWithTransparency ||
  41361. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  41362. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41363. },
  41364. enumerable: true,
  41365. configurable: true
  41366. });
  41367. /**
  41368. * Specifies whether or not this material should be rendered in alpha blend mode.
  41369. */
  41370. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  41371. if (this._disableAlphaBlending) {
  41372. return false;
  41373. }
  41374. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  41375. };
  41376. /**
  41377. * Specifies if the mesh will require alpha blending.
  41378. * @param mesh - BJS mesh.
  41379. */
  41380. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  41381. if (this._disableAlphaBlending) {
  41382. return false;
  41383. }
  41384. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  41385. };
  41386. /**
  41387. * Specifies whether or not this material should be rendered in alpha test mode.
  41388. */
  41389. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41390. if (this._forceAlphaTest) {
  41391. return true;
  41392. }
  41393. if (this._linkRefractionWithTransparency) {
  41394. return false;
  41395. }
  41396. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41397. };
  41398. /**
  41399. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41400. */
  41401. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41402. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41403. };
  41404. /**
  41405. * Gets the texture used for the alpha test.
  41406. */
  41407. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41408. return this._albedoTexture;
  41409. };
  41410. /**
  41411. * Specifies that the submesh is ready to be used.
  41412. * @param mesh - BJS mesh.
  41413. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41414. * @param useInstances - Specifies that instances should be used.
  41415. * @returns - boolean indicating that the submesh is ready or not.
  41416. */
  41417. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41418. if (subMesh.effect && this.isFrozen) {
  41419. if (this._wasPreviouslyReady) {
  41420. return true;
  41421. }
  41422. }
  41423. if (!subMesh._materialDefines) {
  41424. subMesh._materialDefines = new PBRMaterialDefines();
  41425. }
  41426. var defines = subMesh._materialDefines;
  41427. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41428. if (defines._renderId === this.getScene().getRenderId()) {
  41429. return true;
  41430. }
  41431. }
  41432. var scene = this.getScene();
  41433. var engine = scene.getEngine();
  41434. if (defines._areTexturesDirty) {
  41435. if (scene.texturesEnabled) {
  41436. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41437. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41438. return false;
  41439. }
  41440. }
  41441. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41442. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41443. return false;
  41444. }
  41445. }
  41446. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41447. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41448. return false;
  41449. }
  41450. }
  41451. var reflectionTexture = this._getReflectionTexture();
  41452. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41453. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41454. return false;
  41455. }
  41456. }
  41457. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41458. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41459. return false;
  41460. }
  41461. }
  41462. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41463. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41464. return false;
  41465. }
  41466. }
  41467. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41468. if (this._metallicTexture) {
  41469. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41470. return false;
  41471. }
  41472. }
  41473. else if (this._reflectivityTexture) {
  41474. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41475. return false;
  41476. }
  41477. }
  41478. if (this._microSurfaceTexture) {
  41479. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41480. return false;
  41481. }
  41482. }
  41483. }
  41484. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41485. // Bump texture cannot be not blocking.
  41486. if (!this._bumpTexture.isReady()) {
  41487. return false;
  41488. }
  41489. }
  41490. var refractionTexture = this._getRefractionTexture();
  41491. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41492. if (!refractionTexture.isReadyOrNotBlocking()) {
  41493. return false;
  41494. }
  41495. }
  41496. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41497. // This is blocking.
  41498. if (!this._environmentBRDFTexture.isReady()) {
  41499. return false;
  41500. }
  41501. }
  41502. }
  41503. }
  41504. if (defines._areImageProcessingDirty) {
  41505. if (!this._imageProcessingConfiguration.isReady()) {
  41506. return false;
  41507. }
  41508. }
  41509. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41510. mesh.createNormals(true);
  41511. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  41512. }
  41513. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41514. if (effect) {
  41515. scene.resetCachedMaterial();
  41516. subMesh.setEffect(effect, defines);
  41517. this.buildUniformLayout();
  41518. }
  41519. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41520. return false;
  41521. }
  41522. defines._renderId = scene.getRenderId();
  41523. this._wasPreviouslyReady = true;
  41524. return true;
  41525. };
  41526. /**
  41527. * Specifies if the material uses metallic roughness workflow.
  41528. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41529. */
  41530. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41531. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41532. return true;
  41533. }
  41534. return false;
  41535. };
  41536. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41537. if (onCompiled === void 0) { onCompiled = null; }
  41538. if (onError === void 0) { onError = null; }
  41539. if (useInstances === void 0) { useInstances = null; }
  41540. if (useClipPlane === void 0) { useClipPlane = null; }
  41541. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41542. if (!defines.isDirty) {
  41543. return null;
  41544. }
  41545. defines.markAsProcessed();
  41546. var scene = this.getScene();
  41547. var engine = scene.getEngine();
  41548. // Fallbacks
  41549. var fallbacks = new BABYLON.EffectFallbacks();
  41550. var fallbackRank = 0;
  41551. if (defines.USESPHERICALINVERTEX) {
  41552. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41553. }
  41554. if (defines.FOG) {
  41555. fallbacks.addFallback(fallbackRank, "FOG");
  41556. }
  41557. if (defines.POINTSIZE) {
  41558. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41559. }
  41560. if (defines.LOGARITHMICDEPTH) {
  41561. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41562. }
  41563. if (defines.PARALLAX) {
  41564. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41565. }
  41566. if (defines.PARALLAXOCCLUSION) {
  41567. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41568. }
  41569. if (defines.ENVIRONMENTBRDF) {
  41570. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41571. }
  41572. if (defines.TANGENT) {
  41573. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41574. }
  41575. if (defines.BUMP) {
  41576. fallbacks.addFallback(fallbackRank++, "BUMP");
  41577. }
  41578. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41579. if (defines.SPECULARTERM) {
  41580. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41581. }
  41582. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41583. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41584. }
  41585. if (defines.LIGHTMAP) {
  41586. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41587. }
  41588. if (defines.NORMAL) {
  41589. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41590. }
  41591. if (defines.AMBIENT) {
  41592. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41593. }
  41594. if (defines.EMISSIVE) {
  41595. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41596. }
  41597. if (defines.VERTEXCOLOR) {
  41598. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41599. }
  41600. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41601. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41602. }
  41603. if (defines.MORPHTARGETS) {
  41604. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41605. }
  41606. //Attributes
  41607. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41608. if (defines.NORMAL) {
  41609. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41610. }
  41611. if (defines.TANGENT) {
  41612. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41613. }
  41614. if (defines.UV1) {
  41615. attribs.push(BABYLON.VertexBuffer.UVKind);
  41616. }
  41617. if (defines.UV2) {
  41618. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41619. }
  41620. if (defines.VERTEXCOLOR) {
  41621. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41622. }
  41623. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41624. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41625. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41626. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41627. "vFogInfos", "vFogColor", "pointSize",
  41628. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41629. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41630. "mBones",
  41631. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41632. "vLightingIntensity",
  41633. "logarithmicDepthConstant",
  41634. "vSphericalX", "vSphericalY", "vSphericalZ",
  41635. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41636. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41637. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41638. "vTangentSpaceParams"
  41639. ];
  41640. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41641. "bumpSampler", "lightmapSampler", "opacitySampler",
  41642. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41643. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41644. "microSurfaceSampler", "environmentBrdfSampler"];
  41645. var uniformBuffers = ["Material", "Scene"];
  41646. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41647. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41648. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41649. uniformsNames: uniforms,
  41650. uniformBuffersNames: uniformBuffers,
  41651. samplers: samplers,
  41652. defines: defines,
  41653. maxSimultaneousLights: this._maxSimultaneousLights
  41654. });
  41655. var join = defines.toString();
  41656. return engine.createEffect("pbr", {
  41657. attributes: attribs,
  41658. uniformsNames: uniforms,
  41659. uniformBuffersNames: uniformBuffers,
  41660. samplers: samplers,
  41661. defines: join,
  41662. fallbacks: fallbacks,
  41663. onCompiled: onCompiled,
  41664. onError: onError,
  41665. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41666. }, engine);
  41667. };
  41668. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41669. if (useInstances === void 0) { useInstances = null; }
  41670. if (useClipPlane === void 0) { useClipPlane = null; }
  41671. var scene = this.getScene();
  41672. var engine = scene.getEngine();
  41673. // Lights
  41674. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41675. defines._needNormals = true;
  41676. // Textures
  41677. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41678. if (defines._areTexturesDirty) {
  41679. defines._needUVs = false;
  41680. if (scene.texturesEnabled) {
  41681. if (scene.getEngine().getCaps().textureLOD) {
  41682. defines.LODBASEDMICROSFURACE = true;
  41683. }
  41684. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41685. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41686. }
  41687. else {
  41688. defines.ALBEDO = false;
  41689. }
  41690. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41691. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41692. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41693. }
  41694. else {
  41695. defines.AMBIENT = false;
  41696. }
  41697. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41698. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41699. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41700. }
  41701. else {
  41702. defines.OPACITY = false;
  41703. }
  41704. var reflectionTexture = this._getReflectionTexture();
  41705. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41706. defines.REFLECTION = true;
  41707. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41708. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41709. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41710. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41711. defines.INVERTCUBICMAP = true;
  41712. }
  41713. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41714. switch (reflectionTexture.coordinatesMode) {
  41715. case BABYLON.Texture.CUBIC_MODE:
  41716. case BABYLON.Texture.INVCUBIC_MODE:
  41717. defines.REFLECTIONMAP_CUBIC = true;
  41718. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41719. break;
  41720. case BABYLON.Texture.EXPLICIT_MODE:
  41721. defines.REFLECTIONMAP_EXPLICIT = true;
  41722. break;
  41723. case BABYLON.Texture.PLANAR_MODE:
  41724. defines.REFLECTIONMAP_PLANAR = true;
  41725. break;
  41726. case BABYLON.Texture.PROJECTION_MODE:
  41727. defines.REFLECTIONMAP_PROJECTION = true;
  41728. break;
  41729. case BABYLON.Texture.SKYBOX_MODE:
  41730. defines.REFLECTIONMAP_SKYBOX = true;
  41731. break;
  41732. case BABYLON.Texture.SPHERICAL_MODE:
  41733. defines.REFLECTIONMAP_SPHERICAL = true;
  41734. break;
  41735. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41736. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41737. break;
  41738. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41739. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41740. break;
  41741. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41742. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41743. break;
  41744. }
  41745. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41746. if (reflectionTexture.sphericalPolynomial) {
  41747. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41748. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41749. defines.USESPHERICALINVERTEX = false;
  41750. }
  41751. else {
  41752. defines.USESPHERICALINVERTEX = true;
  41753. }
  41754. }
  41755. }
  41756. }
  41757. else {
  41758. defines.REFLECTION = false;
  41759. defines.REFLECTIONMAP_3D = false;
  41760. defines.REFLECTIONMAP_SPHERICAL = false;
  41761. defines.REFLECTIONMAP_PLANAR = false;
  41762. defines.REFLECTIONMAP_CUBIC = false;
  41763. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41764. defines.REFLECTIONMAP_PROJECTION = false;
  41765. defines.REFLECTIONMAP_SKYBOX = false;
  41766. defines.REFLECTIONMAP_EXPLICIT = false;
  41767. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41768. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41769. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41770. defines.INVERTCUBICMAP = false;
  41771. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41772. defines.USESPHERICALINVERTEX = false;
  41773. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41774. defines.LODINREFLECTIONALPHA = false;
  41775. defines.GAMMAREFLECTION = false;
  41776. }
  41777. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41778. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41779. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41780. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  41781. }
  41782. else {
  41783. defines.LIGHTMAP = false;
  41784. }
  41785. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41786. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41787. }
  41788. else {
  41789. defines.EMISSIVE = false;
  41790. }
  41791. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41792. if (this._metallicTexture) {
  41793. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41794. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41795. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41796. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41797. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41798. }
  41799. else if (this._reflectivityTexture) {
  41800. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41801. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41802. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41803. }
  41804. else {
  41805. defines.REFLECTIVITY = false;
  41806. }
  41807. if (this._microSurfaceTexture) {
  41808. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41809. }
  41810. else {
  41811. defines.MICROSURFACEMAP = false;
  41812. }
  41813. }
  41814. else {
  41815. defines.REFLECTIVITY = false;
  41816. defines.MICROSURFACEMAP = false;
  41817. }
  41818. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41819. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41820. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41821. defines.PARALLAX = true;
  41822. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41823. }
  41824. else {
  41825. defines.PARALLAX = false;
  41826. }
  41827. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41828. }
  41829. else {
  41830. defines.BUMP = false;
  41831. }
  41832. var refractionTexture = this._getRefractionTexture();
  41833. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41834. defines.REFRACTION = true;
  41835. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41836. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41837. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41838. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41839. if (this._linkRefractionWithTransparency) {
  41840. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41841. }
  41842. }
  41843. else {
  41844. defines.REFRACTION = false;
  41845. }
  41846. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41847. defines.ENVIRONMENTBRDF = true;
  41848. }
  41849. else {
  41850. defines.ENVIRONMENTBRDF = false;
  41851. }
  41852. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41853. defines.ALPHAFROMALBEDO = true;
  41854. }
  41855. else {
  41856. defines.ALPHAFROMALBEDO = false;
  41857. }
  41858. }
  41859. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41860. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41861. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41862. if (!this.backFaceCulling && this._twoSidedLighting) {
  41863. defines.TWOSIDEDLIGHTING = true;
  41864. }
  41865. else {
  41866. defines.TWOSIDEDLIGHTING = false;
  41867. }
  41868. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  41869. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41870. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41871. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41872. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41873. }
  41874. if (defines._areImageProcessingDirty) {
  41875. this._imageProcessingConfiguration.prepareDefines(defines);
  41876. }
  41877. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41878. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41879. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41880. // Misc.
  41881. if (defines._areMiscDirty) {
  41882. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41883. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41884. }
  41885. // Values that need to be evaluated on every frame
  41886. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41887. // Attribs
  41888. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41889. };
  41890. /**
  41891. * Force shader compilation
  41892. */
  41893. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41894. var _this = this;
  41895. var localOptions = __assign({ clipPlane: false }, options);
  41896. var defines = new PBRMaterialDefines();
  41897. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41898. if (effect.isReady()) {
  41899. if (onCompiled) {
  41900. onCompiled(this);
  41901. }
  41902. }
  41903. else {
  41904. effect.onCompileObservable.add(function () {
  41905. if (onCompiled) {
  41906. onCompiled(_this);
  41907. }
  41908. });
  41909. }
  41910. };
  41911. /**
  41912. * Initializes the uniform buffer layout for the shader.
  41913. */
  41914. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41915. // Order is important !
  41916. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41917. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41918. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41919. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41920. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41921. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41922. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41923. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41924. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41925. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41926. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41927. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41928. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41929. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41930. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41931. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41932. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41933. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41934. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41935. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41936. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41937. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41938. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41939. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41940. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41941. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41942. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41943. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41944. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41945. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41946. this._uniformBuffer.addUniform("pointSize", 1);
  41947. this._uniformBuffer.create();
  41948. };
  41949. /**
  41950. * Unbinds the textures.
  41951. */
  41952. PBRBaseMaterial.prototype.unbind = function () {
  41953. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41954. this._uniformBuffer.setTexture("reflectionSampler", null);
  41955. }
  41956. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41957. this._uniformBuffer.setTexture("refractionSampler", null);
  41958. }
  41959. _super.prototype.unbind.call(this);
  41960. };
  41961. /**
  41962. * Binds the submesh data.
  41963. * @param world - The world matrix.
  41964. * @param mesh - The BJS mesh.
  41965. * @param subMesh - A submesh of the BJS mesh.
  41966. */
  41967. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41968. var scene = this.getScene();
  41969. var defines = subMesh._materialDefines;
  41970. if (!defines) {
  41971. return;
  41972. }
  41973. var effect = subMesh.effect;
  41974. if (!effect) {
  41975. return;
  41976. }
  41977. this._activeEffect = effect;
  41978. // Matrices
  41979. this.bindOnlyWorldMatrix(world);
  41980. // Normal Matrix
  41981. if (defines.OBJECTSPACE_NORMALMAP) {
  41982. world.toNormalMatrix(this._normalMatrix);
  41983. this.bindOnlyNormalMatrix(this._normalMatrix);
  41984. }
  41985. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41986. // Bones
  41987. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41988. var reflectionTexture = null;
  41989. if (mustRebind) {
  41990. this._uniformBuffer.bindToEffect(effect, "Material");
  41991. this.bindViewProjection(effect);
  41992. reflectionTexture = this._getReflectionTexture();
  41993. var refractionTexture = this._getRefractionTexture();
  41994. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41995. // Texture uniforms
  41996. if (scene.texturesEnabled) {
  41997. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41998. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41999. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  42000. }
  42001. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42002. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  42003. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42004. }
  42005. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42006. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42007. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42008. }
  42009. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42010. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  42011. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  42012. if (reflectionTexture.boundingBoxSize) {
  42013. var cubeTexture = reflectionTexture;
  42014. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42015. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42016. }
  42017. var polynomials = reflectionTexture.sphericalPolynomial;
  42018. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  42019. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  42020. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  42021. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  42022. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  42023. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  42024. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  42025. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  42026. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  42027. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  42028. }
  42029. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  42030. }
  42031. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42032. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42033. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42034. }
  42035. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42036. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42037. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42038. }
  42039. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42040. if (this._metallicTexture) {
  42041. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  42042. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  42043. }
  42044. else if (this._reflectivityTexture) {
  42045. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  42046. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  42047. }
  42048. if (this._microSurfaceTexture) {
  42049. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  42050. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  42051. }
  42052. }
  42053. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42054. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  42055. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42056. if (scene._mirroredCameraPosition) {
  42057. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42058. }
  42059. else {
  42060. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42061. }
  42062. }
  42063. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42064. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  42065. var depth = 1.0;
  42066. if (!refractionTexture.isCube) {
  42067. if (refractionTexture.depth) {
  42068. depth = refractionTexture.depth;
  42069. }
  42070. }
  42071. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  42072. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  42073. }
  42074. }
  42075. // Point size
  42076. if (this.pointsCloud) {
  42077. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42078. }
  42079. // Colors
  42080. if (defines.METALLICWORKFLOW) {
  42081. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  42082. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  42083. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  42084. }
  42085. else {
  42086. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  42087. }
  42088. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  42089. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  42090. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  42091. // Misc
  42092. this._lightingInfos.x = this._directIntensity;
  42093. this._lightingInfos.y = this._emissiveIntensity;
  42094. this._lightingInfos.z = this._environmentIntensity;
  42095. this._lightingInfos.w = this._specularIntensity;
  42096. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  42097. }
  42098. // Textures
  42099. if (scene.texturesEnabled) {
  42100. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42101. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  42102. }
  42103. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42104. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  42105. }
  42106. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42107. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  42108. }
  42109. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42110. if (defines.LODBASEDMICROSFURACE) {
  42111. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  42112. }
  42113. else {
  42114. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  42115. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  42116. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  42117. }
  42118. }
  42119. if (defines.ENVIRONMENTBRDF) {
  42120. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  42121. }
  42122. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42123. if (defines.LODBASEDMICROSFURACE) {
  42124. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  42125. }
  42126. else {
  42127. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  42128. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  42129. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  42130. }
  42131. }
  42132. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42133. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  42134. }
  42135. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42136. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  42137. }
  42138. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42139. if (this._metallicTexture) {
  42140. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  42141. }
  42142. else if (this._reflectivityTexture) {
  42143. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  42144. }
  42145. if (this._microSurfaceTexture) {
  42146. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  42147. }
  42148. }
  42149. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42150. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  42151. }
  42152. }
  42153. // Clip plane
  42154. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  42155. // Colors
  42156. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  42157. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42158. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  42159. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  42160. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42161. }
  42162. if (mustRebind || !this.isFrozen) {
  42163. // Lights
  42164. if (scene.lightsEnabled && !this._disableLighting) {
  42165. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  42166. }
  42167. // View
  42168. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  42169. this.bindView(effect);
  42170. }
  42171. // Fog
  42172. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  42173. // Morph targets
  42174. if (defines.NUM_MORPH_INFLUENCERS) {
  42175. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  42176. }
  42177. // image processing
  42178. this._imageProcessingConfiguration.bind(this._activeEffect);
  42179. // Log. depth
  42180. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  42181. }
  42182. this._uniformBuffer.update();
  42183. this._afterBind(mesh);
  42184. };
  42185. /**
  42186. * Returns the animatable textures.
  42187. * @returns - Array of animatable textures.
  42188. */
  42189. PBRBaseMaterial.prototype.getAnimatables = function () {
  42190. var results = [];
  42191. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  42192. results.push(this._albedoTexture);
  42193. }
  42194. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42195. results.push(this._ambientTexture);
  42196. }
  42197. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42198. results.push(this._opacityTexture);
  42199. }
  42200. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42201. results.push(this._reflectionTexture);
  42202. }
  42203. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42204. results.push(this._emissiveTexture);
  42205. }
  42206. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  42207. results.push(this._metallicTexture);
  42208. }
  42209. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  42210. results.push(this._reflectivityTexture);
  42211. }
  42212. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42213. results.push(this._bumpTexture);
  42214. }
  42215. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42216. results.push(this._lightmapTexture);
  42217. }
  42218. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42219. results.push(this._refractionTexture);
  42220. }
  42221. return results;
  42222. };
  42223. /**
  42224. * Returns the texture used for reflections.
  42225. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  42226. */
  42227. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  42228. if (this._reflectionTexture) {
  42229. return this._reflectionTexture;
  42230. }
  42231. return this.getScene().environmentTexture;
  42232. };
  42233. /**
  42234. * Returns the texture used for refraction or null if none is used.
  42235. * @returns - Refection texture if present. If no refraction texture and refraction
  42236. * is linked with transparency, returns environment texture. Otherwise, returns null.
  42237. */
  42238. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  42239. if (this._refractionTexture) {
  42240. return this._refractionTexture;
  42241. }
  42242. if (this._linkRefractionWithTransparency) {
  42243. return this.getScene().environmentTexture;
  42244. }
  42245. return null;
  42246. };
  42247. /**
  42248. * Disposes the resources of the material.
  42249. * @param forceDisposeEffect - Forces the disposal of effects.
  42250. * @param forceDisposeTextures - Forces the disposal of all textures.
  42251. */
  42252. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42253. if (forceDisposeTextures) {
  42254. if (this._albedoTexture) {
  42255. this._albedoTexture.dispose();
  42256. }
  42257. if (this._ambientTexture) {
  42258. this._ambientTexture.dispose();
  42259. }
  42260. if (this._opacityTexture) {
  42261. this._opacityTexture.dispose();
  42262. }
  42263. if (this._reflectionTexture) {
  42264. this._reflectionTexture.dispose();
  42265. }
  42266. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  42267. this._environmentBRDFTexture.dispose();
  42268. }
  42269. if (this._emissiveTexture) {
  42270. this._emissiveTexture.dispose();
  42271. }
  42272. if (this._metallicTexture) {
  42273. this._metallicTexture.dispose();
  42274. }
  42275. if (this._reflectivityTexture) {
  42276. this._reflectivityTexture.dispose();
  42277. }
  42278. if (this._bumpTexture) {
  42279. this._bumpTexture.dispose();
  42280. }
  42281. if (this._lightmapTexture) {
  42282. this._lightmapTexture.dispose();
  42283. }
  42284. if (this._refractionTexture) {
  42285. this._refractionTexture.dispose();
  42286. }
  42287. }
  42288. this._renderTargets.dispose();
  42289. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42290. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42291. }
  42292. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42293. };
  42294. /**
  42295. * Stores the reflectivity values based on metallic roughness workflow.
  42296. */
  42297. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  42298. __decorate([
  42299. BABYLON.serializeAsImageProcessingConfiguration()
  42300. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  42301. __decorate([
  42302. BABYLON.serialize()
  42303. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  42304. __decorate([
  42305. BABYLON.serialize()
  42306. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  42307. return PBRBaseMaterial;
  42308. }(BABYLON.PushMaterial));
  42309. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  42310. })(BABYLON || (BABYLON = {}));
  42311. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  42312. "use strict";
  42313. var BABYLON;
  42314. (function (BABYLON) {
  42315. /**
  42316. * The Physically based simple base material of BJS.
  42317. *
  42318. * This enables better naming and convention enforcements on top of the pbrMaterial.
  42319. * It is used as the base class for both the specGloss and metalRough conventions.
  42320. */
  42321. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  42322. __extends(PBRBaseSimpleMaterial, _super);
  42323. /**
  42324. * Instantiates a new PBRMaterial instance.
  42325. *
  42326. * @param name The material name
  42327. * @param scene The scene the material will be use in.
  42328. */
  42329. function PBRBaseSimpleMaterial(name, scene) {
  42330. var _this = _super.call(this, name, scene) || this;
  42331. /**
  42332. * Number of Simultaneous lights allowed on the material.
  42333. */
  42334. _this.maxSimultaneousLights = 4;
  42335. /**
  42336. * If sets to true, disables all the lights affecting the material.
  42337. */
  42338. _this.disableLighting = false;
  42339. /**
  42340. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42341. */
  42342. _this.invertNormalMapX = false;
  42343. /**
  42344. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42345. */
  42346. _this.invertNormalMapY = false;
  42347. /**
  42348. * Emissivie color used to self-illuminate the model.
  42349. */
  42350. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42351. /**
  42352. * Occlusion Channel Strenght.
  42353. */
  42354. _this.occlusionStrength = 1.0;
  42355. _this.useLightmapAsShadowmap = false;
  42356. _this._useAlphaFromAlbedoTexture = true;
  42357. _this._useAmbientInGrayScale = true;
  42358. return _this;
  42359. }
  42360. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  42361. /**
  42362. * Gets the current double sided mode.
  42363. */
  42364. get: function () {
  42365. return this._twoSidedLighting;
  42366. },
  42367. /**
  42368. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42369. */
  42370. set: function (value) {
  42371. if (this._twoSidedLighting === value) {
  42372. return;
  42373. }
  42374. this._twoSidedLighting = value;
  42375. this.backFaceCulling = !value;
  42376. this._markAllSubMeshesAsTexturesDirty();
  42377. },
  42378. enumerable: true,
  42379. configurable: true
  42380. });
  42381. /**
  42382. * Return the active textures of the material.
  42383. */
  42384. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  42385. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42386. if (this.environmentTexture) {
  42387. activeTextures.push(this.environmentTexture);
  42388. }
  42389. if (this.normalTexture) {
  42390. activeTextures.push(this.normalTexture);
  42391. }
  42392. if (this.emissiveTexture) {
  42393. activeTextures.push(this.emissiveTexture);
  42394. }
  42395. if (this.occlusionTexture) {
  42396. activeTextures.push(this.occlusionTexture);
  42397. }
  42398. if (this.lightmapTexture) {
  42399. activeTextures.push(this.lightmapTexture);
  42400. }
  42401. return activeTextures;
  42402. };
  42403. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42404. if (_super.prototype.hasTexture.call(this, texture)) {
  42405. return true;
  42406. }
  42407. if (this.lightmapTexture === texture) {
  42408. return true;
  42409. }
  42410. return false;
  42411. };
  42412. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42413. return "PBRBaseSimpleMaterial";
  42414. };
  42415. __decorate([
  42416. BABYLON.serialize(),
  42417. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42418. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42419. __decorate([
  42420. BABYLON.serialize(),
  42421. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42422. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42423. __decorate([
  42424. BABYLON.serializeAsTexture(),
  42425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42426. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42427. __decorate([
  42428. BABYLON.serialize(),
  42429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42430. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42431. __decorate([
  42432. BABYLON.serialize(),
  42433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42434. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42435. __decorate([
  42436. BABYLON.serializeAsTexture(),
  42437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42438. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42439. __decorate([
  42440. BABYLON.serializeAsColor3("emissive"),
  42441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42442. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42443. __decorate([
  42444. BABYLON.serializeAsTexture(),
  42445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42446. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42447. __decorate([
  42448. BABYLON.serialize(),
  42449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42450. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42451. __decorate([
  42452. BABYLON.serializeAsTexture(),
  42453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42454. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42455. __decorate([
  42456. BABYLON.serialize(),
  42457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42458. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42459. __decorate([
  42460. BABYLON.serialize()
  42461. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42462. __decorate([
  42463. BABYLON.serializeAsTexture(),
  42464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42465. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42466. __decorate([
  42467. BABYLON.serialize(),
  42468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42469. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42470. return PBRBaseSimpleMaterial;
  42471. }(BABYLON.PBRBaseMaterial));
  42472. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42473. })(BABYLON || (BABYLON = {}));
  42474. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42475. "use strict";
  42476. var BABYLON;
  42477. (function (BABYLON) {
  42478. /**
  42479. * The Physically based material of BJS.
  42480. *
  42481. * This offers the main features of a standard PBR material.
  42482. * For more information, please refer to the documentation :
  42483. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42484. */
  42485. var PBRMaterial = /** @class */ (function (_super) {
  42486. __extends(PBRMaterial, _super);
  42487. /**
  42488. * Instantiates a new PBRMaterial instance.
  42489. *
  42490. * @param name The material name
  42491. * @param scene The scene the material will be use in.
  42492. */
  42493. function PBRMaterial(name, scene) {
  42494. var _this = _super.call(this, name, scene) || this;
  42495. /**
  42496. * Intensity of the direct lights e.g. the four lights available in your scene.
  42497. * This impacts both the direct diffuse and specular highlights.
  42498. */
  42499. _this.directIntensity = 1.0;
  42500. /**
  42501. * Intensity of the emissive part of the material.
  42502. * This helps controlling the emissive effect without modifying the emissive color.
  42503. */
  42504. _this.emissiveIntensity = 1.0;
  42505. /**
  42506. * Intensity of the environment e.g. how much the environment will light the object
  42507. * either through harmonics for rough material or through the refelction for shiny ones.
  42508. */
  42509. _this.environmentIntensity = 1.0;
  42510. /**
  42511. * This is a special control allowing the reduction of the specular highlights coming from the
  42512. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42513. */
  42514. _this.specularIntensity = 1.0;
  42515. /**
  42516. * Debug Control allowing disabling the bump map on this material.
  42517. */
  42518. _this.disableBumpMap = false;
  42519. /**
  42520. * AKA Occlusion Texture Intensity in other nomenclature.
  42521. */
  42522. _this.ambientTextureStrength = 1.0;
  42523. /**
  42524. * The color of a material in ambient lighting.
  42525. */
  42526. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42527. /**
  42528. * AKA Diffuse Color in other nomenclature.
  42529. */
  42530. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42531. /**
  42532. * AKA Specular Color in other nomenclature.
  42533. */
  42534. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42535. /**
  42536. * The color reflected from the material.
  42537. */
  42538. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42539. /**
  42540. * The color emitted from the material.
  42541. */
  42542. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42543. /**
  42544. * AKA Glossiness in other nomenclature.
  42545. */
  42546. _this.microSurface = 1.0;
  42547. /**
  42548. * source material index of refraction (IOR)' / 'destination material IOR.
  42549. */
  42550. _this.indexOfRefraction = 0.66;
  42551. /**
  42552. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42553. */
  42554. _this.invertRefractionY = false;
  42555. /**
  42556. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42557. * Materials half opaque for instance using refraction could benefit from this control.
  42558. */
  42559. _this.linkRefractionWithTransparency = false;
  42560. _this.useLightmapAsShadowmap = false;
  42561. /**
  42562. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42563. */
  42564. _this.useAlphaFromAlbedoTexture = false;
  42565. /**
  42566. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42567. */
  42568. _this.forceAlphaTest = false;
  42569. /**
  42570. * Defines the alpha limits in alpha test mode.
  42571. */
  42572. _this.alphaCutOff = 0.4;
  42573. /**
  42574. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42575. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42576. */
  42577. _this.useSpecularOverAlpha = true;
  42578. /**
  42579. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42580. */
  42581. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42582. /**
  42583. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42584. */
  42585. _this.useRoughnessFromMetallicTextureAlpha = true;
  42586. /**
  42587. * Specifies if the metallic texture contains the roughness information in its green channel.
  42588. */
  42589. _this.useRoughnessFromMetallicTextureGreen = false;
  42590. /**
  42591. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42592. */
  42593. _this.useMetallnessFromMetallicTextureBlue = false;
  42594. /**
  42595. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42596. */
  42597. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42598. /**
  42599. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42600. */
  42601. _this.useAmbientInGrayScale = false;
  42602. /**
  42603. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42604. * The material will try to infer what glossiness each pixel should be.
  42605. */
  42606. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42607. /**
  42608. * BJS is using an harcoded light falloff based on a manually sets up range.
  42609. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42610. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42611. */
  42612. _this.usePhysicalLightFalloff = true;
  42613. /**
  42614. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42615. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42616. */
  42617. _this.useRadianceOverAlpha = true;
  42618. /**
  42619. * Allows using an object space normal map (instead of tangent space).
  42620. */
  42621. _this.useObjectSpaceNormalMap = false;
  42622. /**
  42623. * Allows using the bump map in parallax mode.
  42624. */
  42625. _this.useParallax = false;
  42626. /**
  42627. * Allows using the bump map in parallax occlusion mode.
  42628. */
  42629. _this.useParallaxOcclusion = false;
  42630. /**
  42631. * Controls the scale bias of the parallax mode.
  42632. */
  42633. _this.parallaxScaleBias = 0.05;
  42634. /**
  42635. * If sets to true, disables all the lights affecting the material.
  42636. */
  42637. _this.disableLighting = false;
  42638. /**
  42639. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42640. */
  42641. _this.forceIrradianceInFragment = false;
  42642. /**
  42643. * Number of Simultaneous lights allowed on the material.
  42644. */
  42645. _this.maxSimultaneousLights = 4;
  42646. /**
  42647. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42648. */
  42649. _this.invertNormalMapX = false;
  42650. /**
  42651. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42652. */
  42653. _this.invertNormalMapY = false;
  42654. /**
  42655. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42656. */
  42657. _this.twoSidedLighting = false;
  42658. /**
  42659. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42660. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42661. */
  42662. _this.useAlphaFresnel = false;
  42663. /**
  42664. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42665. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42666. */
  42667. _this.useLinearAlphaFresnel = false;
  42668. /**
  42669. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42670. * And/Or occlude the blended part.
  42671. */
  42672. _this.environmentBRDFTexture = null;
  42673. /**
  42674. * Force normal to face away from face.
  42675. */
  42676. _this.forceNormalForward = false;
  42677. /**
  42678. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42679. * makes the reflect vector face the model (under horizon).
  42680. */
  42681. _this.useHorizonOcclusion = true;
  42682. /**
  42683. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42684. * too much the area relying on ambient texture to define their ambient occlusion.
  42685. */
  42686. _this.useRadianceOcclusion = true;
  42687. /**
  42688. * If set to true, no lighting calculations will be applied.
  42689. */
  42690. _this.unlit = false;
  42691. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42692. return _this;
  42693. }
  42694. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42695. /**
  42696. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42697. */
  42698. get: function () {
  42699. return this._PBRMATERIAL_OPAQUE;
  42700. },
  42701. enumerable: true,
  42702. configurable: true
  42703. });
  42704. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42705. /**
  42706. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42707. */
  42708. get: function () {
  42709. return this._PBRMATERIAL_ALPHATEST;
  42710. },
  42711. enumerable: true,
  42712. configurable: true
  42713. });
  42714. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42715. /**
  42716. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42717. */
  42718. get: function () {
  42719. return this._PBRMATERIAL_ALPHABLEND;
  42720. },
  42721. enumerable: true,
  42722. configurable: true
  42723. });
  42724. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42725. /**
  42726. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42727. * They are also discarded below the alpha cutoff threshold to improve performances.
  42728. */
  42729. get: function () {
  42730. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42731. },
  42732. enumerable: true,
  42733. configurable: true
  42734. });
  42735. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42736. /**
  42737. * Gets the image processing configuration used either in this material.
  42738. */
  42739. get: function () {
  42740. return this._imageProcessingConfiguration;
  42741. },
  42742. /**
  42743. * Sets the Default image processing configuration used either in the this material.
  42744. *
  42745. * If sets to null, the scene one is in use.
  42746. */
  42747. set: function (value) {
  42748. this._attachImageProcessingConfiguration(value);
  42749. // Ensure the effect will be rebuilt.
  42750. this._markAllSubMeshesAsTexturesDirty();
  42751. },
  42752. enumerable: true,
  42753. configurable: true
  42754. });
  42755. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42756. /**
  42757. * Gets wether the color curves effect is enabled.
  42758. */
  42759. get: function () {
  42760. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42761. },
  42762. /**
  42763. * Sets wether the color curves effect is enabled.
  42764. */
  42765. set: function (value) {
  42766. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42767. },
  42768. enumerable: true,
  42769. configurable: true
  42770. });
  42771. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42772. /**
  42773. * Gets wether the color grading effect is enabled.
  42774. */
  42775. get: function () {
  42776. return this.imageProcessingConfiguration.colorGradingEnabled;
  42777. },
  42778. /**
  42779. * Gets wether the color grading effect is enabled.
  42780. */
  42781. set: function (value) {
  42782. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42783. },
  42784. enumerable: true,
  42785. configurable: true
  42786. });
  42787. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42788. /**
  42789. * Gets wether tonemapping is enabled or not.
  42790. */
  42791. get: function () {
  42792. return this._imageProcessingConfiguration.toneMappingEnabled;
  42793. },
  42794. /**
  42795. * Sets wether tonemapping is enabled or not
  42796. */
  42797. set: function (value) {
  42798. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42799. },
  42800. enumerable: true,
  42801. configurable: true
  42802. });
  42803. ;
  42804. ;
  42805. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42806. /**
  42807. * The camera exposure used on this material.
  42808. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42809. * This corresponds to a photographic exposure.
  42810. */
  42811. get: function () {
  42812. return this._imageProcessingConfiguration.exposure;
  42813. },
  42814. /**
  42815. * The camera exposure used on this material.
  42816. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42817. * This corresponds to a photographic exposure.
  42818. */
  42819. set: function (value) {
  42820. this._imageProcessingConfiguration.exposure = value;
  42821. },
  42822. enumerable: true,
  42823. configurable: true
  42824. });
  42825. ;
  42826. ;
  42827. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42828. /**
  42829. * Gets The camera contrast used on this material.
  42830. */
  42831. get: function () {
  42832. return this._imageProcessingConfiguration.contrast;
  42833. },
  42834. /**
  42835. * Sets The camera contrast used on this material.
  42836. */
  42837. set: function (value) {
  42838. this._imageProcessingConfiguration.contrast = value;
  42839. },
  42840. enumerable: true,
  42841. configurable: true
  42842. });
  42843. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42844. /**
  42845. * Gets the Color Grading 2D Lookup Texture.
  42846. */
  42847. get: function () {
  42848. return this._imageProcessingConfiguration.colorGradingTexture;
  42849. },
  42850. /**
  42851. * Sets the Color Grading 2D Lookup Texture.
  42852. */
  42853. set: function (value) {
  42854. this._imageProcessingConfiguration.colorGradingTexture = value;
  42855. },
  42856. enumerable: true,
  42857. configurable: true
  42858. });
  42859. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42860. /**
  42861. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42862. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42863. * 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;
  42864. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42865. */
  42866. get: function () {
  42867. return this._imageProcessingConfiguration.colorCurves;
  42868. },
  42869. /**
  42870. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42871. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42872. * 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;
  42873. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42874. */
  42875. set: function (value) {
  42876. this._imageProcessingConfiguration.colorCurves = value;
  42877. },
  42878. enumerable: true,
  42879. configurable: true
  42880. });
  42881. /**
  42882. * Returns the name of this material class.
  42883. */
  42884. PBRMaterial.prototype.getClassName = function () {
  42885. return "PBRMaterial";
  42886. };
  42887. /**
  42888. * Returns an array of the actively used textures.
  42889. * @returns - Array of BaseTextures
  42890. */
  42891. PBRMaterial.prototype.getActiveTextures = function () {
  42892. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42893. if (this._albedoTexture) {
  42894. activeTextures.push(this._albedoTexture);
  42895. }
  42896. if (this._ambientTexture) {
  42897. activeTextures.push(this._ambientTexture);
  42898. }
  42899. if (this._opacityTexture) {
  42900. activeTextures.push(this._opacityTexture);
  42901. }
  42902. if (this._reflectionTexture) {
  42903. activeTextures.push(this._reflectionTexture);
  42904. }
  42905. if (this._emissiveTexture) {
  42906. activeTextures.push(this._emissiveTexture);
  42907. }
  42908. if (this._reflectivityTexture) {
  42909. activeTextures.push(this._reflectivityTexture);
  42910. }
  42911. if (this._metallicTexture) {
  42912. activeTextures.push(this._metallicTexture);
  42913. }
  42914. if (this._microSurfaceTexture) {
  42915. activeTextures.push(this._microSurfaceTexture);
  42916. }
  42917. if (this._bumpTexture) {
  42918. activeTextures.push(this._bumpTexture);
  42919. }
  42920. if (this._lightmapTexture) {
  42921. activeTextures.push(this._lightmapTexture);
  42922. }
  42923. if (this._refractionTexture) {
  42924. activeTextures.push(this._refractionTexture);
  42925. }
  42926. return activeTextures;
  42927. };
  42928. /**
  42929. * Checks to see if a texture is used in the material.
  42930. * @param texture - Base texture to use.
  42931. * @returns - Boolean specifying if a texture is used in the material.
  42932. */
  42933. PBRMaterial.prototype.hasTexture = function (texture) {
  42934. if (_super.prototype.hasTexture.call(this, texture)) {
  42935. return true;
  42936. }
  42937. if (this._albedoTexture === texture) {
  42938. return true;
  42939. }
  42940. if (this._ambientTexture === texture) {
  42941. return true;
  42942. }
  42943. if (this._opacityTexture === texture) {
  42944. return true;
  42945. }
  42946. if (this._reflectionTexture === texture) {
  42947. return true;
  42948. }
  42949. if (this._reflectivityTexture === texture) {
  42950. return true;
  42951. }
  42952. if (this._metallicTexture === texture) {
  42953. return true;
  42954. }
  42955. if (this._microSurfaceTexture === texture) {
  42956. return true;
  42957. }
  42958. if (this._bumpTexture === texture) {
  42959. return true;
  42960. }
  42961. if (this._lightmapTexture === texture) {
  42962. return true;
  42963. }
  42964. if (this._refractionTexture === texture) {
  42965. return true;
  42966. }
  42967. return false;
  42968. };
  42969. /**
  42970. * Makes a duplicate of the current material.
  42971. * @param name - name to use for the new material.
  42972. */
  42973. PBRMaterial.prototype.clone = function (name) {
  42974. var _this = this;
  42975. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42976. clone.id = name;
  42977. clone.name = name;
  42978. return clone;
  42979. };
  42980. /**
  42981. * Serializes this PBR Material.
  42982. * @returns - An object with the serialized material.
  42983. */
  42984. PBRMaterial.prototype.serialize = function () {
  42985. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42986. serializationObject.customType = "BABYLON.PBRMaterial";
  42987. return serializationObject;
  42988. };
  42989. // Statics
  42990. /**
  42991. * Parses a PBR Material from a serialized object.
  42992. * @param source - Serialized object.
  42993. * @param scene - BJS scene instance.
  42994. * @param rootUrl - url for the scene object
  42995. * @returns - PBRMaterial
  42996. */
  42997. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42998. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42999. };
  43000. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  43001. /**
  43002. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  43003. */
  43004. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  43005. /**
  43006. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  43007. */
  43008. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  43009. /**
  43010. * 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.
  43011. * They are also discarded below the alpha cutoff threshold to improve performances.
  43012. */
  43013. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  43014. __decorate([
  43015. BABYLON.serialize(),
  43016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43017. ], PBRMaterial.prototype, "directIntensity", void 0);
  43018. __decorate([
  43019. BABYLON.serialize(),
  43020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43021. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  43022. __decorate([
  43023. BABYLON.serialize(),
  43024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43025. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  43026. __decorate([
  43027. BABYLON.serialize(),
  43028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43029. ], PBRMaterial.prototype, "specularIntensity", void 0);
  43030. __decorate([
  43031. BABYLON.serialize(),
  43032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43033. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  43034. __decorate([
  43035. BABYLON.serializeAsTexture(),
  43036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43037. ], PBRMaterial.prototype, "albedoTexture", void 0);
  43038. __decorate([
  43039. BABYLON.serializeAsTexture(),
  43040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43041. ], PBRMaterial.prototype, "ambientTexture", void 0);
  43042. __decorate([
  43043. BABYLON.serialize(),
  43044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43045. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  43046. __decorate([
  43047. BABYLON.serializeAsTexture(),
  43048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43049. ], PBRMaterial.prototype, "opacityTexture", void 0);
  43050. __decorate([
  43051. BABYLON.serializeAsTexture(),
  43052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43053. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  43054. __decorate([
  43055. BABYLON.serializeAsTexture(),
  43056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43057. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  43058. __decorate([
  43059. BABYLON.serializeAsTexture(),
  43060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43061. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  43062. __decorate([
  43063. BABYLON.serializeAsTexture(),
  43064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43065. ], PBRMaterial.prototype, "metallicTexture", void 0);
  43066. __decorate([
  43067. BABYLON.serialize(),
  43068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43069. ], PBRMaterial.prototype, "metallic", void 0);
  43070. __decorate([
  43071. BABYLON.serialize(),
  43072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43073. ], PBRMaterial.prototype, "roughness", void 0);
  43074. __decorate([
  43075. BABYLON.serializeAsTexture(),
  43076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43077. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  43078. __decorate([
  43079. BABYLON.serializeAsTexture(),
  43080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43081. ], PBRMaterial.prototype, "bumpTexture", void 0);
  43082. __decorate([
  43083. BABYLON.serializeAsTexture(),
  43084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  43085. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  43086. __decorate([
  43087. BABYLON.serializeAsTexture(),
  43088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43089. ], PBRMaterial.prototype, "refractionTexture", void 0);
  43090. __decorate([
  43091. BABYLON.serializeAsColor3("ambient"),
  43092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43093. ], PBRMaterial.prototype, "ambientColor", void 0);
  43094. __decorate([
  43095. BABYLON.serializeAsColor3("albedo"),
  43096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43097. ], PBRMaterial.prototype, "albedoColor", void 0);
  43098. __decorate([
  43099. BABYLON.serializeAsColor3("reflectivity"),
  43100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43101. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  43102. __decorate([
  43103. BABYLON.serializeAsColor3("reflection"),
  43104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43105. ], PBRMaterial.prototype, "reflectionColor", void 0);
  43106. __decorate([
  43107. BABYLON.serializeAsColor3("emissive"),
  43108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43109. ], PBRMaterial.prototype, "emissiveColor", void 0);
  43110. __decorate([
  43111. BABYLON.serialize(),
  43112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43113. ], PBRMaterial.prototype, "microSurface", void 0);
  43114. __decorate([
  43115. BABYLON.serialize(),
  43116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43117. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  43118. __decorate([
  43119. BABYLON.serialize(),
  43120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43121. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  43122. __decorate([
  43123. BABYLON.serialize(),
  43124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43125. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  43126. __decorate([
  43127. BABYLON.serialize(),
  43128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43129. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43130. __decorate([
  43131. BABYLON.serialize(),
  43132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43133. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  43134. __decorate([
  43135. BABYLON.serialize(),
  43136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43137. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  43138. __decorate([
  43139. BABYLON.serialize(),
  43140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43141. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  43142. __decorate([
  43143. BABYLON.serialize(),
  43144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43145. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  43146. __decorate([
  43147. BABYLON.serialize(),
  43148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43149. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  43150. __decorate([
  43151. BABYLON.serialize(),
  43152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43153. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  43154. __decorate([
  43155. BABYLON.serialize(),
  43156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43157. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  43158. __decorate([
  43159. BABYLON.serialize(),
  43160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43161. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  43162. __decorate([
  43163. BABYLON.serialize(),
  43164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43165. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  43166. __decorate([
  43167. BABYLON.serialize(),
  43168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43169. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  43170. __decorate([
  43171. BABYLON.serialize(),
  43172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43173. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  43174. __decorate([
  43175. BABYLON.serialize(),
  43176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43177. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  43178. __decorate([
  43179. BABYLON.serialize(),
  43180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43181. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  43182. __decorate([
  43183. BABYLON.serialize(),
  43184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43185. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43186. __decorate([
  43187. BABYLON.serialize(),
  43188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43189. ], PBRMaterial.prototype, "useParallax", void 0);
  43190. __decorate([
  43191. BABYLON.serialize(),
  43192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43193. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  43194. __decorate([
  43195. BABYLON.serialize(),
  43196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43197. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  43198. __decorate([
  43199. BABYLON.serialize(),
  43200. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43201. ], PBRMaterial.prototype, "disableLighting", void 0);
  43202. __decorate([
  43203. BABYLON.serialize(),
  43204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43205. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  43206. __decorate([
  43207. BABYLON.serialize(),
  43208. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43209. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  43210. __decorate([
  43211. BABYLON.serialize(),
  43212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43213. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  43214. __decorate([
  43215. BABYLON.serialize(),
  43216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43217. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  43218. __decorate([
  43219. BABYLON.serialize(),
  43220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43221. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  43222. __decorate([
  43223. BABYLON.serialize(),
  43224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43225. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  43226. __decorate([
  43227. BABYLON.serialize(),
  43228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43229. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  43230. __decorate([
  43231. BABYLON.serializeAsTexture(),
  43232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43233. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  43234. __decorate([
  43235. BABYLON.serialize(),
  43236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43237. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  43238. __decorate([
  43239. BABYLON.serialize(),
  43240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43241. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  43242. __decorate([
  43243. BABYLON.serialize(),
  43244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43245. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  43246. __decorate([
  43247. BABYLON.serialize(),
  43248. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43249. ], PBRMaterial.prototype, "unlit", void 0);
  43250. return PBRMaterial;
  43251. }(BABYLON.PBRBaseMaterial));
  43252. BABYLON.PBRMaterial = PBRMaterial;
  43253. })(BABYLON || (BABYLON = {}));
  43254. //# sourceMappingURL=babylon.pbrMaterial.js.map
  43255. "use strict";
  43256. var BABYLON;
  43257. (function (BABYLON) {
  43258. /**
  43259. * The PBR material of BJS following the metal roughness convention.
  43260. *
  43261. * This fits to the PBR convention in the GLTF definition:
  43262. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  43263. */
  43264. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  43265. __extends(PBRMetallicRoughnessMaterial, _super);
  43266. /**
  43267. * Instantiates a new PBRMetalRoughnessMaterial instance.
  43268. *
  43269. * @param name The material name
  43270. * @param scene The scene the material will be use in.
  43271. */
  43272. function PBRMetallicRoughnessMaterial(name, scene) {
  43273. var _this = _super.call(this, name, scene) || this;
  43274. _this._useRoughnessFromMetallicTextureAlpha = false;
  43275. _this._useRoughnessFromMetallicTextureGreen = true;
  43276. _this._useMetallnessFromMetallicTextureBlue = true;
  43277. _this.metallic = 1.0;
  43278. _this.roughness = 1.0;
  43279. return _this;
  43280. }
  43281. /**
  43282. * Return the currrent class name of the material.
  43283. */
  43284. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  43285. return "PBRMetallicRoughnessMaterial";
  43286. };
  43287. /**
  43288. * Return the active textures of the material.
  43289. */
  43290. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  43291. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43292. if (this.baseTexture) {
  43293. activeTextures.push(this.baseTexture);
  43294. }
  43295. if (this.metallicRoughnessTexture) {
  43296. activeTextures.push(this.metallicRoughnessTexture);
  43297. }
  43298. return activeTextures;
  43299. };
  43300. /**
  43301. * Checks to see if a texture is used in the material.
  43302. * @param texture - Base texture to use.
  43303. * @returns - Boolean specifying if a texture is used in the material.
  43304. */
  43305. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  43306. if (_super.prototype.hasTexture.call(this, texture)) {
  43307. return true;
  43308. }
  43309. if (this.baseTexture === texture) {
  43310. return true;
  43311. }
  43312. if (this.metallicRoughnessTexture === texture) {
  43313. return true;
  43314. }
  43315. return false;
  43316. };
  43317. /**
  43318. * Makes a duplicate of the current material.
  43319. * @param name - name to use for the new material.
  43320. */
  43321. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  43322. var _this = this;
  43323. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  43324. clone.id = name;
  43325. clone.name = name;
  43326. return clone;
  43327. };
  43328. /**
  43329. * Serialize the material to a parsable JSON object.
  43330. */
  43331. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  43332. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43333. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  43334. return serializationObject;
  43335. };
  43336. /**
  43337. * Parses a JSON object correponding to the serialize function.
  43338. */
  43339. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  43340. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  43341. };
  43342. __decorate([
  43343. BABYLON.serializeAsColor3(),
  43344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43345. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  43346. __decorate([
  43347. BABYLON.serializeAsTexture(),
  43348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43349. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  43350. __decorate([
  43351. BABYLON.serialize(),
  43352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43353. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  43354. __decorate([
  43355. BABYLON.serialize(),
  43356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43357. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  43358. __decorate([
  43359. BABYLON.serializeAsTexture(),
  43360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  43361. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  43362. return PBRMetallicRoughnessMaterial;
  43363. }(BABYLON.PBRBaseSimpleMaterial));
  43364. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  43365. })(BABYLON || (BABYLON = {}));
  43366. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  43367. "use strict";
  43368. var BABYLON;
  43369. (function (BABYLON) {
  43370. /**
  43371. * The PBR material of BJS following the specular glossiness convention.
  43372. *
  43373. * This fits to the PBR convention in the GLTF definition:
  43374. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  43375. */
  43376. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  43377. __extends(PBRSpecularGlossinessMaterial, _super);
  43378. /**
  43379. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  43380. *
  43381. * @param name The material name
  43382. * @param scene The scene the material will be use in.
  43383. */
  43384. function PBRSpecularGlossinessMaterial(name, scene) {
  43385. var _this = _super.call(this, name, scene) || this;
  43386. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  43387. return _this;
  43388. }
  43389. /**
  43390. * Return the currrent class name of the material.
  43391. */
  43392. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  43393. return "PBRSpecularGlossinessMaterial";
  43394. };
  43395. /**
  43396. * Return the active textures of the material.
  43397. */
  43398. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43399. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43400. if (this.diffuseTexture) {
  43401. activeTextures.push(this.diffuseTexture);
  43402. }
  43403. if (this.specularGlossinessTexture) {
  43404. activeTextures.push(this.specularGlossinessTexture);
  43405. }
  43406. return activeTextures;
  43407. };
  43408. /**
  43409. * Checks to see if a texture is used in the material.
  43410. * @param texture - Base texture to use.
  43411. * @returns - Boolean specifying if a texture is used in the material.
  43412. */
  43413. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43414. if (_super.prototype.hasTexture.call(this, texture)) {
  43415. return true;
  43416. }
  43417. if (this.diffuseTexture === texture) {
  43418. return true;
  43419. }
  43420. if (this.specularGlossinessTexture === texture) {
  43421. return true;
  43422. }
  43423. return false;
  43424. };
  43425. /**
  43426. * Makes a duplicate of the current material.
  43427. * @param name - name to use for the new material.
  43428. */
  43429. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43430. var _this = this;
  43431. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43432. clone.id = name;
  43433. clone.name = name;
  43434. return clone;
  43435. };
  43436. /**
  43437. * Serialize the material to a parsable JSON object.
  43438. */
  43439. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43440. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43441. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43442. return serializationObject;
  43443. };
  43444. /**
  43445. * Parses a JSON object correponding to the serialize function.
  43446. */
  43447. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43448. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43449. };
  43450. __decorate([
  43451. BABYLON.serializeAsColor3("diffuse"),
  43452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43453. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43454. __decorate([
  43455. BABYLON.serializeAsTexture(),
  43456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43457. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43458. __decorate([
  43459. BABYLON.serializeAsColor3("specular"),
  43460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43461. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43462. __decorate([
  43463. BABYLON.serialize(),
  43464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43465. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43466. __decorate([
  43467. BABYLON.serializeAsTexture(),
  43468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43469. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43470. return PBRSpecularGlossinessMaterial;
  43471. }(BABYLON.PBRBaseSimpleMaterial));
  43472. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43473. })(BABYLON || (BABYLON = {}));
  43474. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43475. "use strict";
  43476. var BABYLON;
  43477. (function (BABYLON) {
  43478. BABYLON.CameraInputTypes = {};
  43479. var CameraInputsManager = /** @class */ (function () {
  43480. function CameraInputsManager(camera) {
  43481. this.attached = {};
  43482. this.camera = camera;
  43483. this.checkInputs = function () { };
  43484. }
  43485. /**
  43486. * Add an input method to a camera.
  43487. * builtin inputs example: camera.inputs.addGamepad();
  43488. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43489. * @param input camera input method
  43490. */
  43491. CameraInputsManager.prototype.add = function (input) {
  43492. var type = input.getSimpleName();
  43493. if (this.attached[type]) {
  43494. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43495. return;
  43496. }
  43497. this.attached[type] = input;
  43498. input.camera = this.camera;
  43499. //for checkInputs, we are dynamically creating a function
  43500. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43501. if (input.checkInputs) {
  43502. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43503. }
  43504. if (this.attachedElement) {
  43505. input.attachControl(this.attachedElement);
  43506. }
  43507. };
  43508. /**
  43509. * Remove a specific input method from a camera
  43510. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43511. * @param inputToRemove camera input method
  43512. */
  43513. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43514. for (var cam in this.attached) {
  43515. var input = this.attached[cam];
  43516. if (input === inputToRemove) {
  43517. input.detachControl(this.attachedElement);
  43518. input.camera = null;
  43519. delete this.attached[cam];
  43520. this.rebuildInputCheck();
  43521. }
  43522. }
  43523. };
  43524. CameraInputsManager.prototype.removeByType = function (inputType) {
  43525. for (var cam in this.attached) {
  43526. var input = this.attached[cam];
  43527. if (input.getClassName() === inputType) {
  43528. input.detachControl(this.attachedElement);
  43529. input.camera = null;
  43530. delete this.attached[cam];
  43531. this.rebuildInputCheck();
  43532. }
  43533. }
  43534. };
  43535. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43536. var current = this.checkInputs;
  43537. return function () {
  43538. current();
  43539. fn();
  43540. };
  43541. };
  43542. CameraInputsManager.prototype.attachInput = function (input) {
  43543. if (this.attachedElement) {
  43544. input.attachControl(this.attachedElement, this.noPreventDefault);
  43545. }
  43546. };
  43547. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43548. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43549. if (this.attachedElement) {
  43550. return;
  43551. }
  43552. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43553. this.attachedElement = element;
  43554. this.noPreventDefault = noPreventDefault;
  43555. for (var cam in this.attached) {
  43556. this.attached[cam].attachControl(element, noPreventDefault);
  43557. }
  43558. };
  43559. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43560. if (disconnect === void 0) { disconnect = false; }
  43561. if (this.attachedElement !== element) {
  43562. return;
  43563. }
  43564. for (var cam in this.attached) {
  43565. this.attached[cam].detachControl(element);
  43566. if (disconnect) {
  43567. this.attached[cam].camera = null;
  43568. }
  43569. }
  43570. this.attachedElement = null;
  43571. };
  43572. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43573. this.checkInputs = function () { };
  43574. for (var cam in this.attached) {
  43575. var input = this.attached[cam];
  43576. if (input.checkInputs) {
  43577. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43578. }
  43579. }
  43580. };
  43581. /**
  43582. * Remove all attached input methods from a camera
  43583. */
  43584. CameraInputsManager.prototype.clear = function () {
  43585. if (this.attachedElement) {
  43586. this.detachElement(this.attachedElement, true);
  43587. }
  43588. this.attached = {};
  43589. this.attachedElement = null;
  43590. this.checkInputs = function () { };
  43591. };
  43592. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43593. var inputs = {};
  43594. for (var cam in this.attached) {
  43595. var input = this.attached[cam];
  43596. var res = BABYLON.SerializationHelper.Serialize(input);
  43597. inputs[input.getClassName()] = res;
  43598. }
  43599. serializedCamera.inputsmgr = inputs;
  43600. };
  43601. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43602. var parsedInputs = parsedCamera.inputsmgr;
  43603. if (parsedInputs) {
  43604. this.clear();
  43605. for (var n in parsedInputs) {
  43606. var construct = BABYLON.CameraInputTypes[n];
  43607. if (construct) {
  43608. var parsedinput = parsedInputs[n];
  43609. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43610. this.add(input);
  43611. }
  43612. }
  43613. }
  43614. else {
  43615. //2016-03-08 this part is for managing backward compatibility
  43616. for (var n in this.attached) {
  43617. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43618. if (construct) {
  43619. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43620. this.remove(this.attached[n]);
  43621. this.add(input);
  43622. }
  43623. }
  43624. }
  43625. };
  43626. return CameraInputsManager;
  43627. }());
  43628. BABYLON.CameraInputsManager = CameraInputsManager;
  43629. })(BABYLON || (BABYLON = {}));
  43630. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43631. "use strict";
  43632. var BABYLON;
  43633. (function (BABYLON) {
  43634. var TargetCamera = /** @class */ (function (_super) {
  43635. __extends(TargetCamera, _super);
  43636. function TargetCamera(name, position, scene) {
  43637. var _this = _super.call(this, name, position, scene) || this;
  43638. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43639. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43640. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43641. _this.speed = 2.0;
  43642. _this.noRotationConstraint = false;
  43643. _this.lockedTarget = null;
  43644. _this._currentTarget = BABYLON.Vector3.Zero();
  43645. _this._viewMatrix = BABYLON.Matrix.Zero();
  43646. _this._camMatrix = BABYLON.Matrix.Zero();
  43647. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43648. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43649. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43650. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43651. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43652. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43653. _this._tempMatrix = BABYLON.Matrix.Zero();
  43654. return _this;
  43655. }
  43656. TargetCamera.prototype.getFrontPosition = function (distance) {
  43657. this.getWorldMatrix();
  43658. var direction = this.getTarget().subtract(this.position);
  43659. direction.normalize();
  43660. direction.scaleInPlace(distance);
  43661. return this.globalPosition.add(direction);
  43662. };
  43663. TargetCamera.prototype._getLockedTargetPosition = function () {
  43664. if (!this.lockedTarget) {
  43665. return null;
  43666. }
  43667. if (this.lockedTarget.absolutePosition) {
  43668. this.lockedTarget.computeWorldMatrix();
  43669. }
  43670. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43671. };
  43672. TargetCamera.prototype.storeState = function () {
  43673. this._storedPosition = this.position.clone();
  43674. this._storedRotation = this.rotation.clone();
  43675. if (this.rotationQuaternion) {
  43676. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43677. }
  43678. return _super.prototype.storeState.call(this);
  43679. };
  43680. /**
  43681. * Restored camera state. You must call storeState() first
  43682. */
  43683. TargetCamera.prototype._restoreStateValues = function () {
  43684. if (!_super.prototype._restoreStateValues.call(this)) {
  43685. return false;
  43686. }
  43687. this.position = this._storedPosition.clone();
  43688. this.rotation = this._storedRotation.clone();
  43689. if (this.rotationQuaternion) {
  43690. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43691. }
  43692. this.cameraDirection.copyFromFloats(0, 0, 0);
  43693. this.cameraRotation.copyFromFloats(0, 0);
  43694. return true;
  43695. };
  43696. // Cache
  43697. TargetCamera.prototype._initCache = function () {
  43698. _super.prototype._initCache.call(this);
  43699. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43700. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43701. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43702. };
  43703. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43704. if (!ignoreParentClass) {
  43705. _super.prototype._updateCache.call(this);
  43706. }
  43707. var lockedTargetPosition = this._getLockedTargetPosition();
  43708. if (!lockedTargetPosition) {
  43709. this._cache.lockedTarget = null;
  43710. }
  43711. else {
  43712. if (!this._cache.lockedTarget) {
  43713. this._cache.lockedTarget = lockedTargetPosition.clone();
  43714. }
  43715. else {
  43716. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43717. }
  43718. }
  43719. this._cache.rotation.copyFrom(this.rotation);
  43720. if (this.rotationQuaternion)
  43721. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43722. };
  43723. // Synchronized
  43724. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43725. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43726. return false;
  43727. }
  43728. var lockedTargetPosition = this._getLockedTargetPosition();
  43729. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43730. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43731. };
  43732. // Methods
  43733. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43734. var engine = this.getEngine();
  43735. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43736. };
  43737. // Target
  43738. TargetCamera.prototype.setTarget = function (target) {
  43739. this.upVector.normalize();
  43740. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43741. this._camMatrix.invert();
  43742. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43743. var vDir = target.subtract(this.position);
  43744. if (vDir.x >= 0.0) {
  43745. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43746. }
  43747. else {
  43748. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43749. }
  43750. this.rotation.z = 0;
  43751. if (isNaN(this.rotation.x)) {
  43752. this.rotation.x = 0;
  43753. }
  43754. if (isNaN(this.rotation.y)) {
  43755. this.rotation.y = 0;
  43756. }
  43757. if (isNaN(this.rotation.z)) {
  43758. this.rotation.z = 0;
  43759. }
  43760. if (this.rotationQuaternion) {
  43761. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43762. }
  43763. };
  43764. /**
  43765. * Return the current target position of the camera. This value is expressed in local space.
  43766. */
  43767. TargetCamera.prototype.getTarget = function () {
  43768. return this._currentTarget;
  43769. };
  43770. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43771. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43772. };
  43773. TargetCamera.prototype._updatePosition = function () {
  43774. if (this.parent) {
  43775. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43776. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43777. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43778. return;
  43779. }
  43780. this.position.addInPlace(this.cameraDirection);
  43781. };
  43782. TargetCamera.prototype._checkInputs = function () {
  43783. var needToMove = this._decideIfNeedsToMove();
  43784. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43785. // Move
  43786. if (needToMove) {
  43787. this._updatePosition();
  43788. }
  43789. // Rotate
  43790. if (needToRotate) {
  43791. this.rotation.x += this.cameraRotation.x;
  43792. this.rotation.y += this.cameraRotation.y;
  43793. //rotate, if quaternion is set and rotation was used
  43794. if (this.rotationQuaternion) {
  43795. var len = this.rotation.lengthSquared();
  43796. if (len) {
  43797. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43798. }
  43799. }
  43800. if (!this.noRotationConstraint) {
  43801. var limit = (Math.PI / 2) * 0.95;
  43802. if (this.rotation.x > limit)
  43803. this.rotation.x = limit;
  43804. if (this.rotation.x < -limit)
  43805. this.rotation.x = -limit;
  43806. }
  43807. }
  43808. // Inertia
  43809. if (needToMove) {
  43810. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43811. this.cameraDirection.x = 0;
  43812. }
  43813. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43814. this.cameraDirection.y = 0;
  43815. }
  43816. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43817. this.cameraDirection.z = 0;
  43818. }
  43819. this.cameraDirection.scaleInPlace(this.inertia);
  43820. }
  43821. if (needToRotate) {
  43822. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43823. this.cameraRotation.x = 0;
  43824. }
  43825. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43826. this.cameraRotation.y = 0;
  43827. }
  43828. this.cameraRotation.scaleInPlace(this.inertia);
  43829. }
  43830. _super.prototype._checkInputs.call(this);
  43831. };
  43832. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43833. if (this.rotationQuaternion) {
  43834. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43835. }
  43836. else {
  43837. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43838. }
  43839. //update the up vector!
  43840. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43841. };
  43842. TargetCamera.prototype._getViewMatrix = function () {
  43843. if (this.lockedTarget) {
  43844. this.setTarget(this._getLockedTargetPosition());
  43845. }
  43846. // Compute
  43847. this._updateCameraRotationMatrix();
  43848. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43849. // Computing target and final matrix
  43850. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43851. if (this.getScene().useRightHandedSystem) {
  43852. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43853. }
  43854. else {
  43855. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43856. }
  43857. return this._viewMatrix;
  43858. };
  43859. /**
  43860. * @override
  43861. * Override Camera.createRigCamera
  43862. */
  43863. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43864. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43865. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43866. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43867. if (!this.rotationQuaternion) {
  43868. this.rotationQuaternion = new BABYLON.Quaternion();
  43869. }
  43870. rigCamera._cameraRigParams = {};
  43871. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43872. }
  43873. return rigCamera;
  43874. }
  43875. return null;
  43876. };
  43877. /**
  43878. * @override
  43879. * Override Camera._updateRigCameras
  43880. */
  43881. TargetCamera.prototype._updateRigCameras = function () {
  43882. var camLeft = this._rigCameras[0];
  43883. var camRight = this._rigCameras[1];
  43884. switch (this.cameraRigMode) {
  43885. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43886. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43887. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43888. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43889. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43890. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43891. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43892. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43893. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43894. camLeft.setTarget(this.getTarget());
  43895. camRight.setTarget(this.getTarget());
  43896. break;
  43897. case BABYLON.Camera.RIG_MODE_VR:
  43898. if (camLeft.rotationQuaternion) {
  43899. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43900. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43901. }
  43902. else {
  43903. camLeft.rotation.copyFrom(this.rotation);
  43904. camRight.rotation.copyFrom(this.rotation);
  43905. }
  43906. camLeft.position.copyFrom(this.position);
  43907. camRight.position.copyFrom(this.position);
  43908. break;
  43909. }
  43910. _super.prototype._updateRigCameras.call(this);
  43911. };
  43912. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43913. if (!this._rigCamTransformMatrix) {
  43914. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43915. }
  43916. var target = this.getTarget();
  43917. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43918. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43919. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43920. };
  43921. TargetCamera.prototype.getClassName = function () {
  43922. return "TargetCamera";
  43923. };
  43924. __decorate([
  43925. BABYLON.serializeAsVector3()
  43926. ], TargetCamera.prototype, "rotation", void 0);
  43927. __decorate([
  43928. BABYLON.serialize()
  43929. ], TargetCamera.prototype, "speed", void 0);
  43930. __decorate([
  43931. BABYLON.serializeAsMeshReference("lockedTargetId")
  43932. ], TargetCamera.prototype, "lockedTarget", void 0);
  43933. return TargetCamera;
  43934. }(BABYLON.Camera));
  43935. BABYLON.TargetCamera = TargetCamera;
  43936. })(BABYLON || (BABYLON = {}));
  43937. //# sourceMappingURL=babylon.targetCamera.js.map
  43938. "use strict";
  43939. var BABYLON;
  43940. (function (BABYLON) {
  43941. var FreeCameraMouseInput = /** @class */ (function () {
  43942. function FreeCameraMouseInput(touchEnabled) {
  43943. if (touchEnabled === void 0) { touchEnabled = true; }
  43944. this.touchEnabled = touchEnabled;
  43945. this.buttons = [0, 1, 2];
  43946. this.angularSensibility = 2000.0;
  43947. this.previousPosition = null;
  43948. }
  43949. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43950. var _this = this;
  43951. var engine = this.camera.getEngine();
  43952. if (!this._pointerInput) {
  43953. this._pointerInput = function (p, s) {
  43954. var evt = p.event;
  43955. if (engine.isInVRExclusivePointerMode) {
  43956. return;
  43957. }
  43958. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43959. return;
  43960. }
  43961. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43962. return;
  43963. }
  43964. var srcElement = (evt.srcElement || evt.target);
  43965. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43966. try {
  43967. srcElement.setPointerCapture(evt.pointerId);
  43968. }
  43969. catch (e) {
  43970. //Nothing to do with the error. Execution will continue.
  43971. }
  43972. _this.previousPosition = {
  43973. x: evt.clientX,
  43974. y: evt.clientY
  43975. };
  43976. if (!noPreventDefault) {
  43977. evt.preventDefault();
  43978. element.focus();
  43979. }
  43980. }
  43981. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43982. try {
  43983. srcElement.releasePointerCapture(evt.pointerId);
  43984. }
  43985. catch (e) {
  43986. //Nothing to do with the error.
  43987. }
  43988. _this.previousPosition = null;
  43989. if (!noPreventDefault) {
  43990. evt.preventDefault();
  43991. }
  43992. }
  43993. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43994. if (!_this.previousPosition || engine.isPointerLock) {
  43995. return;
  43996. }
  43997. var offsetX = evt.clientX - _this.previousPosition.x;
  43998. var offsetY = evt.clientY - _this.previousPosition.y;
  43999. if (_this.camera.getScene().useRightHandedSystem) {
  44000. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  44001. }
  44002. else {
  44003. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  44004. }
  44005. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44006. _this.previousPosition = {
  44007. x: evt.clientX,
  44008. y: evt.clientY
  44009. };
  44010. if (!noPreventDefault) {
  44011. evt.preventDefault();
  44012. }
  44013. }
  44014. };
  44015. }
  44016. this._onMouseMove = function (evt) {
  44017. if (!engine.isPointerLock) {
  44018. return;
  44019. }
  44020. if (engine.isInVRExclusivePointerMode) {
  44021. return;
  44022. }
  44023. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44024. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44025. if (_this.camera.getScene().useRightHandedSystem) {
  44026. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  44027. }
  44028. else {
  44029. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  44030. }
  44031. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44032. _this.previousPosition = null;
  44033. if (!noPreventDefault) {
  44034. evt.preventDefault();
  44035. }
  44036. };
  44037. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  44038. element.addEventListener("mousemove", this._onMouseMove, false);
  44039. };
  44040. FreeCameraMouseInput.prototype.detachControl = function (element) {
  44041. if (this._observer && element) {
  44042. this.camera.getScene().onPointerObservable.remove(this._observer);
  44043. if (this._onMouseMove) {
  44044. element.removeEventListener("mousemove", this._onMouseMove);
  44045. }
  44046. this._observer = null;
  44047. this._onMouseMove = null;
  44048. this.previousPosition = null;
  44049. }
  44050. };
  44051. FreeCameraMouseInput.prototype.getClassName = function () {
  44052. return "FreeCameraMouseInput";
  44053. };
  44054. FreeCameraMouseInput.prototype.getSimpleName = function () {
  44055. return "mouse";
  44056. };
  44057. __decorate([
  44058. BABYLON.serialize()
  44059. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  44060. __decorate([
  44061. BABYLON.serialize()
  44062. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  44063. return FreeCameraMouseInput;
  44064. }());
  44065. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  44066. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  44067. })(BABYLON || (BABYLON = {}));
  44068. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  44069. "use strict";
  44070. var BABYLON;
  44071. (function (BABYLON) {
  44072. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  44073. function FreeCameraKeyboardMoveInput() {
  44074. this._keys = new Array();
  44075. this.keysUp = [38];
  44076. this.keysDown = [40];
  44077. this.keysLeft = [37];
  44078. this.keysRight = [39];
  44079. }
  44080. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44081. var _this = this;
  44082. if (this._onCanvasBlurObserver) {
  44083. return;
  44084. }
  44085. this._scene = this.camera.getScene();
  44086. this._engine = this._scene.getEngine();
  44087. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44088. _this._keys = [];
  44089. });
  44090. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44091. var evt = info.event;
  44092. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44093. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44094. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44095. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44096. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44097. var index = _this._keys.indexOf(evt.keyCode);
  44098. if (index === -1) {
  44099. _this._keys.push(evt.keyCode);
  44100. }
  44101. if (!noPreventDefault) {
  44102. evt.preventDefault();
  44103. }
  44104. }
  44105. }
  44106. else {
  44107. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44108. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44109. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44110. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44111. var index = _this._keys.indexOf(evt.keyCode);
  44112. if (index >= 0) {
  44113. _this._keys.splice(index, 1);
  44114. }
  44115. if (!noPreventDefault) {
  44116. evt.preventDefault();
  44117. }
  44118. }
  44119. }
  44120. });
  44121. };
  44122. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44123. if (this._scene) {
  44124. if (this._onKeyboardObserver) {
  44125. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44126. }
  44127. if (this._onCanvasBlurObserver) {
  44128. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44129. }
  44130. this._onKeyboardObserver = null;
  44131. this._onCanvasBlurObserver = null;
  44132. }
  44133. this._keys = [];
  44134. };
  44135. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44136. if (this._onKeyboardObserver) {
  44137. var camera = this.camera;
  44138. // Keyboard
  44139. for (var index = 0; index < this._keys.length; index++) {
  44140. var keyCode = this._keys[index];
  44141. var speed = camera._computeLocalCameraSpeed();
  44142. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44143. camera._localDirection.copyFromFloats(-speed, 0, 0);
  44144. }
  44145. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44146. camera._localDirection.copyFromFloats(0, 0, speed);
  44147. }
  44148. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44149. camera._localDirection.copyFromFloats(speed, 0, 0);
  44150. }
  44151. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44152. camera._localDirection.copyFromFloats(0, 0, -speed);
  44153. }
  44154. if (camera.getScene().useRightHandedSystem) {
  44155. camera._localDirection.z *= -1;
  44156. }
  44157. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  44158. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  44159. camera.cameraDirection.addInPlace(camera._transformedDirection);
  44160. }
  44161. }
  44162. };
  44163. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  44164. return "FreeCameraKeyboardMoveInput";
  44165. };
  44166. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  44167. this._keys = [];
  44168. };
  44169. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44170. return "keyboard";
  44171. };
  44172. __decorate([
  44173. BABYLON.serialize()
  44174. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44175. __decorate([
  44176. BABYLON.serialize()
  44177. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44178. __decorate([
  44179. BABYLON.serialize()
  44180. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44181. __decorate([
  44182. BABYLON.serialize()
  44183. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44184. return FreeCameraKeyboardMoveInput;
  44185. }());
  44186. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  44187. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  44188. })(BABYLON || (BABYLON = {}));
  44189. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  44190. "use strict";
  44191. var BABYLON;
  44192. (function (BABYLON) {
  44193. var FreeCameraInputsManager = /** @class */ (function (_super) {
  44194. __extends(FreeCameraInputsManager, _super);
  44195. function FreeCameraInputsManager(camera) {
  44196. return _super.call(this, camera) || this;
  44197. }
  44198. FreeCameraInputsManager.prototype.addKeyboard = function () {
  44199. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  44200. return this;
  44201. };
  44202. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  44203. if (touchEnabled === void 0) { touchEnabled = true; }
  44204. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  44205. return this;
  44206. };
  44207. FreeCameraInputsManager.prototype.addGamepad = function () {
  44208. this.add(new BABYLON.FreeCameraGamepadInput());
  44209. return this;
  44210. };
  44211. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  44212. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  44213. return this;
  44214. };
  44215. FreeCameraInputsManager.prototype.addTouch = function () {
  44216. this.add(new BABYLON.FreeCameraTouchInput());
  44217. return this;
  44218. };
  44219. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  44220. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  44221. return this;
  44222. };
  44223. return FreeCameraInputsManager;
  44224. }(BABYLON.CameraInputsManager));
  44225. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  44226. })(BABYLON || (BABYLON = {}));
  44227. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  44228. "use strict";
  44229. var BABYLON;
  44230. (function (BABYLON) {
  44231. var FreeCamera = /** @class */ (function (_super) {
  44232. __extends(FreeCamera, _super);
  44233. function FreeCamera(name, position, scene) {
  44234. var _this = _super.call(this, name, position, scene) || this;
  44235. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  44236. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  44237. _this.checkCollisions = false;
  44238. _this.applyGravity = false;
  44239. _this._needMoveForGravity = false;
  44240. _this._oldPosition = BABYLON.Vector3.Zero();
  44241. _this._diffPosition = BABYLON.Vector3.Zero();
  44242. _this._newPosition = BABYLON.Vector3.Zero();
  44243. // Collisions
  44244. _this._collisionMask = -1;
  44245. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44246. if (collidedMesh === void 0) { collidedMesh = null; }
  44247. //TODO move this to the collision coordinator!
  44248. if (_this.getScene().workerCollisions)
  44249. newPosition.multiplyInPlace(_this._collider._radius);
  44250. var updatePosition = function (newPos) {
  44251. _this._newPosition.copyFrom(newPos);
  44252. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  44253. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  44254. _this.position.addInPlace(_this._diffPosition);
  44255. if (_this.onCollide && collidedMesh) {
  44256. _this.onCollide(collidedMesh);
  44257. }
  44258. }
  44259. };
  44260. updatePosition(newPosition);
  44261. };
  44262. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  44263. _this.inputs.addKeyboard().addMouse();
  44264. return _this;
  44265. }
  44266. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  44267. //-- begin properties for backward compatibility for inputs
  44268. /**
  44269. * Gets the input sensibility for a mouse input. (default is 2000.0)
  44270. * Higher values reduce sensitivity.
  44271. */
  44272. get: function () {
  44273. var mouse = this.inputs.attached["mouse"];
  44274. if (mouse)
  44275. return mouse.angularSensibility;
  44276. return 0;
  44277. },
  44278. /**
  44279. * Sets the input sensibility for a mouse input. (default is 2000.0)
  44280. * Higher values reduce sensitivity.
  44281. */
  44282. set: function (value) {
  44283. var mouse = this.inputs.attached["mouse"];
  44284. if (mouse)
  44285. mouse.angularSensibility = value;
  44286. },
  44287. enumerable: true,
  44288. configurable: true
  44289. });
  44290. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  44291. get: function () {
  44292. var keyboard = this.inputs.attached["keyboard"];
  44293. if (keyboard)
  44294. return keyboard.keysUp;
  44295. return [];
  44296. },
  44297. set: function (value) {
  44298. var keyboard = this.inputs.attached["keyboard"];
  44299. if (keyboard)
  44300. keyboard.keysUp = value;
  44301. },
  44302. enumerable: true,
  44303. configurable: true
  44304. });
  44305. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  44306. get: function () {
  44307. var keyboard = this.inputs.attached["keyboard"];
  44308. if (keyboard)
  44309. return keyboard.keysDown;
  44310. return [];
  44311. },
  44312. set: function (value) {
  44313. var keyboard = this.inputs.attached["keyboard"];
  44314. if (keyboard)
  44315. keyboard.keysDown = value;
  44316. },
  44317. enumerable: true,
  44318. configurable: true
  44319. });
  44320. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  44321. get: function () {
  44322. var keyboard = this.inputs.attached["keyboard"];
  44323. if (keyboard)
  44324. return keyboard.keysLeft;
  44325. return [];
  44326. },
  44327. set: function (value) {
  44328. var keyboard = this.inputs.attached["keyboard"];
  44329. if (keyboard)
  44330. keyboard.keysLeft = value;
  44331. },
  44332. enumerable: true,
  44333. configurable: true
  44334. });
  44335. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  44336. get: function () {
  44337. var keyboard = this.inputs.attached["keyboard"];
  44338. if (keyboard)
  44339. return keyboard.keysRight;
  44340. return [];
  44341. },
  44342. set: function (value) {
  44343. var keyboard = this.inputs.attached["keyboard"];
  44344. if (keyboard)
  44345. keyboard.keysRight = value;
  44346. },
  44347. enumerable: true,
  44348. configurable: true
  44349. });
  44350. // Controls
  44351. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44352. this.inputs.attachElement(element, noPreventDefault);
  44353. };
  44354. FreeCamera.prototype.detachControl = function (element) {
  44355. this.inputs.detachElement(element);
  44356. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44357. this.cameraRotation = new BABYLON.Vector2(0, 0);
  44358. };
  44359. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  44360. get: function () {
  44361. return this._collisionMask;
  44362. },
  44363. set: function (mask) {
  44364. this._collisionMask = !isNaN(mask) ? mask : -1;
  44365. },
  44366. enumerable: true,
  44367. configurable: true
  44368. });
  44369. FreeCamera.prototype._collideWithWorld = function (displacement) {
  44370. var globalPosition;
  44371. if (this.parent) {
  44372. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  44373. }
  44374. else {
  44375. globalPosition = this.position;
  44376. }
  44377. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  44378. this._oldPosition.addInPlace(this.ellipsoidOffset);
  44379. if (!this._collider) {
  44380. this._collider = new BABYLON.Collider();
  44381. }
  44382. this._collider._radius = this.ellipsoid;
  44383. this._collider.collisionMask = this._collisionMask;
  44384. //no need for clone, as long as gravity is not on.
  44385. var actualDisplacement = displacement;
  44386. //add gravity to the direction to prevent the dual-collision checking
  44387. if (this.applyGravity) {
  44388. //this prevents mending with cameraDirection, a global variable of the free camera class.
  44389. actualDisplacement = displacement.add(this.getScene().gravity);
  44390. }
  44391. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44392. };
  44393. FreeCamera.prototype._checkInputs = function () {
  44394. if (!this._localDirection) {
  44395. this._localDirection = BABYLON.Vector3.Zero();
  44396. this._transformedDirection = BABYLON.Vector3.Zero();
  44397. }
  44398. this.inputs.checkInputs();
  44399. _super.prototype._checkInputs.call(this);
  44400. };
  44401. FreeCamera.prototype._decideIfNeedsToMove = function () {
  44402. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44403. };
  44404. FreeCamera.prototype._updatePosition = function () {
  44405. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44406. this._collideWithWorld(this.cameraDirection);
  44407. }
  44408. else {
  44409. _super.prototype._updatePosition.call(this);
  44410. }
  44411. };
  44412. FreeCamera.prototype.dispose = function () {
  44413. this.inputs.clear();
  44414. _super.prototype.dispose.call(this);
  44415. };
  44416. FreeCamera.prototype.getClassName = function () {
  44417. return "FreeCamera";
  44418. };
  44419. __decorate([
  44420. BABYLON.serializeAsVector3()
  44421. ], FreeCamera.prototype, "ellipsoid", void 0);
  44422. __decorate([
  44423. BABYLON.serializeAsVector3()
  44424. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44425. __decorate([
  44426. BABYLON.serialize()
  44427. ], FreeCamera.prototype, "checkCollisions", void 0);
  44428. __decorate([
  44429. BABYLON.serialize()
  44430. ], FreeCamera.prototype, "applyGravity", void 0);
  44431. return FreeCamera;
  44432. }(BABYLON.TargetCamera));
  44433. BABYLON.FreeCamera = FreeCamera;
  44434. })(BABYLON || (BABYLON = {}));
  44435. //# sourceMappingURL=babylon.freeCamera.js.map
  44436. "use strict";
  44437. var BABYLON;
  44438. (function (BABYLON) {
  44439. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44440. function ArcRotateCameraKeyboardMoveInput() {
  44441. this._keys = new Array();
  44442. this.keysUp = [38];
  44443. this.keysDown = [40];
  44444. this.keysLeft = [37];
  44445. this.keysRight = [39];
  44446. this.keysReset = [220];
  44447. this.panningSensibility = 50.0;
  44448. this.zoomingSensibility = 25.0;
  44449. this.useAltToZoom = true;
  44450. }
  44451. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44452. var _this = this;
  44453. if (this._onCanvasBlurObserver) {
  44454. return;
  44455. }
  44456. this._scene = this.camera.getScene();
  44457. this._engine = this._scene.getEngine();
  44458. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44459. _this._keys = [];
  44460. });
  44461. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44462. var evt = info.event;
  44463. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44464. _this._ctrlPressed = evt.ctrlKey;
  44465. _this._altPressed = evt.altKey;
  44466. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44467. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44468. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44469. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44470. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44471. var index = _this._keys.indexOf(evt.keyCode);
  44472. if (index === -1) {
  44473. _this._keys.push(evt.keyCode);
  44474. }
  44475. if (evt.preventDefault) {
  44476. if (!noPreventDefault) {
  44477. evt.preventDefault();
  44478. }
  44479. }
  44480. }
  44481. }
  44482. else {
  44483. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44484. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44485. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44486. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44487. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44488. var index = _this._keys.indexOf(evt.keyCode);
  44489. if (index >= 0) {
  44490. _this._keys.splice(index, 1);
  44491. }
  44492. if (evt.preventDefault) {
  44493. if (!noPreventDefault) {
  44494. evt.preventDefault();
  44495. }
  44496. }
  44497. }
  44498. }
  44499. });
  44500. };
  44501. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44502. if (this._scene) {
  44503. if (this._onKeyboardObserver) {
  44504. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44505. }
  44506. if (this._onCanvasBlurObserver) {
  44507. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44508. }
  44509. this._onKeyboardObserver = null;
  44510. this._onCanvasBlurObserver = null;
  44511. }
  44512. this._keys = [];
  44513. };
  44514. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44515. if (this._onKeyboardObserver) {
  44516. var camera = this.camera;
  44517. for (var index = 0; index < this._keys.length; index++) {
  44518. var keyCode = this._keys[index];
  44519. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44520. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44521. camera.inertialPanningX -= 1 / this.panningSensibility;
  44522. }
  44523. else {
  44524. camera.inertialAlphaOffset -= 0.01;
  44525. }
  44526. }
  44527. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44528. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44529. camera.inertialPanningY += 1 / this.panningSensibility;
  44530. }
  44531. else if (this._altPressed && this.useAltToZoom) {
  44532. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44533. }
  44534. else {
  44535. camera.inertialBetaOffset -= 0.01;
  44536. }
  44537. }
  44538. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44539. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44540. camera.inertialPanningX += 1 / this.panningSensibility;
  44541. }
  44542. else {
  44543. camera.inertialAlphaOffset += 0.01;
  44544. }
  44545. }
  44546. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44547. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44548. camera.inertialPanningY -= 1 / this.panningSensibility;
  44549. }
  44550. else if (this._altPressed && this.useAltToZoom) {
  44551. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44552. }
  44553. else {
  44554. camera.inertialBetaOffset += 0.01;
  44555. }
  44556. }
  44557. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44558. camera.restoreState();
  44559. }
  44560. }
  44561. }
  44562. };
  44563. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44564. return "ArcRotateCameraKeyboardMoveInput";
  44565. };
  44566. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44567. return "keyboard";
  44568. };
  44569. __decorate([
  44570. BABYLON.serialize()
  44571. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44572. __decorate([
  44573. BABYLON.serialize()
  44574. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44575. __decorate([
  44576. BABYLON.serialize()
  44577. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44578. __decorate([
  44579. BABYLON.serialize()
  44580. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44581. __decorate([
  44582. BABYLON.serialize()
  44583. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44584. __decorate([
  44585. BABYLON.serialize()
  44586. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44587. __decorate([
  44588. BABYLON.serialize()
  44589. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44590. __decorate([
  44591. BABYLON.serialize()
  44592. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44593. return ArcRotateCameraKeyboardMoveInput;
  44594. }());
  44595. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44596. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44597. })(BABYLON || (BABYLON = {}));
  44598. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44599. "use strict";
  44600. var BABYLON;
  44601. (function (BABYLON) {
  44602. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44603. function ArcRotateCameraMouseWheelInput() {
  44604. this.wheelPrecision = 3.0;
  44605. /**
  44606. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44607. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44608. */
  44609. this.wheelDeltaPercentage = 0;
  44610. }
  44611. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44612. var _this = this;
  44613. this._wheel = function (p, s) {
  44614. //sanity check - this should be a PointerWheel event.
  44615. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44616. return;
  44617. var event = p.event;
  44618. var delta = 0;
  44619. if (event.wheelDelta) {
  44620. if (_this.wheelDeltaPercentage) {
  44621. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  44622. if (event.wheelDelta > 0) {
  44623. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  44624. }
  44625. else {
  44626. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  44627. }
  44628. }
  44629. else {
  44630. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  44631. }
  44632. }
  44633. else if (event.detail) {
  44634. delta = -event.detail / _this.wheelPrecision;
  44635. }
  44636. if (delta)
  44637. _this.camera.inertialRadiusOffset += delta;
  44638. if (event.preventDefault) {
  44639. if (!noPreventDefault) {
  44640. event.preventDefault();
  44641. }
  44642. }
  44643. };
  44644. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44645. };
  44646. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44647. if (this._observer && element) {
  44648. this.camera.getScene().onPointerObservable.remove(this._observer);
  44649. this._observer = null;
  44650. this._wheel = null;
  44651. }
  44652. };
  44653. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44654. return "ArcRotateCameraMouseWheelInput";
  44655. };
  44656. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44657. return "mousewheel";
  44658. };
  44659. __decorate([
  44660. BABYLON.serialize()
  44661. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44662. __decorate([
  44663. BABYLON.serialize()
  44664. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44665. return ArcRotateCameraMouseWheelInput;
  44666. }());
  44667. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44668. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44669. })(BABYLON || (BABYLON = {}));
  44670. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44671. "use strict";
  44672. var BABYLON;
  44673. (function (BABYLON) {
  44674. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44675. function ArcRotateCameraPointersInput() {
  44676. this.buttons = [0, 1, 2];
  44677. this.angularSensibilityX = 1000.0;
  44678. this.angularSensibilityY = 1000.0;
  44679. this.pinchPrecision = 12.0;
  44680. /**
  44681. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44682. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44683. */
  44684. this.pinchDeltaPercentage = 0;
  44685. this.panningSensibility = 1000.0;
  44686. this.multiTouchPanning = true;
  44687. this.multiTouchPanAndZoom = true;
  44688. this._isPanClick = false;
  44689. this.pinchInwards = true;
  44690. }
  44691. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44692. var _this = this;
  44693. var engine = this.camera.getEngine();
  44694. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44695. var pointA = null;
  44696. var pointB = null;
  44697. var previousPinchSquaredDistance = 0;
  44698. var initialDistance = 0;
  44699. var twoFingerActivityCount = 0;
  44700. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44701. this._pointerInput = function (p, s) {
  44702. var evt = p.event;
  44703. var isTouch = p.event.pointerType === "touch";
  44704. if (engine.isInVRExclusivePointerMode) {
  44705. return;
  44706. }
  44707. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44708. return;
  44709. }
  44710. var srcElement = (evt.srcElement || evt.target);
  44711. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44712. try {
  44713. srcElement.setPointerCapture(evt.pointerId);
  44714. }
  44715. catch (e) {
  44716. //Nothing to do with the error. Execution will continue.
  44717. }
  44718. // Manage panning with pan button click
  44719. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44720. // manage pointers
  44721. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44722. if (pointA === null) {
  44723. pointA = cacheSoloPointer;
  44724. }
  44725. else if (pointB === null) {
  44726. pointB = cacheSoloPointer;
  44727. }
  44728. if (!noPreventDefault) {
  44729. evt.preventDefault();
  44730. element.focus();
  44731. }
  44732. }
  44733. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44734. _this.camera.restoreState();
  44735. }
  44736. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44737. try {
  44738. srcElement.releasePointerCapture(evt.pointerId);
  44739. }
  44740. catch (e) {
  44741. //Nothing to do with the error.
  44742. }
  44743. cacheSoloPointer = null;
  44744. previousPinchSquaredDistance = 0;
  44745. previousMultiTouchPanPosition.isPaning = false;
  44746. previousMultiTouchPanPosition.isPinching = false;
  44747. twoFingerActivityCount = 0;
  44748. initialDistance = 0;
  44749. if (!isTouch) {
  44750. pointB = null; // Mouse and pen are mono pointer
  44751. }
  44752. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44753. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44754. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44755. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44756. if (engine.badOS) {
  44757. pointA = pointB = null;
  44758. }
  44759. else {
  44760. //only remove the impacted pointer in case of multitouch allowing on most
  44761. //platforms switching from rotate to zoom and pan seamlessly.
  44762. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44763. pointA = pointB;
  44764. pointB = null;
  44765. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44766. }
  44767. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44768. pointB = null;
  44769. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44770. }
  44771. else {
  44772. pointA = pointB = null;
  44773. }
  44774. }
  44775. if (!noPreventDefault) {
  44776. evt.preventDefault();
  44777. }
  44778. }
  44779. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44780. if (!noPreventDefault) {
  44781. evt.preventDefault();
  44782. }
  44783. // One button down
  44784. if (pointA && pointB === null && cacheSoloPointer) {
  44785. if (_this.panningSensibility !== 0 &&
  44786. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44787. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44788. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44789. }
  44790. else {
  44791. var offsetX = evt.clientX - cacheSoloPointer.x;
  44792. var offsetY = evt.clientY - cacheSoloPointer.y;
  44793. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44794. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44795. }
  44796. cacheSoloPointer.x = evt.clientX;
  44797. cacheSoloPointer.y = evt.clientY;
  44798. }
  44799. else if (pointA && pointB) {
  44800. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44801. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44802. ed.x = evt.clientX;
  44803. ed.y = evt.clientY;
  44804. var direction = _this.pinchInwards ? 1 : -1;
  44805. var distX = pointA.x - pointB.x;
  44806. var distY = pointA.y - pointB.y;
  44807. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44808. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44809. if (previousPinchSquaredDistance === 0) {
  44810. initialDistance = pinchDistance;
  44811. previousPinchSquaredDistance = pinchSquaredDistance;
  44812. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44813. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44814. return;
  44815. }
  44816. if (_this.multiTouchPanAndZoom) {
  44817. if (_this.pinchDeltaPercentage) {
  44818. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44819. }
  44820. else {
  44821. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44822. (_this.pinchPrecision *
  44823. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44824. direction);
  44825. }
  44826. if (_this.panningSensibility !== 0) {
  44827. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44828. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44829. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44830. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44831. previousMultiTouchPanPosition.x = pointersCenterX;
  44832. previousMultiTouchPanPosition.y = pointersCenterY;
  44833. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44834. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44835. }
  44836. }
  44837. else {
  44838. twoFingerActivityCount++;
  44839. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44840. if (_this.pinchDeltaPercentage) {
  44841. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44842. }
  44843. else {
  44844. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44845. (_this.pinchPrecision *
  44846. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44847. direction);
  44848. }
  44849. previousMultiTouchPanPosition.isPaning = false;
  44850. previousMultiTouchPanPosition.isPinching = true;
  44851. }
  44852. else {
  44853. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44854. if (!previousMultiTouchPanPosition.isPaning) {
  44855. previousMultiTouchPanPosition.isPaning = true;
  44856. previousMultiTouchPanPosition.isPinching = false;
  44857. previousMultiTouchPanPosition.x = ed.x;
  44858. previousMultiTouchPanPosition.y = ed.y;
  44859. return;
  44860. }
  44861. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44862. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44863. }
  44864. }
  44865. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44866. previousMultiTouchPanPosition.x = ed.x;
  44867. previousMultiTouchPanPosition.y = ed.y;
  44868. }
  44869. }
  44870. previousPinchSquaredDistance = pinchSquaredDistance;
  44871. }
  44872. }
  44873. };
  44874. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44875. this._onContextMenu = function (evt) {
  44876. evt.preventDefault();
  44877. };
  44878. if (!this.camera._useCtrlForPanning) {
  44879. element.addEventListener("contextmenu", this._onContextMenu, false);
  44880. }
  44881. this._onLostFocus = function () {
  44882. //this._keys = [];
  44883. pointA = pointB = null;
  44884. previousPinchSquaredDistance = 0;
  44885. previousMultiTouchPanPosition.isPaning = false;
  44886. previousMultiTouchPanPosition.isPinching = false;
  44887. twoFingerActivityCount = 0;
  44888. cacheSoloPointer = null;
  44889. initialDistance = 0;
  44890. };
  44891. this._onMouseMove = function (evt) {
  44892. if (!engine.isPointerLock) {
  44893. return;
  44894. }
  44895. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44896. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44897. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44898. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44899. if (!noPreventDefault) {
  44900. evt.preventDefault();
  44901. }
  44902. };
  44903. this._onGestureStart = function (e) {
  44904. if (window.MSGesture === undefined) {
  44905. return;
  44906. }
  44907. if (!_this._MSGestureHandler) {
  44908. _this._MSGestureHandler = new MSGesture();
  44909. _this._MSGestureHandler.target = element;
  44910. }
  44911. _this._MSGestureHandler.addPointer(e.pointerId);
  44912. };
  44913. this._onGesture = function (e) {
  44914. _this.camera.radius *= e.scale;
  44915. if (e.preventDefault) {
  44916. if (!noPreventDefault) {
  44917. e.stopPropagation();
  44918. e.preventDefault();
  44919. }
  44920. }
  44921. };
  44922. element.addEventListener("mousemove", this._onMouseMove, false);
  44923. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44924. element.addEventListener("MSGestureChange", this._onGesture, false);
  44925. BABYLON.Tools.RegisterTopRootEvents([
  44926. { name: "blur", handler: this._onLostFocus }
  44927. ]);
  44928. };
  44929. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44930. if (this._onLostFocus) {
  44931. BABYLON.Tools.UnregisterTopRootEvents([
  44932. { name: "blur", handler: this._onLostFocus }
  44933. ]);
  44934. }
  44935. if (element && this._observer) {
  44936. this.camera.getScene().onPointerObservable.remove(this._observer);
  44937. this._observer = null;
  44938. if (this._onContextMenu) {
  44939. element.removeEventListener("contextmenu", this._onContextMenu);
  44940. }
  44941. if (this._onMouseMove) {
  44942. element.removeEventListener("mousemove", this._onMouseMove);
  44943. }
  44944. if (this._onGestureStart) {
  44945. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44946. }
  44947. if (this._onGesture) {
  44948. element.removeEventListener("MSGestureChange", this._onGesture);
  44949. }
  44950. this._isPanClick = false;
  44951. this.pinchInwards = true;
  44952. this._onMouseMove = null;
  44953. this._onGestureStart = null;
  44954. this._onGesture = null;
  44955. this._MSGestureHandler = null;
  44956. this._onLostFocus = null;
  44957. this._onContextMenu = null;
  44958. }
  44959. };
  44960. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44961. return "ArcRotateCameraPointersInput";
  44962. };
  44963. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44964. return "pointers";
  44965. };
  44966. __decorate([
  44967. BABYLON.serialize()
  44968. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44969. __decorate([
  44970. BABYLON.serialize()
  44971. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44972. __decorate([
  44973. BABYLON.serialize()
  44974. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44975. __decorate([
  44976. BABYLON.serialize()
  44977. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44978. __decorate([
  44979. BABYLON.serialize()
  44980. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44981. __decorate([
  44982. BABYLON.serialize()
  44983. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44984. __decorate([
  44985. BABYLON.serialize()
  44986. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44987. __decorate([
  44988. BABYLON.serialize()
  44989. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44990. return ArcRotateCameraPointersInput;
  44991. }());
  44992. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44993. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44994. })(BABYLON || (BABYLON = {}));
  44995. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44996. "use strict";
  44997. var BABYLON;
  44998. (function (BABYLON) {
  44999. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  45000. __extends(ArcRotateCameraInputsManager, _super);
  45001. function ArcRotateCameraInputsManager(camera) {
  45002. return _super.call(this, camera) || this;
  45003. }
  45004. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  45005. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  45006. return this;
  45007. };
  45008. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  45009. this.add(new BABYLON.ArcRotateCameraPointersInput());
  45010. return this;
  45011. };
  45012. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  45013. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  45014. return this;
  45015. };
  45016. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  45017. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  45018. return this;
  45019. };
  45020. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  45021. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  45022. return this;
  45023. };
  45024. return ArcRotateCameraInputsManager;
  45025. }(BABYLON.CameraInputsManager));
  45026. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  45027. })(BABYLON || (BABYLON = {}));
  45028. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  45029. "use strict";
  45030. var BABYLON;
  45031. (function (BABYLON) {
  45032. var ArcRotateCamera = /** @class */ (function (_super) {
  45033. __extends(ArcRotateCamera, _super);
  45034. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  45035. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  45036. _this.inertialAlphaOffset = 0;
  45037. _this.inertialBetaOffset = 0;
  45038. _this.inertialRadiusOffset = 0;
  45039. _this.lowerAlphaLimit = null;
  45040. _this.upperAlphaLimit = null;
  45041. _this.lowerBetaLimit = 0.01;
  45042. _this.upperBetaLimit = Math.PI;
  45043. _this.lowerRadiusLimit = null;
  45044. _this.upperRadiusLimit = null;
  45045. _this.inertialPanningX = 0;
  45046. _this.inertialPanningY = 0;
  45047. _this.pinchToPanMaxDistance = 20;
  45048. _this.panningDistanceLimit = null;
  45049. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  45050. _this.panningInertia = 0.9;
  45051. //-- end properties for backward compatibility for inputs
  45052. _this.zoomOnFactor = 1;
  45053. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  45054. _this.allowUpsideDown = true;
  45055. _this._viewMatrix = new BABYLON.Matrix();
  45056. // Panning
  45057. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  45058. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  45059. _this.checkCollisions = false;
  45060. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45061. _this._previousPosition = BABYLON.Vector3.Zero();
  45062. _this._collisionVelocity = BABYLON.Vector3.Zero();
  45063. _this._newPosition = BABYLON.Vector3.Zero();
  45064. _this._computationVector = BABYLON.Vector3.Zero();
  45065. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  45066. if (collidedMesh === void 0) { collidedMesh = null; }
  45067. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  45068. newPosition.multiplyInPlace(_this._collider._radius);
  45069. }
  45070. if (!collidedMesh) {
  45071. _this._previousPosition.copyFrom(_this.position);
  45072. }
  45073. else {
  45074. _this.setPosition(newPosition);
  45075. if (_this.onCollide) {
  45076. _this.onCollide(collidedMesh);
  45077. }
  45078. }
  45079. // Recompute because of constraints
  45080. var cosa = Math.cos(_this.alpha);
  45081. var sina = Math.sin(_this.alpha);
  45082. var cosb = Math.cos(_this.beta);
  45083. var sinb = Math.sin(_this.beta);
  45084. if (sinb === 0) {
  45085. sinb = 0.0001;
  45086. }
  45087. var target = _this._getTargetPosition();
  45088. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  45089. target.addToRef(_this._computationVector, _this._newPosition);
  45090. _this.position.copyFrom(_this._newPosition);
  45091. var up = _this.upVector;
  45092. if (_this.allowUpsideDown && _this.beta < 0) {
  45093. up = up.clone();
  45094. up = up.negate();
  45095. }
  45096. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  45097. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  45098. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  45099. _this._collisionTriggered = false;
  45100. };
  45101. _this._target = BABYLON.Vector3.Zero();
  45102. if (target) {
  45103. _this.setTarget(target);
  45104. }
  45105. _this.alpha = alpha;
  45106. _this.beta = beta;
  45107. _this.radius = radius;
  45108. _this.getViewMatrix();
  45109. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  45110. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  45111. return _this;
  45112. }
  45113. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  45114. get: function () {
  45115. return this._target;
  45116. },
  45117. set: function (value) {
  45118. this.setTarget(value);
  45119. },
  45120. enumerable: true,
  45121. configurable: true
  45122. });
  45123. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  45124. //-- begin properties for backward compatibility for inputs
  45125. get: function () {
  45126. var pointers = this.inputs.attached["pointers"];
  45127. if (pointers)
  45128. return pointers.angularSensibilityX;
  45129. return 0;
  45130. },
  45131. set: function (value) {
  45132. var pointers = this.inputs.attached["pointers"];
  45133. if (pointers) {
  45134. pointers.angularSensibilityX = value;
  45135. }
  45136. },
  45137. enumerable: true,
  45138. configurable: true
  45139. });
  45140. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  45141. get: function () {
  45142. var pointers = this.inputs.attached["pointers"];
  45143. if (pointers)
  45144. return pointers.angularSensibilityY;
  45145. return 0;
  45146. },
  45147. set: function (value) {
  45148. var pointers = this.inputs.attached["pointers"];
  45149. if (pointers) {
  45150. pointers.angularSensibilityY = value;
  45151. }
  45152. },
  45153. enumerable: true,
  45154. configurable: true
  45155. });
  45156. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  45157. get: function () {
  45158. var pointers = this.inputs.attached["pointers"];
  45159. if (pointers)
  45160. return pointers.pinchPrecision;
  45161. return 0;
  45162. },
  45163. set: function (value) {
  45164. var pointers = this.inputs.attached["pointers"];
  45165. if (pointers) {
  45166. pointers.pinchPrecision = value;
  45167. }
  45168. },
  45169. enumerable: true,
  45170. configurable: true
  45171. });
  45172. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  45173. get: function () {
  45174. var pointers = this.inputs.attached["pointers"];
  45175. if (pointers)
  45176. return pointers.pinchDeltaPercentage;
  45177. return 0;
  45178. },
  45179. set: function (value) {
  45180. var pointers = this.inputs.attached["pointers"];
  45181. if (pointers) {
  45182. pointers.pinchDeltaPercentage = value;
  45183. }
  45184. },
  45185. enumerable: true,
  45186. configurable: true
  45187. });
  45188. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  45189. get: function () {
  45190. var pointers = this.inputs.attached["pointers"];
  45191. if (pointers)
  45192. return pointers.panningSensibility;
  45193. return 0;
  45194. },
  45195. set: function (value) {
  45196. var pointers = this.inputs.attached["pointers"];
  45197. if (pointers) {
  45198. pointers.panningSensibility = value;
  45199. }
  45200. },
  45201. enumerable: true,
  45202. configurable: true
  45203. });
  45204. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  45205. get: function () {
  45206. var keyboard = this.inputs.attached["keyboard"];
  45207. if (keyboard)
  45208. return keyboard.keysUp;
  45209. return [];
  45210. },
  45211. set: function (value) {
  45212. var keyboard = this.inputs.attached["keyboard"];
  45213. if (keyboard)
  45214. keyboard.keysUp = value;
  45215. },
  45216. enumerable: true,
  45217. configurable: true
  45218. });
  45219. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  45220. get: function () {
  45221. var keyboard = this.inputs.attached["keyboard"];
  45222. if (keyboard)
  45223. return keyboard.keysDown;
  45224. return [];
  45225. },
  45226. set: function (value) {
  45227. var keyboard = this.inputs.attached["keyboard"];
  45228. if (keyboard)
  45229. keyboard.keysDown = value;
  45230. },
  45231. enumerable: true,
  45232. configurable: true
  45233. });
  45234. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  45235. get: function () {
  45236. var keyboard = this.inputs.attached["keyboard"];
  45237. if (keyboard)
  45238. return keyboard.keysLeft;
  45239. return [];
  45240. },
  45241. set: function (value) {
  45242. var keyboard = this.inputs.attached["keyboard"];
  45243. if (keyboard)
  45244. keyboard.keysLeft = value;
  45245. },
  45246. enumerable: true,
  45247. configurable: true
  45248. });
  45249. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  45250. get: function () {
  45251. var keyboard = this.inputs.attached["keyboard"];
  45252. if (keyboard)
  45253. return keyboard.keysRight;
  45254. return [];
  45255. },
  45256. set: function (value) {
  45257. var keyboard = this.inputs.attached["keyboard"];
  45258. if (keyboard)
  45259. keyboard.keysRight = value;
  45260. },
  45261. enumerable: true,
  45262. configurable: true
  45263. });
  45264. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  45265. get: function () {
  45266. var mousewheel = this.inputs.attached["mousewheel"];
  45267. if (mousewheel)
  45268. return mousewheel.wheelPrecision;
  45269. return 0;
  45270. },
  45271. set: function (value) {
  45272. var mousewheel = this.inputs.attached["mousewheel"];
  45273. if (mousewheel)
  45274. mousewheel.wheelPrecision = value;
  45275. },
  45276. enumerable: true,
  45277. configurable: true
  45278. });
  45279. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  45280. get: function () {
  45281. var mousewheel = this.inputs.attached["mousewheel"];
  45282. if (mousewheel)
  45283. return mousewheel.wheelDeltaPercentage;
  45284. return 0;
  45285. },
  45286. set: function (value) {
  45287. var mousewheel = this.inputs.attached["mousewheel"];
  45288. if (mousewheel)
  45289. mousewheel.wheelDeltaPercentage = value;
  45290. },
  45291. enumerable: true,
  45292. configurable: true
  45293. });
  45294. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  45295. get: function () {
  45296. return this._bouncingBehavior;
  45297. },
  45298. enumerable: true,
  45299. configurable: true
  45300. });
  45301. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  45302. get: function () {
  45303. return this._bouncingBehavior != null;
  45304. },
  45305. set: function (value) {
  45306. if (value === this.useBouncingBehavior) {
  45307. return;
  45308. }
  45309. if (value) {
  45310. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  45311. this.addBehavior(this._bouncingBehavior);
  45312. }
  45313. else if (this._bouncingBehavior) {
  45314. this.removeBehavior(this._bouncingBehavior);
  45315. this._bouncingBehavior = null;
  45316. }
  45317. },
  45318. enumerable: true,
  45319. configurable: true
  45320. });
  45321. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  45322. get: function () {
  45323. return this._framingBehavior;
  45324. },
  45325. enumerable: true,
  45326. configurable: true
  45327. });
  45328. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  45329. get: function () {
  45330. return this._framingBehavior != null;
  45331. },
  45332. set: function (value) {
  45333. if (value === this.useFramingBehavior) {
  45334. return;
  45335. }
  45336. if (value) {
  45337. this._framingBehavior = new BABYLON.FramingBehavior();
  45338. this.addBehavior(this._framingBehavior);
  45339. }
  45340. else if (this._framingBehavior) {
  45341. this.removeBehavior(this._framingBehavior);
  45342. this._framingBehavior = null;
  45343. }
  45344. },
  45345. enumerable: true,
  45346. configurable: true
  45347. });
  45348. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  45349. get: function () {
  45350. return this._autoRotationBehavior;
  45351. },
  45352. enumerable: true,
  45353. configurable: true
  45354. });
  45355. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  45356. get: function () {
  45357. return this._autoRotationBehavior != null;
  45358. },
  45359. set: function (value) {
  45360. if (value === this.useAutoRotationBehavior) {
  45361. return;
  45362. }
  45363. if (value) {
  45364. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  45365. this.addBehavior(this._autoRotationBehavior);
  45366. }
  45367. else if (this._autoRotationBehavior) {
  45368. this.removeBehavior(this._autoRotationBehavior);
  45369. this._autoRotationBehavior = null;
  45370. }
  45371. },
  45372. enumerable: true,
  45373. configurable: true
  45374. });
  45375. // Cache
  45376. ArcRotateCamera.prototype._initCache = function () {
  45377. _super.prototype._initCache.call(this);
  45378. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45379. this._cache.alpha = undefined;
  45380. this._cache.beta = undefined;
  45381. this._cache.radius = undefined;
  45382. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  45383. };
  45384. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  45385. if (!ignoreParentClass) {
  45386. _super.prototype._updateCache.call(this);
  45387. }
  45388. this._cache._target.copyFrom(this._getTargetPosition());
  45389. this._cache.alpha = this.alpha;
  45390. this._cache.beta = this.beta;
  45391. this._cache.radius = this.radius;
  45392. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  45393. };
  45394. ArcRotateCamera.prototype._getTargetPosition = function () {
  45395. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  45396. var pos = this._targetHost.getAbsolutePosition();
  45397. if (this._targetBoundingCenter) {
  45398. pos.addToRef(this._targetBoundingCenter, this._target);
  45399. }
  45400. else {
  45401. this._target.copyFrom(pos);
  45402. }
  45403. }
  45404. var lockedTargetPosition = this._getLockedTargetPosition();
  45405. if (lockedTargetPosition) {
  45406. return lockedTargetPosition;
  45407. }
  45408. return this._target;
  45409. };
  45410. ArcRotateCamera.prototype.storeState = function () {
  45411. this._storedAlpha = this.alpha;
  45412. this._storedBeta = this.beta;
  45413. this._storedRadius = this.radius;
  45414. this._storedTarget = this._getTargetPosition().clone();
  45415. return _super.prototype.storeState.call(this);
  45416. };
  45417. /**
  45418. * Restored camera state. You must call storeState() first
  45419. */
  45420. ArcRotateCamera.prototype._restoreStateValues = function () {
  45421. if (!_super.prototype._restoreStateValues.call(this)) {
  45422. return false;
  45423. }
  45424. this.alpha = this._storedAlpha;
  45425. this.beta = this._storedBeta;
  45426. this.radius = this._storedRadius;
  45427. this.setTarget(this._storedTarget.clone());
  45428. this.inertialAlphaOffset = 0;
  45429. this.inertialBetaOffset = 0;
  45430. this.inertialRadiusOffset = 0;
  45431. this.inertialPanningX = 0;
  45432. this.inertialPanningY = 0;
  45433. return true;
  45434. };
  45435. // Synchronized
  45436. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45437. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45438. return false;
  45439. return this._cache._target.equals(this._getTargetPosition())
  45440. && this._cache.alpha === this.alpha
  45441. && this._cache.beta === this.beta
  45442. && this._cache.radius === this.radius
  45443. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45444. };
  45445. // Methods
  45446. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45447. var _this = this;
  45448. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45449. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45450. this._useCtrlForPanning = useCtrlForPanning;
  45451. this._panningMouseButton = panningMouseButton;
  45452. this.inputs.attachElement(element, noPreventDefault);
  45453. this._reset = function () {
  45454. _this.inertialAlphaOffset = 0;
  45455. _this.inertialBetaOffset = 0;
  45456. _this.inertialRadiusOffset = 0;
  45457. _this.inertialPanningX = 0;
  45458. _this.inertialPanningY = 0;
  45459. };
  45460. };
  45461. ArcRotateCamera.prototype.detachControl = function (element) {
  45462. this.inputs.detachElement(element);
  45463. if (this._reset) {
  45464. this._reset();
  45465. }
  45466. };
  45467. ArcRotateCamera.prototype._checkInputs = function () {
  45468. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45469. if (this._collisionTriggered) {
  45470. return;
  45471. }
  45472. this.inputs.checkInputs();
  45473. // Inertia
  45474. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45475. if (this.getScene().useRightHandedSystem) {
  45476. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45477. }
  45478. else {
  45479. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45480. }
  45481. this.beta += this.inertialBetaOffset;
  45482. this.radius -= this.inertialRadiusOffset;
  45483. this.inertialAlphaOffset *= this.inertia;
  45484. this.inertialBetaOffset *= this.inertia;
  45485. this.inertialRadiusOffset *= this.inertia;
  45486. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45487. this.inertialAlphaOffset = 0;
  45488. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45489. this.inertialBetaOffset = 0;
  45490. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45491. this.inertialRadiusOffset = 0;
  45492. }
  45493. // Panning inertia
  45494. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45495. if (!this._localDirection) {
  45496. this._localDirection = BABYLON.Vector3.Zero();
  45497. this._transformedDirection = BABYLON.Vector3.Zero();
  45498. }
  45499. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45500. this._localDirection.multiplyInPlace(this.panningAxis);
  45501. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45502. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45503. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45504. if (!this.panningAxis.y) {
  45505. this._transformedDirection.y = 0;
  45506. }
  45507. if (!this._targetHost) {
  45508. if (this.panningDistanceLimit) {
  45509. this._transformedDirection.addInPlace(this._target);
  45510. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45511. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45512. this._target.copyFrom(this._transformedDirection);
  45513. }
  45514. }
  45515. else {
  45516. this._target.addInPlace(this._transformedDirection);
  45517. }
  45518. }
  45519. this.inertialPanningX *= this.panningInertia;
  45520. this.inertialPanningY *= this.panningInertia;
  45521. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45522. this.inertialPanningX = 0;
  45523. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45524. this.inertialPanningY = 0;
  45525. }
  45526. // Limits
  45527. this._checkLimits();
  45528. _super.prototype._checkInputs.call(this);
  45529. };
  45530. ArcRotateCamera.prototype._checkLimits = function () {
  45531. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45532. if (this.allowUpsideDown && this.beta > Math.PI) {
  45533. this.beta = this.beta - (2 * Math.PI);
  45534. }
  45535. }
  45536. else {
  45537. if (this.beta < this.lowerBetaLimit) {
  45538. this.beta = this.lowerBetaLimit;
  45539. }
  45540. }
  45541. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45542. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45543. this.beta = this.beta + (2 * Math.PI);
  45544. }
  45545. }
  45546. else {
  45547. if (this.beta > this.upperBetaLimit) {
  45548. this.beta = this.upperBetaLimit;
  45549. }
  45550. }
  45551. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45552. this.alpha = this.lowerAlphaLimit;
  45553. }
  45554. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45555. this.alpha = this.upperAlphaLimit;
  45556. }
  45557. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45558. this.radius = this.lowerRadiusLimit;
  45559. }
  45560. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45561. this.radius = this.upperRadiusLimit;
  45562. }
  45563. };
  45564. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45565. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45566. this.radius = this._computationVector.length();
  45567. if (this.radius === 0) {
  45568. this.radius = 0.0001; // Just to avoid division by zero
  45569. }
  45570. // Alpha
  45571. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45572. if (this._computationVector.z < 0) {
  45573. this.alpha = 2 * Math.PI - this.alpha;
  45574. }
  45575. // Beta
  45576. this.beta = Math.acos(this._computationVector.y / this.radius);
  45577. this._checkLimits();
  45578. };
  45579. ArcRotateCamera.prototype.setPosition = function (position) {
  45580. if (this.position.equals(position)) {
  45581. return;
  45582. }
  45583. this.position.copyFrom(position);
  45584. this.rebuildAnglesAndRadius();
  45585. };
  45586. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45587. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45588. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45589. if (target.getBoundingInfo) {
  45590. if (toBoundingCenter) {
  45591. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45592. }
  45593. else {
  45594. this._targetBoundingCenter = null;
  45595. }
  45596. this._targetHost = target;
  45597. this._target = this._getTargetPosition();
  45598. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45599. }
  45600. else {
  45601. var newTarget = target;
  45602. var currentTarget = this._getTargetPosition();
  45603. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45604. return;
  45605. }
  45606. this._targetHost = null;
  45607. this._target = newTarget;
  45608. this._targetBoundingCenter = null;
  45609. this.onMeshTargetChangedObservable.notifyObservers(null);
  45610. }
  45611. this.rebuildAnglesAndRadius();
  45612. };
  45613. ArcRotateCamera.prototype._getViewMatrix = function () {
  45614. // Compute
  45615. var cosa = Math.cos(this.alpha);
  45616. var sina = Math.sin(this.alpha);
  45617. var cosb = Math.cos(this.beta);
  45618. var sinb = Math.sin(this.beta);
  45619. if (sinb === 0) {
  45620. sinb = 0.0001;
  45621. }
  45622. var target = this._getTargetPosition();
  45623. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45624. target.addToRef(this._computationVector, this._newPosition);
  45625. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45626. if (!this._collider) {
  45627. this._collider = new BABYLON.Collider();
  45628. }
  45629. this._collider._radius = this.collisionRadius;
  45630. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45631. this._collisionTriggered = true;
  45632. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45633. }
  45634. else {
  45635. this.position.copyFrom(this._newPosition);
  45636. var up = this.upVector;
  45637. if (this.allowUpsideDown && sinb < 0) {
  45638. up = up.clone();
  45639. up = up.negate();
  45640. }
  45641. if (this.getScene().useRightHandedSystem) {
  45642. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45643. }
  45644. else {
  45645. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45646. }
  45647. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45648. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45649. }
  45650. this._currentTarget = target;
  45651. return this._viewMatrix;
  45652. };
  45653. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45654. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45655. meshes = meshes || this.getScene().meshes;
  45656. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45657. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45658. this.radius = distance * this.zoomOnFactor;
  45659. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45660. };
  45661. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45662. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45663. var meshesOrMinMaxVector;
  45664. var distance;
  45665. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45666. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45667. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45668. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45669. }
  45670. else {
  45671. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45672. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45673. distance = minMaxVectorAndDistance.distance;
  45674. }
  45675. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45676. if (!doNotUpdateMaxZ) {
  45677. this.maxZ = distance * 2;
  45678. }
  45679. };
  45680. /**
  45681. * @override
  45682. * Override Camera.createRigCamera
  45683. */
  45684. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45685. var alphaShift = 0;
  45686. switch (this.cameraRigMode) {
  45687. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45688. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45689. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45690. case BABYLON.Camera.RIG_MODE_VR:
  45691. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45692. break;
  45693. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45694. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45695. break;
  45696. }
  45697. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45698. rigCam._cameraRigParams = {};
  45699. return rigCam;
  45700. };
  45701. /**
  45702. * @override
  45703. * Override Camera._updateRigCameras
  45704. */
  45705. ArcRotateCamera.prototype._updateRigCameras = function () {
  45706. var camLeft = this._rigCameras[0];
  45707. var camRight = this._rigCameras[1];
  45708. camLeft.beta = camRight.beta = this.beta;
  45709. camLeft.radius = camRight.radius = this.radius;
  45710. switch (this.cameraRigMode) {
  45711. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45712. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45713. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45714. case BABYLON.Camera.RIG_MODE_VR:
  45715. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45716. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45717. break;
  45718. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45719. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45720. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45721. break;
  45722. }
  45723. _super.prototype._updateRigCameras.call(this);
  45724. };
  45725. ArcRotateCamera.prototype.dispose = function () {
  45726. this.inputs.clear();
  45727. _super.prototype.dispose.call(this);
  45728. };
  45729. ArcRotateCamera.prototype.getClassName = function () {
  45730. return "ArcRotateCamera";
  45731. };
  45732. __decorate([
  45733. BABYLON.serialize()
  45734. ], ArcRotateCamera.prototype, "alpha", void 0);
  45735. __decorate([
  45736. BABYLON.serialize()
  45737. ], ArcRotateCamera.prototype, "beta", void 0);
  45738. __decorate([
  45739. BABYLON.serialize()
  45740. ], ArcRotateCamera.prototype, "radius", void 0);
  45741. __decorate([
  45742. BABYLON.serializeAsVector3("target")
  45743. ], ArcRotateCamera.prototype, "_target", void 0);
  45744. __decorate([
  45745. BABYLON.serialize()
  45746. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45747. __decorate([
  45748. BABYLON.serialize()
  45749. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45750. __decorate([
  45751. BABYLON.serialize()
  45752. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45753. __decorate([
  45754. BABYLON.serialize()
  45755. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45756. __decorate([
  45757. BABYLON.serialize()
  45758. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45759. __decorate([
  45760. BABYLON.serialize()
  45761. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45762. __decorate([
  45763. BABYLON.serialize()
  45764. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45765. __decorate([
  45766. BABYLON.serialize()
  45767. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45768. __decorate([
  45769. BABYLON.serialize()
  45770. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45771. __decorate([
  45772. BABYLON.serialize()
  45773. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45774. __decorate([
  45775. BABYLON.serialize()
  45776. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45777. __decorate([
  45778. BABYLON.serialize()
  45779. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45780. __decorate([
  45781. BABYLON.serialize()
  45782. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45783. __decorate([
  45784. BABYLON.serializeAsVector3()
  45785. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45786. __decorate([
  45787. BABYLON.serialize()
  45788. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45789. __decorate([
  45790. BABYLON.serialize()
  45791. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45792. __decorate([
  45793. BABYLON.serialize()
  45794. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45795. return ArcRotateCamera;
  45796. }(BABYLON.TargetCamera));
  45797. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45798. })(BABYLON || (BABYLON = {}));
  45799. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45800. "use strict";
  45801. var BABYLON;
  45802. (function (BABYLON) {
  45803. /**
  45804. * The HemisphericLight simulates the ambient environment light,
  45805. * so the passed direction is the light reflection direction, not the incoming direction.
  45806. */
  45807. var HemisphericLight = /** @class */ (function (_super) {
  45808. __extends(HemisphericLight, _super);
  45809. /**
  45810. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45811. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45812. * The HemisphericLight can't cast shadows.
  45813. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45814. * @param name The friendly name of the light
  45815. * @param direction The direction of the light reflection
  45816. * @param scene The scene the light belongs to
  45817. */
  45818. function HemisphericLight(name, direction, scene) {
  45819. var _this = _super.call(this, name, scene) || this;
  45820. /**
  45821. * The groundColor is the light in the opposite direction to the one specified during creation.
  45822. * 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.
  45823. */
  45824. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45825. _this.direction = direction || BABYLON.Vector3.Up();
  45826. return _this;
  45827. }
  45828. HemisphericLight.prototype._buildUniformLayout = function () {
  45829. this._uniformBuffer.addUniform("vLightData", 4);
  45830. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45831. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45832. this._uniformBuffer.addUniform("vLightGround", 3);
  45833. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45834. this._uniformBuffer.addUniform("depthValues", 2);
  45835. this._uniformBuffer.create();
  45836. };
  45837. /**
  45838. * Returns the string "HemisphericLight".
  45839. * @return The class name
  45840. */
  45841. HemisphericLight.prototype.getClassName = function () {
  45842. return "HemisphericLight";
  45843. };
  45844. /**
  45845. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45846. * Returns the updated direction.
  45847. * @param target The target the direction should point to
  45848. * @return The computed direction
  45849. */
  45850. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45851. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45852. return this.direction;
  45853. };
  45854. /**
  45855. * Returns the shadow generator associated to the light.
  45856. * @returns Always null for hemispheric lights because it does not support shadows.
  45857. */
  45858. HemisphericLight.prototype.getShadowGenerator = function () {
  45859. return null;
  45860. };
  45861. /**
  45862. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45863. * @param effect The effect to update
  45864. * @param lightIndex The index of the light in the effect to update
  45865. * @returns The hemispheric light
  45866. */
  45867. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45868. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45869. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45870. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45871. return this;
  45872. };
  45873. /**
  45874. * @ignore internal use only.
  45875. */
  45876. HemisphericLight.prototype._getWorldMatrix = function () {
  45877. if (!this._worldMatrix) {
  45878. this._worldMatrix = BABYLON.Matrix.Identity();
  45879. }
  45880. return this._worldMatrix;
  45881. };
  45882. /**
  45883. * Returns the integer 3.
  45884. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45885. */
  45886. HemisphericLight.prototype.getTypeID = function () {
  45887. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45888. };
  45889. __decorate([
  45890. BABYLON.serializeAsColor3()
  45891. ], HemisphericLight.prototype, "groundColor", void 0);
  45892. __decorate([
  45893. BABYLON.serializeAsVector3()
  45894. ], HemisphericLight.prototype, "direction", void 0);
  45895. return HemisphericLight;
  45896. }(BABYLON.Light));
  45897. BABYLON.HemisphericLight = HemisphericLight;
  45898. })(BABYLON || (BABYLON = {}));
  45899. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45900. "use strict";
  45901. var BABYLON;
  45902. (function (BABYLON) {
  45903. /**
  45904. * Base implementation of @see IShadowLight
  45905. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45906. */
  45907. var ShadowLight = /** @class */ (function (_super) {
  45908. __extends(ShadowLight, _super);
  45909. function ShadowLight() {
  45910. var _this = _super !== null && _super.apply(this, arguments) || this;
  45911. _this._needProjectionMatrixCompute = true;
  45912. return _this;
  45913. }
  45914. ShadowLight.prototype._setPosition = function (value) {
  45915. this._position = value;
  45916. };
  45917. Object.defineProperty(ShadowLight.prototype, "position", {
  45918. /**
  45919. * Sets the position the shadow will be casted from. Also use as the light position for both
  45920. * point and spot lights.
  45921. */
  45922. get: function () {
  45923. return this._position;
  45924. },
  45925. /**
  45926. * Sets the position the shadow will be casted from. Also use as the light position for both
  45927. * point and spot lights.
  45928. */
  45929. set: function (value) {
  45930. this._setPosition(value);
  45931. },
  45932. enumerable: true,
  45933. configurable: true
  45934. });
  45935. ShadowLight.prototype._setDirection = function (value) {
  45936. this._direction = value;
  45937. };
  45938. Object.defineProperty(ShadowLight.prototype, "direction", {
  45939. /**
  45940. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45941. * Also use as the light direction on spot and directional lights.
  45942. */
  45943. get: function () {
  45944. return this._direction;
  45945. },
  45946. /**
  45947. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45948. * Also use as the light direction on spot and directional lights.
  45949. */
  45950. set: function (value) {
  45951. this._setDirection(value);
  45952. },
  45953. enumerable: true,
  45954. configurable: true
  45955. });
  45956. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45957. /**
  45958. * Gets the shadow projection clipping minimum z value.
  45959. */
  45960. get: function () {
  45961. return this._shadowMinZ;
  45962. },
  45963. /**
  45964. * Sets the shadow projection clipping minimum z value.
  45965. */
  45966. set: function (value) {
  45967. this._shadowMinZ = value;
  45968. this.forceProjectionMatrixCompute();
  45969. },
  45970. enumerable: true,
  45971. configurable: true
  45972. });
  45973. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45974. /**
  45975. * Sets the shadow projection clipping maximum z value.
  45976. */
  45977. get: function () {
  45978. return this._shadowMaxZ;
  45979. },
  45980. /**
  45981. * Gets the shadow projection clipping maximum z value.
  45982. */
  45983. set: function (value) {
  45984. this._shadowMaxZ = value;
  45985. this.forceProjectionMatrixCompute();
  45986. },
  45987. enumerable: true,
  45988. configurable: true
  45989. });
  45990. /**
  45991. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45992. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45993. */
  45994. ShadowLight.prototype.computeTransformedInformation = function () {
  45995. if (this.parent && this.parent.getWorldMatrix) {
  45996. if (!this.transformedPosition) {
  45997. this.transformedPosition = BABYLON.Vector3.Zero();
  45998. }
  45999. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  46000. // In case the direction is present.
  46001. if (this.direction) {
  46002. if (!this.transformedDirection) {
  46003. this.transformedDirection = BABYLON.Vector3.Zero();
  46004. }
  46005. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  46006. }
  46007. return true;
  46008. }
  46009. return false;
  46010. };
  46011. /**
  46012. * Return the depth scale used for the shadow map.
  46013. * @returns the depth scale.
  46014. */
  46015. ShadowLight.prototype.getDepthScale = function () {
  46016. return 50.0;
  46017. };
  46018. /**
  46019. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  46020. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46021. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46022. */
  46023. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  46024. return this.transformedDirection ? this.transformedDirection : this.direction;
  46025. };
  46026. /**
  46027. * Returns the ShadowLight absolute position in the World.
  46028. * @returns the position vector in world space
  46029. */
  46030. ShadowLight.prototype.getAbsolutePosition = function () {
  46031. return this.transformedPosition ? this.transformedPosition : this.position;
  46032. };
  46033. /**
  46034. * Sets the ShadowLight direction toward the passed target.
  46035. * @param target The point tot target in local space
  46036. * @returns the updated ShadowLight direction
  46037. */
  46038. ShadowLight.prototype.setDirectionToTarget = function (target) {
  46039. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  46040. return this.direction;
  46041. };
  46042. /**
  46043. * Returns the light rotation in euler definition.
  46044. * @returns the x y z rotation in local space.
  46045. */
  46046. ShadowLight.prototype.getRotation = function () {
  46047. this.direction.normalize();
  46048. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  46049. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  46050. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  46051. };
  46052. /**
  46053. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  46054. * @returns true if a cube texture needs to be use
  46055. */
  46056. ShadowLight.prototype.needCube = function () {
  46057. return false;
  46058. };
  46059. /**
  46060. * Detects if the projection matrix requires to be recomputed this frame.
  46061. * @returns true if it requires to be recomputed otherwise, false.
  46062. */
  46063. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  46064. return this._needProjectionMatrixCompute;
  46065. };
  46066. /**
  46067. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  46068. */
  46069. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  46070. this._needProjectionMatrixCompute = true;
  46071. };
  46072. /**
  46073. * Get the world matrix of the sahdow lights.
  46074. * @ignore Internal Use Only
  46075. */
  46076. ShadowLight.prototype._getWorldMatrix = function () {
  46077. if (!this._worldMatrix) {
  46078. this._worldMatrix = BABYLON.Matrix.Identity();
  46079. }
  46080. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  46081. return this._worldMatrix;
  46082. };
  46083. /**
  46084. * Gets the minZ used for shadow according to both the scene and the light.
  46085. * @param activeCamera The camera we are returning the min for
  46086. * @returns the depth min z
  46087. */
  46088. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  46089. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  46090. };
  46091. /**
  46092. * Gets the maxZ used for shadow according to both the scene and the light.
  46093. * @param activeCamera The camera we are returning the max for
  46094. * @returns the depth max z
  46095. */
  46096. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  46097. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  46098. };
  46099. /**
  46100. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  46101. * @param matrix The materix to updated with the projection information
  46102. * @param viewMatrix The transform matrix of the light
  46103. * @param renderList The list of mesh to render in the map
  46104. * @returns The current light
  46105. */
  46106. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46107. if (this.customProjectionMatrixBuilder) {
  46108. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  46109. }
  46110. else {
  46111. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46112. }
  46113. return this;
  46114. };
  46115. __decorate([
  46116. BABYLON.serializeAsVector3()
  46117. ], ShadowLight.prototype, "position", null);
  46118. __decorate([
  46119. BABYLON.serializeAsVector3()
  46120. ], ShadowLight.prototype, "direction", null);
  46121. __decorate([
  46122. BABYLON.serialize()
  46123. ], ShadowLight.prototype, "shadowMinZ", null);
  46124. __decorate([
  46125. BABYLON.serialize()
  46126. ], ShadowLight.prototype, "shadowMaxZ", null);
  46127. return ShadowLight;
  46128. }(BABYLON.Light));
  46129. BABYLON.ShadowLight = ShadowLight;
  46130. })(BABYLON || (BABYLON = {}));
  46131. //# sourceMappingURL=babylon.shadowLight.js.map
  46132. "use strict";
  46133. var BABYLON;
  46134. (function (BABYLON) {
  46135. /**
  46136. * A point light is a light defined by an unique point in world space.
  46137. * The light is emitted in every direction from this point.
  46138. * A good example of a point light is a standard light bulb.
  46139. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46140. */
  46141. var PointLight = /** @class */ (function (_super) {
  46142. __extends(PointLight, _super);
  46143. /**
  46144. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  46145. * A PointLight emits the light in every direction.
  46146. * It can cast shadows.
  46147. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  46148. * ```javascript
  46149. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  46150. * ```
  46151. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46152. * @param name The light friendly name
  46153. * @param position The position of the point light in the scene
  46154. * @param scene The scene the lights belongs to
  46155. */
  46156. function PointLight(name, position, scene) {
  46157. var _this = _super.call(this, name, scene) || this;
  46158. _this._shadowAngle = Math.PI / 2;
  46159. _this.position = position;
  46160. return _this;
  46161. }
  46162. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  46163. /**
  46164. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46165. * This specifies what angle the shadow will use to be created.
  46166. *
  46167. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46168. */
  46169. get: function () {
  46170. return this._shadowAngle;
  46171. },
  46172. /**
  46173. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46174. * This specifies what angle the shadow will use to be created.
  46175. *
  46176. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46177. */
  46178. set: function (value) {
  46179. this._shadowAngle = value;
  46180. this.forceProjectionMatrixCompute();
  46181. },
  46182. enumerable: true,
  46183. configurable: true
  46184. });
  46185. Object.defineProperty(PointLight.prototype, "direction", {
  46186. /**
  46187. * Gets the direction if it has been set.
  46188. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46189. */
  46190. get: function () {
  46191. return this._direction;
  46192. },
  46193. /**
  46194. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46195. */
  46196. set: function (value) {
  46197. var previousNeedCube = this.needCube();
  46198. this._direction = value;
  46199. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  46200. this._shadowGenerator.recreateShadowMap();
  46201. }
  46202. },
  46203. enumerable: true,
  46204. configurable: true
  46205. });
  46206. /**
  46207. * Returns the string "PointLight"
  46208. * @returns the class name
  46209. */
  46210. PointLight.prototype.getClassName = function () {
  46211. return "PointLight";
  46212. };
  46213. /**
  46214. * Returns the integer 0.
  46215. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46216. */
  46217. PointLight.prototype.getTypeID = function () {
  46218. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  46219. };
  46220. /**
  46221. * Specifies wether or not the shadowmap should be a cube texture.
  46222. * @returns true if the shadowmap needs to be a cube texture.
  46223. */
  46224. PointLight.prototype.needCube = function () {
  46225. return !this.direction;
  46226. };
  46227. /**
  46228. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  46229. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46230. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46231. */
  46232. PointLight.prototype.getShadowDirection = function (faceIndex) {
  46233. if (this.direction) {
  46234. return _super.prototype.getShadowDirection.call(this, faceIndex);
  46235. }
  46236. else {
  46237. switch (faceIndex) {
  46238. case 0:
  46239. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  46240. case 1:
  46241. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  46242. case 2:
  46243. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  46244. case 3:
  46245. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  46246. case 4:
  46247. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  46248. case 5:
  46249. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  46250. }
  46251. }
  46252. return BABYLON.Vector3.Zero();
  46253. };
  46254. /**
  46255. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  46256. * - fov = PI / 2
  46257. * - aspect ratio : 1.0
  46258. * - z-near and far equal to the active camera minZ and maxZ.
  46259. * Returns the PointLight.
  46260. */
  46261. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46262. var activeCamera = this.getScene().activeCamera;
  46263. if (!activeCamera) {
  46264. return;
  46265. }
  46266. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46267. };
  46268. PointLight.prototype._buildUniformLayout = function () {
  46269. this._uniformBuffer.addUniform("vLightData", 4);
  46270. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46271. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46272. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46273. this._uniformBuffer.addUniform("depthValues", 2);
  46274. this._uniformBuffer.create();
  46275. };
  46276. /**
  46277. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  46278. * @param effect The effect to update
  46279. * @param lightIndex The index of the light in the effect to update
  46280. * @returns The point light
  46281. */
  46282. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  46283. if (this.computeTransformedInformation()) {
  46284. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  46285. return this;
  46286. }
  46287. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  46288. return this;
  46289. };
  46290. __decorate([
  46291. BABYLON.serialize()
  46292. ], PointLight.prototype, "shadowAngle", null);
  46293. return PointLight;
  46294. }(BABYLON.ShadowLight));
  46295. BABYLON.PointLight = PointLight;
  46296. })(BABYLON || (BABYLON = {}));
  46297. //# sourceMappingURL=babylon.pointLight.js.map
  46298. "use strict";
  46299. var BABYLON;
  46300. (function (BABYLON) {
  46301. /**
  46302. * A directional light is defined by a direction (what a surprise!).
  46303. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  46304. * 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.
  46305. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46306. */
  46307. var DirectionalLight = /** @class */ (function (_super) {
  46308. __extends(DirectionalLight, _super);
  46309. /**
  46310. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  46311. * The directional light is emitted from everywhere in the given direction.
  46312. * It can cast shawdows.
  46313. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46314. * @param name The friendly name of the light
  46315. * @param direction The direction of the light
  46316. * @param scene The scene the light belongs to
  46317. */
  46318. function DirectionalLight(name, direction, scene) {
  46319. var _this = _super.call(this, name, scene) || this;
  46320. _this._shadowFrustumSize = 0;
  46321. _this._shadowOrthoScale = 0.1;
  46322. /**
  46323. * Automatically compute the projection matrix to best fit (including all the casters)
  46324. * on each frame.
  46325. */
  46326. _this.autoUpdateExtends = true;
  46327. // Cache
  46328. _this._orthoLeft = Number.MAX_VALUE;
  46329. _this._orthoRight = Number.MIN_VALUE;
  46330. _this._orthoTop = Number.MIN_VALUE;
  46331. _this._orthoBottom = Number.MAX_VALUE;
  46332. _this.position = direction.scale(-1.0);
  46333. _this.direction = direction;
  46334. return _this;
  46335. }
  46336. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  46337. /**
  46338. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  46339. */
  46340. get: function () {
  46341. return this._shadowFrustumSize;
  46342. },
  46343. /**
  46344. * Specifies a fix frustum size for the shadow generation.
  46345. */
  46346. set: function (value) {
  46347. this._shadowFrustumSize = value;
  46348. this.forceProjectionMatrixCompute();
  46349. },
  46350. enumerable: true,
  46351. configurable: true
  46352. });
  46353. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  46354. /**
  46355. * Gets the shadow projection scale against the optimal computed one.
  46356. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46357. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46358. */
  46359. get: function () {
  46360. return this._shadowOrthoScale;
  46361. },
  46362. /**
  46363. * Sets the shadow projection scale against the optimal computed one.
  46364. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46365. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46366. */
  46367. set: function (value) {
  46368. this._shadowOrthoScale = value;
  46369. this.forceProjectionMatrixCompute();
  46370. },
  46371. enumerable: true,
  46372. configurable: true
  46373. });
  46374. /**
  46375. * Returns the string "DirectionalLight".
  46376. * @return The class name
  46377. */
  46378. DirectionalLight.prototype.getClassName = function () {
  46379. return "DirectionalLight";
  46380. };
  46381. /**
  46382. * Returns the integer 1.
  46383. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46384. */
  46385. DirectionalLight.prototype.getTypeID = function () {
  46386. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  46387. };
  46388. /**
  46389. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  46390. * Returns the DirectionalLight Shadow projection matrix.
  46391. */
  46392. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46393. if (this.shadowFrustumSize > 0) {
  46394. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  46395. }
  46396. else {
  46397. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46398. }
  46399. };
  46400. /**
  46401. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  46402. * Returns the DirectionalLight Shadow projection matrix.
  46403. */
  46404. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  46405. var activeCamera = this.getScene().activeCamera;
  46406. if (!activeCamera) {
  46407. return;
  46408. }
  46409. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46410. };
  46411. /**
  46412. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  46413. * Returns the DirectionalLight Shadow projection matrix.
  46414. */
  46415. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46416. var activeCamera = this.getScene().activeCamera;
  46417. if (!activeCamera) {
  46418. return;
  46419. }
  46420. // Check extends
  46421. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  46422. var tempVector3 = BABYLON.Vector3.Zero();
  46423. this._orthoLeft = Number.MAX_VALUE;
  46424. this._orthoRight = Number.MIN_VALUE;
  46425. this._orthoTop = Number.MIN_VALUE;
  46426. this._orthoBottom = Number.MAX_VALUE;
  46427. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46428. var mesh = renderList[meshIndex];
  46429. if (!mesh) {
  46430. continue;
  46431. }
  46432. var boundingInfo = mesh.getBoundingInfo();
  46433. var boundingBox = boundingInfo.boundingBox;
  46434. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46435. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46436. if (tempVector3.x < this._orthoLeft)
  46437. this._orthoLeft = tempVector3.x;
  46438. if (tempVector3.y < this._orthoBottom)
  46439. this._orthoBottom = tempVector3.y;
  46440. if (tempVector3.x > this._orthoRight)
  46441. this._orthoRight = tempVector3.x;
  46442. if (tempVector3.y > this._orthoTop)
  46443. this._orthoTop = tempVector3.y;
  46444. }
  46445. }
  46446. }
  46447. var xOffset = this._orthoRight - this._orthoLeft;
  46448. var yOffset = this._orthoTop - this._orthoBottom;
  46449. 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);
  46450. };
  46451. DirectionalLight.prototype._buildUniformLayout = function () {
  46452. this._uniformBuffer.addUniform("vLightData", 4);
  46453. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46454. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46455. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46456. this._uniformBuffer.addUniform("depthValues", 2);
  46457. this._uniformBuffer.create();
  46458. };
  46459. /**
  46460. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46461. * @param effect The effect to update
  46462. * @param lightIndex The index of the light in the effect to update
  46463. * @returns The directional light
  46464. */
  46465. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46466. if (this.computeTransformedInformation()) {
  46467. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46468. return this;
  46469. }
  46470. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46471. return this;
  46472. };
  46473. /**
  46474. * Gets the minZ used for shadow according to both the scene and the light.
  46475. *
  46476. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46477. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46478. * @param activeCamera The camera we are returning the min for
  46479. * @returns the depth min z
  46480. */
  46481. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46482. return 1;
  46483. };
  46484. /**
  46485. * Gets the maxZ used for shadow according to both the scene and the light.
  46486. *
  46487. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46488. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46489. * @param activeCamera The camera we are returning the max for
  46490. * @returns the depth max z
  46491. */
  46492. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46493. return 1;
  46494. };
  46495. __decorate([
  46496. BABYLON.serialize()
  46497. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46498. __decorate([
  46499. BABYLON.serialize()
  46500. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46501. __decorate([
  46502. BABYLON.serialize()
  46503. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46504. return DirectionalLight;
  46505. }(BABYLON.ShadowLight));
  46506. BABYLON.DirectionalLight = DirectionalLight;
  46507. })(BABYLON || (BABYLON = {}));
  46508. //# sourceMappingURL=babylon.directionalLight.js.map
  46509. "use strict";
  46510. var BABYLON;
  46511. (function (BABYLON) {
  46512. /**
  46513. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46514. * These values define a cone of light starting from the position, emitting toward the direction.
  46515. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46516. * and the exponent defines the speed of the decay of the light with distance (reach).
  46517. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46518. */
  46519. var SpotLight = /** @class */ (function (_super) {
  46520. __extends(SpotLight, _super);
  46521. /**
  46522. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46523. * It can cast shadows.
  46524. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46525. * @param name The light friendly name
  46526. * @param position The position of the spot light in the scene
  46527. * @param direction The direction of the light in the scene
  46528. * @param angle The cone angle of the light in Radians
  46529. * @param exponent The light decay speed with the distance from the emission spot
  46530. * @param scene The scene the lights belongs to
  46531. */
  46532. function SpotLight(name, position, direction, angle, exponent, scene) {
  46533. var _this = _super.call(this, name, scene) || this;
  46534. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46535. _this._projectionTextureLightNear = 1e-6;
  46536. _this._projectionTextureLightFar = 1000.0;
  46537. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46538. _this._projectionTextureViewLightDirty = true;
  46539. _this._projectionTextureProjectionLightDirty = true;
  46540. _this._projectionTextureDirty = true;
  46541. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46542. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46543. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46544. _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);
  46545. _this.position = position;
  46546. _this.direction = direction;
  46547. _this.angle = angle;
  46548. _this.exponent = exponent;
  46549. return _this;
  46550. }
  46551. Object.defineProperty(SpotLight.prototype, "angle", {
  46552. /**
  46553. * Gets the cone angle of the spot light in Radians.
  46554. */
  46555. get: function () {
  46556. return this._angle;
  46557. },
  46558. /**
  46559. * Sets the cone angle of the spot light in Radians.
  46560. */
  46561. set: function (value) {
  46562. this._angle = value;
  46563. this._projectionTextureProjectionLightDirty = true;
  46564. this.forceProjectionMatrixCompute();
  46565. },
  46566. enumerable: true,
  46567. configurable: true
  46568. });
  46569. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46570. /**
  46571. * Allows scaling the angle of the light for shadow generation only.
  46572. */
  46573. get: function () {
  46574. return this._shadowAngleScale;
  46575. },
  46576. /**
  46577. * Allows scaling the angle of the light for shadow generation only.
  46578. */
  46579. set: function (value) {
  46580. this._shadowAngleScale = value;
  46581. this.forceProjectionMatrixCompute();
  46582. },
  46583. enumerable: true,
  46584. configurable: true
  46585. });
  46586. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46587. /**
  46588. * Allows reading the projecton texture
  46589. */
  46590. get: function () {
  46591. return this._projectionTextureMatrix;
  46592. },
  46593. enumerable: true,
  46594. configurable: true
  46595. });
  46596. ;
  46597. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46598. /**
  46599. * Gets the near clip of the Spotlight for texture projection.
  46600. */
  46601. get: function () {
  46602. return this._projectionTextureLightNear;
  46603. },
  46604. /**
  46605. * Sets the near clip of the Spotlight for texture projection.
  46606. */
  46607. set: function (value) {
  46608. this._projectionTextureLightNear = value;
  46609. this._projectionTextureProjectionLightDirty = true;
  46610. },
  46611. enumerable: true,
  46612. configurable: true
  46613. });
  46614. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46615. /**
  46616. * Gets the far clip of the Spotlight for texture projection.
  46617. */
  46618. get: function () {
  46619. return this._projectionTextureLightFar;
  46620. },
  46621. /**
  46622. * Sets the far clip of the Spotlight for texture projection.
  46623. */
  46624. set: function (value) {
  46625. this._projectionTextureLightFar = value;
  46626. this._projectionTextureProjectionLightDirty = true;
  46627. },
  46628. enumerable: true,
  46629. configurable: true
  46630. });
  46631. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46632. /**
  46633. * Gets the Up vector of the Spotlight for texture projection.
  46634. */
  46635. get: function () {
  46636. return this._projectionTextureUpDirection;
  46637. },
  46638. /**
  46639. * Sets the Up vector of the Spotlight for texture projection.
  46640. */
  46641. set: function (value) {
  46642. this._projectionTextureUpDirection = value;
  46643. this._projectionTextureProjectionLightDirty = true;
  46644. },
  46645. enumerable: true,
  46646. configurable: true
  46647. });
  46648. ;
  46649. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46650. /**
  46651. * Gets the projection texture of the light.
  46652. */
  46653. get: function () {
  46654. return this._projectionTexture;
  46655. },
  46656. /**
  46657. * Sets the projection texture of the light.
  46658. */
  46659. set: function (value) {
  46660. this._projectionTexture = value;
  46661. this._projectionTextureDirty = true;
  46662. },
  46663. enumerable: true,
  46664. configurable: true
  46665. });
  46666. /**
  46667. * Returns the string "SpotLight".
  46668. * @returns the class name
  46669. */
  46670. SpotLight.prototype.getClassName = function () {
  46671. return "SpotLight";
  46672. };
  46673. /**
  46674. * Returns the integer 2.
  46675. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46676. */
  46677. SpotLight.prototype.getTypeID = function () {
  46678. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46679. };
  46680. /**
  46681. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46682. */
  46683. SpotLight.prototype._setDirection = function (value) {
  46684. _super.prototype._setDirection.call(this, value);
  46685. this._projectionTextureViewLightDirty = true;
  46686. };
  46687. /**
  46688. * Overrides the position setter to recompute the projection texture view light Matrix.
  46689. */
  46690. SpotLight.prototype._setPosition = function (value) {
  46691. _super.prototype._setPosition.call(this, value);
  46692. this._projectionTextureViewLightDirty = true;
  46693. };
  46694. /**
  46695. * 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.
  46696. * Returns the SpotLight.
  46697. */
  46698. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46699. var activeCamera = this.getScene().activeCamera;
  46700. if (!activeCamera) {
  46701. return;
  46702. }
  46703. this._shadowAngleScale = this._shadowAngleScale || 1;
  46704. var angle = this._shadowAngleScale * this._angle;
  46705. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46706. };
  46707. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46708. this._projectionTextureViewLightDirty = false;
  46709. this._projectionTextureDirty = true;
  46710. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46711. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46712. };
  46713. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46714. this._projectionTextureProjectionLightDirty = false;
  46715. this._projectionTextureDirty = true;
  46716. var light_far = this.projectionTextureLightFar;
  46717. var light_near = this.projectionTextureLightNear;
  46718. var P = light_far / (light_far - light_near);
  46719. var Q = -P * light_near;
  46720. var S = 1.0 / Math.tan(this._angle / 2.0);
  46721. var A = 1.0;
  46722. 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);
  46723. };
  46724. /**
  46725. * Main function for light texture projection matrix computing.
  46726. */
  46727. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46728. this._projectionTextureDirty = false;
  46729. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46730. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46731. };
  46732. SpotLight.prototype._buildUniformLayout = function () {
  46733. this._uniformBuffer.addUniform("vLightData", 4);
  46734. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46735. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46736. this._uniformBuffer.addUniform("vLightDirection", 3);
  46737. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46738. this._uniformBuffer.addUniform("depthValues", 2);
  46739. this._uniformBuffer.create();
  46740. };
  46741. /**
  46742. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46743. * @param effect The effect to update
  46744. * @param lightIndex The index of the light in the effect to update
  46745. * @returns The spot light
  46746. */
  46747. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46748. var normalizeDirection;
  46749. if (this.computeTransformedInformation()) {
  46750. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46751. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46752. }
  46753. else {
  46754. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46755. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46756. }
  46757. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46758. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46759. if (this._projectionTextureViewLightDirty) {
  46760. this._computeProjectionTextureViewLightMatrix();
  46761. }
  46762. if (this._projectionTextureProjectionLightDirty) {
  46763. this._computeProjectionTextureProjectionLightMatrix();
  46764. }
  46765. if (this._projectionTextureDirty) {
  46766. this._computeProjectionTextureMatrix();
  46767. }
  46768. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46769. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46770. }
  46771. return this;
  46772. };
  46773. /**
  46774. * Disposes the light and the associated resources.
  46775. */
  46776. SpotLight.prototype.dispose = function () {
  46777. _super.prototype.dispose.call(this);
  46778. if (this._projectionTexture) {
  46779. this._projectionTexture.dispose();
  46780. }
  46781. };
  46782. __decorate([
  46783. BABYLON.serialize()
  46784. ], SpotLight.prototype, "angle", null);
  46785. __decorate([
  46786. BABYLON.serialize()
  46787. ], SpotLight.prototype, "shadowAngleScale", null);
  46788. __decorate([
  46789. BABYLON.serialize()
  46790. ], SpotLight.prototype, "exponent", void 0);
  46791. __decorate([
  46792. BABYLON.serialize()
  46793. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46794. __decorate([
  46795. BABYLON.serialize()
  46796. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46797. __decorate([
  46798. BABYLON.serialize()
  46799. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46800. __decorate([
  46801. BABYLON.serializeAsTexture("projectedLightTexture")
  46802. ], SpotLight.prototype, "_projectionTexture", void 0);
  46803. return SpotLight;
  46804. }(BABYLON.ShadowLight));
  46805. BABYLON.SpotLight = SpotLight;
  46806. })(BABYLON || (BABYLON = {}));
  46807. //# sourceMappingURL=babylon.spotLight.js.map
  46808. "use strict";
  46809. var BABYLON;
  46810. (function (BABYLON) {
  46811. /**
  46812. * Class used to override all child animations of a given target
  46813. */
  46814. var AnimationPropertiesOverride = /** @class */ (function () {
  46815. function AnimationPropertiesOverride() {
  46816. /**
  46817. * Gets or sets a value indicating if animation blending must be used
  46818. */
  46819. this.enableBlending = false;
  46820. /**
  46821. * Gets or sets the blending speed to use when enableBlending is true
  46822. */
  46823. this.blendingSpeed = 0.01;
  46824. /**
  46825. * Gets or sets the default loop mode to use
  46826. */
  46827. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46828. }
  46829. return AnimationPropertiesOverride;
  46830. }());
  46831. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46832. })(BABYLON || (BABYLON = {}));
  46833. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46834. "use strict";
  46835. var BABYLON;
  46836. (function (BABYLON) {
  46837. var AnimationRange = /** @class */ (function () {
  46838. function AnimationRange(name, from, to) {
  46839. this.name = name;
  46840. this.from = from;
  46841. this.to = to;
  46842. }
  46843. AnimationRange.prototype.clone = function () {
  46844. return new AnimationRange(this.name, this.from, this.to);
  46845. };
  46846. return AnimationRange;
  46847. }());
  46848. BABYLON.AnimationRange = AnimationRange;
  46849. /**
  46850. * Composed of a frame, and an action function
  46851. */
  46852. var AnimationEvent = /** @class */ (function () {
  46853. function AnimationEvent(frame, action, onlyOnce) {
  46854. this.frame = frame;
  46855. this.action = action;
  46856. this.onlyOnce = onlyOnce;
  46857. this.isDone = false;
  46858. }
  46859. return AnimationEvent;
  46860. }());
  46861. BABYLON.AnimationEvent = AnimationEvent;
  46862. var PathCursor = /** @class */ (function () {
  46863. function PathCursor(path) {
  46864. this.path = path;
  46865. this._onchange = new Array();
  46866. this.value = 0;
  46867. this.animations = new Array();
  46868. }
  46869. PathCursor.prototype.getPoint = function () {
  46870. var point = this.path.getPointAtLengthPosition(this.value);
  46871. return new BABYLON.Vector3(point.x, 0, point.y);
  46872. };
  46873. PathCursor.prototype.moveAhead = function (step) {
  46874. if (step === void 0) { step = 0.002; }
  46875. this.move(step);
  46876. return this;
  46877. };
  46878. PathCursor.prototype.moveBack = function (step) {
  46879. if (step === void 0) { step = 0.002; }
  46880. this.move(-step);
  46881. return this;
  46882. };
  46883. PathCursor.prototype.move = function (step) {
  46884. if (Math.abs(step) > 1) {
  46885. throw "step size should be less than 1.";
  46886. }
  46887. this.value += step;
  46888. this.ensureLimits();
  46889. this.raiseOnChange();
  46890. return this;
  46891. };
  46892. PathCursor.prototype.ensureLimits = function () {
  46893. while (this.value > 1) {
  46894. this.value -= 1;
  46895. }
  46896. while (this.value < 0) {
  46897. this.value += 1;
  46898. }
  46899. return this;
  46900. };
  46901. // used by animation engine
  46902. PathCursor.prototype.raiseOnChange = function () {
  46903. var _this = this;
  46904. this._onchange.forEach(function (f) { return f(_this); });
  46905. return this;
  46906. };
  46907. PathCursor.prototype.onchange = function (f) {
  46908. this._onchange.push(f);
  46909. return this;
  46910. };
  46911. return PathCursor;
  46912. }());
  46913. BABYLON.PathCursor = PathCursor;
  46914. var AnimationKeyInterpolation;
  46915. (function (AnimationKeyInterpolation) {
  46916. /**
  46917. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46918. */
  46919. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46920. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46921. var Animation = /** @class */ (function () {
  46922. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46923. this.name = name;
  46924. this.targetProperty = targetProperty;
  46925. this.framePerSecond = framePerSecond;
  46926. this.dataType = dataType;
  46927. this.loopMode = loopMode;
  46928. this.enableBlending = enableBlending;
  46929. this._runtimeAnimations = new Array();
  46930. // The set of event that will be linked to this animation
  46931. this._events = new Array();
  46932. this.blendingSpeed = 0.01;
  46933. this._ranges = {};
  46934. this.targetPropertyPath = targetProperty.split(".");
  46935. this.dataType = dataType;
  46936. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46937. }
  46938. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46939. var dataType = undefined;
  46940. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46941. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46942. }
  46943. else if (from instanceof BABYLON.Quaternion) {
  46944. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46945. }
  46946. else if (from instanceof BABYLON.Vector3) {
  46947. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46948. }
  46949. else if (from instanceof BABYLON.Vector2) {
  46950. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46951. }
  46952. else if (from instanceof BABYLON.Color3) {
  46953. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46954. }
  46955. else if (from instanceof BABYLON.Size) {
  46956. dataType = Animation.ANIMATIONTYPE_SIZE;
  46957. }
  46958. if (dataType == undefined) {
  46959. return null;
  46960. }
  46961. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46962. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46963. animation.setKeys(keys);
  46964. if (easingFunction !== undefined) {
  46965. animation.setEasingFunction(easingFunction);
  46966. }
  46967. return animation;
  46968. };
  46969. /**
  46970. * Sets up an animation.
  46971. * @param property the property to animate
  46972. * @param animationType the animation type to apply
  46973. * @param easingFunction the easing function used in the animation
  46974. * @returns The created animation
  46975. */
  46976. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46977. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46978. animation.setEasingFunction(easingFunction);
  46979. return animation;
  46980. };
  46981. /**
  46982. * Create and start an animation on a node
  46983. * @param {string} name defines the name of the global animation that will be run on all nodes
  46984. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46985. * @param {string} targetProperty defines property to animate
  46986. * @param {number} framePerSecond defines the number of frame per second yo use
  46987. * @param {number} totalFrame defines the number of frames in total
  46988. * @param {any} from defines the initial value
  46989. * @param {any} to defines the final value
  46990. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46991. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46992. * @param onAnimationEnd defines the callback to call when animation end
  46993. * @returns the animatable created for this animation
  46994. */
  46995. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46996. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46997. if (!animation) {
  46998. return null;
  46999. }
  47000. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47001. };
  47002. /**
  47003. * Create and start an animation on a node and its descendants
  47004. * @param {string} name defines the name of the global animation that will be run on all nodes
  47005. * @param {BABYLON.Node} node defines the root node where the animation will take place
  47006. * @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.
  47007. * @param {string} targetProperty defines property to animate
  47008. * @param {number} framePerSecond defines the number of frame per second yo use
  47009. * @param {number} totalFrame defines the number of frames in total
  47010. * @param {any} from defines the initial value
  47011. * @param {any} to defines the final value
  47012. * @param {number} loopMode defines which loop mode you want to use (off by default)
  47013. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  47014. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  47015. * @returns the list of animatables created for all nodes
  47016. * @example https://www.babylonjs-playground.com/#MH0VLI
  47017. */
  47018. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47019. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47020. if (!animation) {
  47021. return null;
  47022. }
  47023. var scene = node.getScene();
  47024. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47025. };
  47026. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47027. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47028. if (!animation) {
  47029. return null;
  47030. }
  47031. node.animations.push(animation);
  47032. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47033. };
  47034. /**
  47035. * Transition property of the Camera to the target Value.
  47036. * @param property The property to transition
  47037. * @param targetValue The target Value of the property
  47038. * @param host The object where the property to animate belongs
  47039. * @param scene Scene used to run the animation
  47040. * @param frameRate Framerate (in frame/s) to use
  47041. * @param transition The transition type we want to use
  47042. * @param duration The duration of the animation, in milliseconds
  47043. * @param onAnimationEnd Call back trigger at the end of the animation.
  47044. */
  47045. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  47046. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  47047. if (duration <= 0) {
  47048. host[property] = targetValue;
  47049. if (onAnimationEnd) {
  47050. onAnimationEnd();
  47051. }
  47052. return null;
  47053. }
  47054. var endFrame = frameRate * (duration / 1000);
  47055. transition.setKeys([{
  47056. frame: 0,
  47057. value: host[property].clone ? host[property].clone() : host[property]
  47058. },
  47059. {
  47060. frame: endFrame,
  47061. value: targetValue
  47062. }]);
  47063. if (!host.animations) {
  47064. host.animations = [];
  47065. }
  47066. host.animations.push(transition);
  47067. var animation = scene.beginAnimation(host, 0, endFrame, false);
  47068. animation.onAnimationEnd = onAnimationEnd;
  47069. return animation;
  47070. };
  47071. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  47072. /**
  47073. * Return the array of runtime animations currently using this animation
  47074. */
  47075. get: function () {
  47076. return this._runtimeAnimations;
  47077. },
  47078. enumerable: true,
  47079. configurable: true
  47080. });
  47081. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  47082. get: function () {
  47083. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  47084. var runtimeAnimation = _a[_i];
  47085. if (!runtimeAnimation.isStopped) {
  47086. return true;
  47087. }
  47088. }
  47089. return false;
  47090. },
  47091. enumerable: true,
  47092. configurable: true
  47093. });
  47094. // Methods
  47095. /**
  47096. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  47097. */
  47098. Animation.prototype.toString = function (fullDetails) {
  47099. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  47100. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  47101. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  47102. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  47103. if (fullDetails) {
  47104. ret += ", Ranges: {";
  47105. var first = true;
  47106. for (var name in this._ranges) {
  47107. if (first) {
  47108. ret += ", ";
  47109. first = false;
  47110. }
  47111. ret += name;
  47112. }
  47113. ret += "}";
  47114. }
  47115. return ret;
  47116. };
  47117. /**
  47118. * Add an event to this animation.
  47119. */
  47120. Animation.prototype.addEvent = function (event) {
  47121. this._events.push(event);
  47122. };
  47123. /**
  47124. * Remove all events found at the given frame
  47125. * @param frame
  47126. */
  47127. Animation.prototype.removeEvents = function (frame) {
  47128. for (var index = 0; index < this._events.length; index++) {
  47129. if (this._events[index].frame === frame) {
  47130. this._events.splice(index, 1);
  47131. index--;
  47132. }
  47133. }
  47134. };
  47135. Animation.prototype.getEvents = function () {
  47136. return this._events;
  47137. };
  47138. Animation.prototype.createRange = function (name, from, to) {
  47139. // check name not already in use; could happen for bones after serialized
  47140. if (!this._ranges[name]) {
  47141. this._ranges[name] = new AnimationRange(name, from, to);
  47142. }
  47143. };
  47144. Animation.prototype.deleteRange = function (name, deleteFrames) {
  47145. if (deleteFrames === void 0) { deleteFrames = true; }
  47146. var range = this._ranges[name];
  47147. if (!range) {
  47148. return;
  47149. }
  47150. if (deleteFrames) {
  47151. var from = range.from;
  47152. var to = range.to;
  47153. // this loop MUST go high to low for multiple splices to work
  47154. for (var key = this._keys.length - 1; key >= 0; key--) {
  47155. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  47156. this._keys.splice(key, 1);
  47157. }
  47158. }
  47159. }
  47160. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  47161. };
  47162. Animation.prototype.getRange = function (name) {
  47163. return this._ranges[name];
  47164. };
  47165. Animation.prototype.getKeys = function () {
  47166. return this._keys;
  47167. };
  47168. Animation.prototype.getHighestFrame = function () {
  47169. var ret = 0;
  47170. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  47171. if (ret < this._keys[key].frame) {
  47172. ret = this._keys[key].frame;
  47173. }
  47174. }
  47175. return ret;
  47176. };
  47177. Animation.prototype.getEasingFunction = function () {
  47178. return this._easingFunction;
  47179. };
  47180. Animation.prototype.setEasingFunction = function (easingFunction) {
  47181. this._easingFunction = easingFunction;
  47182. };
  47183. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  47184. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  47185. };
  47186. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47187. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47188. };
  47189. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  47190. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  47191. };
  47192. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47193. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  47194. };
  47195. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  47196. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  47197. };
  47198. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47199. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47200. };
  47201. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  47202. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  47203. };
  47204. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47205. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47206. };
  47207. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  47208. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  47209. };
  47210. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  47211. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  47212. };
  47213. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  47214. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  47215. };
  47216. Animation.prototype.clone = function () {
  47217. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  47218. clone.enableBlending = this.enableBlending;
  47219. clone.blendingSpeed = this.blendingSpeed;
  47220. if (this._keys) {
  47221. clone.setKeys(this._keys);
  47222. }
  47223. if (this._ranges) {
  47224. clone._ranges = {};
  47225. for (var name in this._ranges) {
  47226. var range = this._ranges[name];
  47227. if (!range) {
  47228. continue;
  47229. }
  47230. clone._ranges[name] = range.clone();
  47231. }
  47232. }
  47233. return clone;
  47234. };
  47235. Animation.prototype.setKeys = function (values) {
  47236. this._keys = values.slice(0);
  47237. };
  47238. Animation.prototype.serialize = function () {
  47239. var serializationObject = {};
  47240. serializationObject.name = this.name;
  47241. serializationObject.property = this.targetProperty;
  47242. serializationObject.framePerSecond = this.framePerSecond;
  47243. serializationObject.dataType = this.dataType;
  47244. serializationObject.loopBehavior = this.loopMode;
  47245. serializationObject.enableBlending = this.enableBlending;
  47246. serializationObject.blendingSpeed = this.blendingSpeed;
  47247. var dataType = this.dataType;
  47248. serializationObject.keys = [];
  47249. var keys = this.getKeys();
  47250. for (var index = 0; index < keys.length; index++) {
  47251. var animationKey = keys[index];
  47252. var key = {};
  47253. key.frame = animationKey.frame;
  47254. switch (dataType) {
  47255. case Animation.ANIMATIONTYPE_FLOAT:
  47256. key.values = [animationKey.value];
  47257. break;
  47258. case Animation.ANIMATIONTYPE_QUATERNION:
  47259. case Animation.ANIMATIONTYPE_MATRIX:
  47260. case Animation.ANIMATIONTYPE_VECTOR3:
  47261. case Animation.ANIMATIONTYPE_COLOR3:
  47262. key.values = animationKey.value.asArray();
  47263. break;
  47264. }
  47265. serializationObject.keys.push(key);
  47266. }
  47267. serializationObject.ranges = [];
  47268. for (var name in this._ranges) {
  47269. var source = this._ranges[name];
  47270. if (!source) {
  47271. continue;
  47272. }
  47273. var range = {};
  47274. range.name = name;
  47275. range.from = source.from;
  47276. range.to = source.to;
  47277. serializationObject.ranges.push(range);
  47278. }
  47279. return serializationObject;
  47280. };
  47281. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  47282. get: function () {
  47283. return Animation._ANIMATIONTYPE_FLOAT;
  47284. },
  47285. enumerable: true,
  47286. configurable: true
  47287. });
  47288. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  47289. get: function () {
  47290. return Animation._ANIMATIONTYPE_VECTOR3;
  47291. },
  47292. enumerable: true,
  47293. configurable: true
  47294. });
  47295. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  47296. get: function () {
  47297. return Animation._ANIMATIONTYPE_VECTOR2;
  47298. },
  47299. enumerable: true,
  47300. configurable: true
  47301. });
  47302. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  47303. get: function () {
  47304. return Animation._ANIMATIONTYPE_SIZE;
  47305. },
  47306. enumerable: true,
  47307. configurable: true
  47308. });
  47309. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  47310. get: function () {
  47311. return Animation._ANIMATIONTYPE_QUATERNION;
  47312. },
  47313. enumerable: true,
  47314. configurable: true
  47315. });
  47316. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  47317. get: function () {
  47318. return Animation._ANIMATIONTYPE_MATRIX;
  47319. },
  47320. enumerable: true,
  47321. configurable: true
  47322. });
  47323. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  47324. get: function () {
  47325. return Animation._ANIMATIONTYPE_COLOR3;
  47326. },
  47327. enumerable: true,
  47328. configurable: true
  47329. });
  47330. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  47331. get: function () {
  47332. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  47333. },
  47334. enumerable: true,
  47335. configurable: true
  47336. });
  47337. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  47338. get: function () {
  47339. return Animation._ANIMATIONLOOPMODE_CYCLE;
  47340. },
  47341. enumerable: true,
  47342. configurable: true
  47343. });
  47344. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  47345. get: function () {
  47346. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  47347. },
  47348. enumerable: true,
  47349. configurable: true
  47350. });
  47351. Animation.Parse = function (parsedAnimation) {
  47352. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  47353. var dataType = parsedAnimation.dataType;
  47354. var keys = [];
  47355. var data;
  47356. var index;
  47357. if (parsedAnimation.enableBlending) {
  47358. animation.enableBlending = parsedAnimation.enableBlending;
  47359. }
  47360. if (parsedAnimation.blendingSpeed) {
  47361. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  47362. }
  47363. for (index = 0; index < parsedAnimation.keys.length; index++) {
  47364. var key = parsedAnimation.keys[index];
  47365. var inTangent;
  47366. var outTangent;
  47367. switch (dataType) {
  47368. case Animation.ANIMATIONTYPE_FLOAT:
  47369. data = key.values[0];
  47370. if (key.values.length >= 1) {
  47371. inTangent = key.values[1];
  47372. }
  47373. if (key.values.length >= 2) {
  47374. outTangent = key.values[2];
  47375. }
  47376. break;
  47377. case Animation.ANIMATIONTYPE_QUATERNION:
  47378. data = BABYLON.Quaternion.FromArray(key.values);
  47379. if (key.values.length >= 8) {
  47380. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  47381. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  47382. inTangent = _inTangent;
  47383. }
  47384. }
  47385. if (key.values.length >= 12) {
  47386. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  47387. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  47388. outTangent = _outTangent;
  47389. }
  47390. }
  47391. break;
  47392. case Animation.ANIMATIONTYPE_MATRIX:
  47393. data = BABYLON.Matrix.FromArray(key.values);
  47394. break;
  47395. case Animation.ANIMATIONTYPE_COLOR3:
  47396. data = BABYLON.Color3.FromArray(key.values);
  47397. break;
  47398. case Animation.ANIMATIONTYPE_VECTOR3:
  47399. default:
  47400. data = BABYLON.Vector3.FromArray(key.values);
  47401. break;
  47402. }
  47403. var keyData = {};
  47404. keyData.frame = key.frame;
  47405. keyData.value = data;
  47406. if (inTangent != undefined) {
  47407. keyData.inTangent = inTangent;
  47408. }
  47409. if (outTangent != undefined) {
  47410. keyData.outTangent = outTangent;
  47411. }
  47412. keys.push(keyData);
  47413. }
  47414. animation.setKeys(keys);
  47415. if (parsedAnimation.ranges) {
  47416. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  47417. data = parsedAnimation.ranges[index];
  47418. animation.createRange(data.name, data.from, data.to);
  47419. }
  47420. }
  47421. return animation;
  47422. };
  47423. Animation.AppendSerializedAnimations = function (source, destination) {
  47424. if (source.animations) {
  47425. destination.animations = [];
  47426. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47427. var animation = source.animations[animationIndex];
  47428. destination.animations.push(animation.serialize());
  47429. }
  47430. }
  47431. };
  47432. Animation.AllowMatricesInterpolation = false;
  47433. // Statics
  47434. Animation._ANIMATIONTYPE_FLOAT = 0;
  47435. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47436. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47437. Animation._ANIMATIONTYPE_MATRIX = 3;
  47438. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47439. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47440. Animation._ANIMATIONTYPE_SIZE = 6;
  47441. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47442. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47443. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47444. return Animation;
  47445. }());
  47446. BABYLON.Animation = Animation;
  47447. })(BABYLON || (BABYLON = {}));
  47448. //# sourceMappingURL=babylon.animation.js.map
  47449. "use strict";
  47450. var BABYLON;
  47451. (function (BABYLON) {
  47452. /**
  47453. * This class defines the direct association between an animation and a target
  47454. */
  47455. var TargetedAnimation = /** @class */ (function () {
  47456. function TargetedAnimation() {
  47457. }
  47458. return TargetedAnimation;
  47459. }());
  47460. BABYLON.TargetedAnimation = TargetedAnimation;
  47461. /**
  47462. * Use this class to create coordinated animations on multiple targets
  47463. */
  47464. var AnimationGroup = /** @class */ (function () {
  47465. function AnimationGroup(name, scene) {
  47466. if (scene === void 0) { scene = null; }
  47467. this.name = name;
  47468. this._targetedAnimations = new Array();
  47469. this._animatables = new Array();
  47470. this._from = Number.MAX_VALUE;
  47471. this._to = -Number.MAX_VALUE;
  47472. this._speedRatio = 1;
  47473. this.onAnimationEndObservable = new BABYLON.Observable();
  47474. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47475. this._scene.animationGroups.push(this);
  47476. }
  47477. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47478. /**
  47479. * Define if the animations are started
  47480. */
  47481. get: function () {
  47482. return this._isStarted;
  47483. },
  47484. enumerable: true,
  47485. configurable: true
  47486. });
  47487. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47488. /**
  47489. * Gets or sets the speed ratio to use for all animations
  47490. */
  47491. get: function () {
  47492. return this._speedRatio;
  47493. },
  47494. /**
  47495. * Gets or sets the speed ratio to use for all animations
  47496. */
  47497. set: function (value) {
  47498. if (this._speedRatio === value) {
  47499. return;
  47500. }
  47501. this._speedRatio = value;
  47502. for (var index = 0; index < this._animatables.length; index++) {
  47503. var animatable = this._animatables[index];
  47504. animatable.speedRatio = this._speedRatio;
  47505. }
  47506. },
  47507. enumerable: true,
  47508. configurable: true
  47509. });
  47510. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47511. /**
  47512. * Gets the targeted animations for this animation group
  47513. */
  47514. get: function () {
  47515. return this._targetedAnimations;
  47516. },
  47517. enumerable: true,
  47518. configurable: true
  47519. });
  47520. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47521. /**
  47522. * returning the list of animatables controlled by this animation group.
  47523. */
  47524. get: function () {
  47525. return this._animatables;
  47526. },
  47527. enumerable: true,
  47528. configurable: true
  47529. });
  47530. /**
  47531. * Add an animation (with its target) in the group
  47532. * @param animation defines the animation we want to add
  47533. * @param target defines the target of the animation
  47534. * @returns the {BABYLON.TargetedAnimation} object
  47535. */
  47536. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47537. var targetedAnimation = {
  47538. animation: animation,
  47539. target: target
  47540. };
  47541. var keys = animation.getKeys();
  47542. if (this._from > keys[0].frame) {
  47543. this._from = keys[0].frame;
  47544. }
  47545. if (this._to < keys[keys.length - 1].frame) {
  47546. this._to = keys[keys.length - 1].frame;
  47547. }
  47548. this._targetedAnimations.push(targetedAnimation);
  47549. return targetedAnimation;
  47550. };
  47551. /**
  47552. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47553. * It can add constant keys at begin or end
  47554. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47555. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47556. */
  47557. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47558. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47559. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47560. beginFrame = Math.max(beginFrame, this._from);
  47561. endFrame = Math.min(endFrame, this._to);
  47562. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47563. var targetedAnimation = this._targetedAnimations[index];
  47564. var keys = targetedAnimation.animation.getKeys();
  47565. var startKey = keys[0];
  47566. var endKey = keys[keys.length - 1];
  47567. if (startKey.frame > beginFrame) {
  47568. var newKey = {
  47569. frame: beginFrame,
  47570. value: startKey.value,
  47571. inTangent: startKey.inTangent,
  47572. outTangent: startKey.outTangent,
  47573. interpolation: startKey.interpolation
  47574. };
  47575. keys.splice(0, 0, newKey);
  47576. }
  47577. if (endKey.frame < endFrame) {
  47578. var newKey = {
  47579. frame: endFrame,
  47580. value: endKey.value,
  47581. inTangent: endKey.outTangent,
  47582. outTangent: endKey.outTangent,
  47583. interpolation: endKey.interpolation
  47584. };
  47585. keys.push(newKey);
  47586. }
  47587. }
  47588. return this;
  47589. };
  47590. /**
  47591. * Start all animations on given targets
  47592. * @param loop defines if animations must loop
  47593. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47594. * @param from defines the from key (optional)
  47595. * @param to defines the to key (optional)
  47596. * @returns the current animation group
  47597. */
  47598. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  47599. var _this = this;
  47600. if (loop === void 0) { loop = false; }
  47601. if (speedRatio === void 0) { speedRatio = 1; }
  47602. if (this._isStarted || this._targetedAnimations.length === 0) {
  47603. return this;
  47604. }
  47605. var _loop_1 = function () {
  47606. var targetedAnimation = this_1._targetedAnimations[index];
  47607. if (!targetedAnimation.target.animations) {
  47608. targetedAnimation.target.animations = [];
  47609. }
  47610. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  47611. targetedAnimation.target.animations.push(targetedAnimation.animation);
  47612. }
  47613. 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 () {
  47614. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47615. }));
  47616. };
  47617. var this_1 = this;
  47618. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47619. _loop_1();
  47620. }
  47621. this._speedRatio = speedRatio;
  47622. this._isStarted = true;
  47623. return this;
  47624. };
  47625. /**
  47626. * Pause all animations
  47627. */
  47628. AnimationGroup.prototype.pause = function () {
  47629. if (!this._isStarted) {
  47630. return this;
  47631. }
  47632. for (var index = 0; index < this._animatables.length; index++) {
  47633. var animatable = this._animatables[index];
  47634. animatable.pause();
  47635. }
  47636. return this;
  47637. };
  47638. /**
  47639. * Play all animations to initial state
  47640. * This function will start() the animations if they were not started or will restart() them if they were paused
  47641. * @param loop defines if animations must loop
  47642. */
  47643. AnimationGroup.prototype.play = function (loop) {
  47644. if (this.isStarted) {
  47645. if (loop !== undefined) {
  47646. for (var index = 0; index < this._animatables.length; index++) {
  47647. var animatable = this._animatables[index];
  47648. animatable.loopAnimation = loop;
  47649. }
  47650. }
  47651. this.restart();
  47652. }
  47653. else {
  47654. this.start(loop, this._speedRatio);
  47655. }
  47656. return this;
  47657. };
  47658. /**
  47659. * Reset all animations to initial state
  47660. */
  47661. AnimationGroup.prototype.reset = function () {
  47662. if (!this._isStarted) {
  47663. return this;
  47664. }
  47665. for (var index = 0; index < this._animatables.length; index++) {
  47666. var animatable = this._animatables[index];
  47667. animatable.reset();
  47668. }
  47669. return this;
  47670. };
  47671. /**
  47672. * Restart animations from key 0
  47673. */
  47674. AnimationGroup.prototype.restart = function () {
  47675. if (!this._isStarted) {
  47676. return this;
  47677. }
  47678. for (var index = 0; index < this._animatables.length; index++) {
  47679. var animatable = this._animatables[index];
  47680. animatable.restart();
  47681. }
  47682. return this;
  47683. };
  47684. /**
  47685. * Stop all animations
  47686. */
  47687. AnimationGroup.prototype.stop = function () {
  47688. if (!this._isStarted) {
  47689. return this;
  47690. }
  47691. for (var index = 0; index < this._animatables.length; index++) {
  47692. var animatable = this._animatables[index];
  47693. animatable.stop();
  47694. }
  47695. this._isStarted = false;
  47696. return this;
  47697. };
  47698. /**
  47699. * Goes to a specific frame in this animation group
  47700. *
  47701. * @param frame the frame number to go to
  47702. * @return the animationGroup
  47703. */
  47704. AnimationGroup.prototype.goToFrame = function (frame) {
  47705. if (!this._isStarted) {
  47706. return this;
  47707. }
  47708. for (var index = 0; index < this._animatables.length; index++) {
  47709. var animatable = this._animatables[index];
  47710. animatable.goToFrame(frame);
  47711. }
  47712. return this;
  47713. };
  47714. /**
  47715. * Dispose all associated resources
  47716. */
  47717. AnimationGroup.prototype.dispose = function () {
  47718. this._targetedAnimations = [];
  47719. this._animatables = [];
  47720. var index = this._scene.animationGroups.indexOf(this);
  47721. if (index > -1) {
  47722. this._scene.animationGroups.splice(index, 1);
  47723. }
  47724. };
  47725. return AnimationGroup;
  47726. }());
  47727. BABYLON.AnimationGroup = AnimationGroup;
  47728. })(BABYLON || (BABYLON = {}));
  47729. //# sourceMappingURL=babylon.animationGroup.js.map
  47730. "use strict";
  47731. var BABYLON;
  47732. (function (BABYLON) {
  47733. var RuntimeAnimation = /** @class */ (function () {
  47734. /**
  47735. * Create a new RuntimeAnimation object
  47736. * @param target defines the target of the animation
  47737. * @param animation defines the source {BABYLON.Animation} object
  47738. * @param scene defines the hosting scene
  47739. * @param host defines the initiating Animatable
  47740. */
  47741. function RuntimeAnimation(target, animation, scene, host) {
  47742. this._currentFrame = 0;
  47743. this._offsetsCache = {};
  47744. this._highLimitsCache = {};
  47745. this._stopped = false;
  47746. this._blendingFactor = 0;
  47747. this._targetPath = "";
  47748. this._weight = 1.0;
  47749. this._ratioOffset = 0;
  47750. this._previousDelay = 0;
  47751. this._previousRatio = 0;
  47752. this._animation = animation;
  47753. this._target = target;
  47754. this._scene = scene;
  47755. this._host = host;
  47756. animation._runtimeAnimations.push(this);
  47757. }
  47758. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  47759. /**
  47760. * Gets the current frame
  47761. */
  47762. get: function () {
  47763. return this._currentFrame;
  47764. },
  47765. enumerable: true,
  47766. configurable: true
  47767. });
  47768. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  47769. /**
  47770. * Gets the weight of the runtime animation
  47771. */
  47772. get: function () {
  47773. return this._weight;
  47774. },
  47775. enumerable: true,
  47776. configurable: true
  47777. });
  47778. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  47779. /**
  47780. * Gets the original value of the runtime animation
  47781. */
  47782. get: function () {
  47783. return this._originalValue;
  47784. },
  47785. enumerable: true,
  47786. configurable: true
  47787. });
  47788. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  47789. /**
  47790. * Gets the current value of the runtime animation
  47791. */
  47792. get: function () {
  47793. return this._currentValue;
  47794. },
  47795. enumerable: true,
  47796. configurable: true
  47797. });
  47798. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  47799. /**
  47800. * Gets the path where to store the animated value in the target
  47801. */
  47802. get: function () {
  47803. return this._targetPath;
  47804. },
  47805. enumerable: true,
  47806. configurable: true
  47807. });
  47808. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  47809. /**
  47810. * Gets the actual target of the runtime animation
  47811. */
  47812. get: function () {
  47813. return this._activeTarget;
  47814. },
  47815. enumerable: true,
  47816. configurable: true
  47817. });
  47818. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47819. get: function () {
  47820. return this._animation;
  47821. },
  47822. enumerable: true,
  47823. configurable: true
  47824. });
  47825. RuntimeAnimation.prototype.reset = function () {
  47826. this._offsetsCache = {};
  47827. this._highLimitsCache = {};
  47828. this._currentFrame = 0;
  47829. this._blendingFactor = 0;
  47830. this._originalValue = null;
  47831. };
  47832. RuntimeAnimation.prototype.isStopped = function () {
  47833. return this._stopped;
  47834. };
  47835. RuntimeAnimation.prototype.dispose = function () {
  47836. var index = this._animation.runtimeAnimations.indexOf(this);
  47837. if (index > -1) {
  47838. this._animation.runtimeAnimations.splice(index, 1);
  47839. }
  47840. };
  47841. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47842. if (typeof value === "function") {
  47843. return value();
  47844. }
  47845. return value;
  47846. };
  47847. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47848. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47849. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47850. }
  47851. this._currentFrame = currentFrame;
  47852. var keys = this._animation.getKeys();
  47853. // Try to get a hash to find the right key
  47854. 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));
  47855. if (keys[startKeyIndex].frame >= currentFrame) {
  47856. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47857. startKeyIndex--;
  47858. }
  47859. }
  47860. for (var key = startKeyIndex; key < keys.length; key++) {
  47861. var endKey = keys[key + 1];
  47862. if (endKey.frame >= currentFrame) {
  47863. var startKey = keys[key];
  47864. var startValue = this._getKeyValue(startKey.value);
  47865. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47866. return startValue;
  47867. }
  47868. var endValue = this._getKeyValue(endKey.value);
  47869. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47870. var frameDelta = endKey.frame - startKey.frame;
  47871. // gradient : percent of currentFrame between the frame inf and the frame sup
  47872. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47873. // check for easingFunction and correction of gradient
  47874. var easingFunction = this._animation.getEasingFunction();
  47875. if (easingFunction != null) {
  47876. gradient = easingFunction.ease(gradient);
  47877. }
  47878. switch (this._animation.dataType) {
  47879. // Float
  47880. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47881. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47882. switch (loopMode) {
  47883. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47884. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47885. return floatValue;
  47886. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47887. return offsetValue * repeatCount + floatValue;
  47888. }
  47889. break;
  47890. // Quaternion
  47891. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47892. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47893. switch (loopMode) {
  47894. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47895. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47896. return quatValue;
  47897. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47898. return quatValue.add(offsetValue.scale(repeatCount));
  47899. }
  47900. return quatValue;
  47901. // Vector3
  47902. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47903. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47904. switch (loopMode) {
  47905. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47906. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47907. return vec3Value;
  47908. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47909. return vec3Value.add(offsetValue.scale(repeatCount));
  47910. }
  47911. // Vector2
  47912. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47913. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47914. switch (loopMode) {
  47915. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47916. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47917. return vec2Value;
  47918. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47919. return vec2Value.add(offsetValue.scale(repeatCount));
  47920. }
  47921. // Size
  47922. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47923. switch (loopMode) {
  47924. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47925. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47926. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47927. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47928. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47929. }
  47930. // Color3
  47931. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47932. switch (loopMode) {
  47933. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47934. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47935. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47936. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47937. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47938. }
  47939. // Matrix
  47940. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47941. switch (loopMode) {
  47942. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47943. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47944. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47945. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47946. }
  47947. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47948. return startValue;
  47949. }
  47950. default:
  47951. break;
  47952. }
  47953. break;
  47954. }
  47955. }
  47956. return this._getKeyValue(keys[keys.length - 1].value);
  47957. };
  47958. /**
  47959. * Affect the interpolated value to the target
  47960. * @param currentValue defines the value computed by the animation
  47961. * @param weight defines the weight to apply to this value
  47962. */
  47963. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  47964. if (weight === void 0) { weight = 1.0; }
  47965. // Set value
  47966. var path;
  47967. var destination;
  47968. var targetPropertyPath = this._animation.targetPropertyPath;
  47969. if (targetPropertyPath.length > 1) {
  47970. var property = this._target[targetPropertyPath[0]];
  47971. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47972. property = property[targetPropertyPath[index]];
  47973. }
  47974. path = targetPropertyPath[targetPropertyPath.length - 1];
  47975. destination = property;
  47976. }
  47977. else {
  47978. path = targetPropertyPath[0];
  47979. destination = this._target;
  47980. }
  47981. this._targetPath = path;
  47982. this._activeTarget = destination;
  47983. this._weight = weight;
  47984. // Blending
  47985. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47986. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47987. if (enableBlending && this._blendingFactor <= 1.0) {
  47988. if (!this._originalBlendValue) {
  47989. var originalValue = destination[path];
  47990. if (originalValue.clone) {
  47991. this._originalBlendValue = originalValue.clone();
  47992. }
  47993. else {
  47994. this._originalBlendValue = originalValue;
  47995. }
  47996. }
  47997. }
  47998. if (weight !== -1.0) {
  47999. if (!this._originalValue) {
  48000. var originalValue = void 0;
  48001. if (destination.getRestPose) {
  48002. originalValue = destination.getRestPose();
  48003. }
  48004. else {
  48005. originalValue = destination[path];
  48006. }
  48007. if (originalValue.clone) {
  48008. this._originalValue = originalValue.clone();
  48009. }
  48010. else {
  48011. this._originalValue = originalValue;
  48012. }
  48013. }
  48014. }
  48015. if (enableBlending && this._blendingFactor <= 1.0) {
  48016. if (this._originalBlendValue.prototype) {
  48017. if (this._originalBlendValue.prototype.Lerp) {
  48018. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  48019. }
  48020. else {
  48021. this._currentValue = currentValue;
  48022. }
  48023. }
  48024. else if (this._originalBlendValue.m) {
  48025. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  48026. }
  48027. else {
  48028. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  48029. }
  48030. this._blendingFactor += blendingSpeed;
  48031. }
  48032. else {
  48033. this._currentValue = currentValue;
  48034. }
  48035. if (weight !== -1.0) {
  48036. this._scene._registerTargetForLateAnimationBinding(this);
  48037. }
  48038. else {
  48039. destination[path] = this._currentValue;
  48040. }
  48041. if (this._target.markAsDirty) {
  48042. this._target.markAsDirty(this._animation.targetProperty);
  48043. }
  48044. };
  48045. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  48046. if (this._target && this._target.animationPropertiesOverride) {
  48047. return this._target.animationPropertiesOverride.loopMode;
  48048. }
  48049. return this._animation.loopMode;
  48050. };
  48051. /**
  48052. * Move the current animation to a given frame
  48053. * @param frame defines the frame to move to
  48054. */
  48055. RuntimeAnimation.prototype.goToFrame = function (frame) {
  48056. var keys = this._animation.getKeys();
  48057. if (frame < keys[0].frame) {
  48058. frame = keys[0].frame;
  48059. }
  48060. else if (frame > keys[keys.length - 1].frame) {
  48061. frame = keys[keys.length - 1].frame;
  48062. }
  48063. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  48064. this.setValue(currentValue, -1);
  48065. };
  48066. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  48067. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  48068. this._ratioOffset = this._previousRatio - newRatio;
  48069. };
  48070. /**
  48071. * Execute the current animation
  48072. * @param delay defines the delay to add to the current frame
  48073. * @param from defines the lower bound of the animation range
  48074. * @param to defines the upper bound of the animation range
  48075. * @param loop defines if the current animation must loop
  48076. * @param speedRatio defines the current speed ratio
  48077. * @param weight defines the weight of the animation (default is -1 so no weight)
  48078. * @returns a boolean indicating if the animation has ended
  48079. */
  48080. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  48081. if (weight === void 0) { weight = -1.0; }
  48082. var targetPropertyPath = this._animation.targetPropertyPath;
  48083. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  48084. this._stopped = true;
  48085. return false;
  48086. }
  48087. var returnValue = true;
  48088. var keys = this._animation.getKeys();
  48089. // Adding a start key at frame 0 if missing
  48090. if (keys[0].frame !== 0) {
  48091. var newKey = { frame: 0, value: keys[0].value };
  48092. keys.splice(0, 0, newKey);
  48093. }
  48094. // Check limits
  48095. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  48096. from = keys[0].frame;
  48097. }
  48098. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  48099. to = keys[keys.length - 1].frame;
  48100. }
  48101. //to and from cannot be the same key
  48102. if (from === to) {
  48103. if (from > keys[0].frame) {
  48104. from--;
  48105. }
  48106. else if (to < keys[keys.length - 1].frame) {
  48107. to++;
  48108. }
  48109. }
  48110. // Compute ratio
  48111. var range = to - from;
  48112. var offsetValue;
  48113. // ratio represents the frame delta between from and to
  48114. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  48115. var highLimitValue = 0;
  48116. this._previousDelay = delay;
  48117. this._previousRatio = ratio;
  48118. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  48119. returnValue = false;
  48120. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  48121. }
  48122. else {
  48123. // Get max value if required
  48124. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  48125. var keyOffset = to.toString() + from.toString();
  48126. if (!this._offsetsCache[keyOffset]) {
  48127. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48128. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48129. switch (this._animation.dataType) {
  48130. // Float
  48131. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48132. this._offsetsCache[keyOffset] = toValue - fromValue;
  48133. break;
  48134. // Quaternion
  48135. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48136. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48137. break;
  48138. // Vector3
  48139. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48140. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48141. // Vector2
  48142. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48143. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48144. // Size
  48145. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48146. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48147. // Color3
  48148. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48149. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48150. default:
  48151. break;
  48152. }
  48153. this._highLimitsCache[keyOffset] = toValue;
  48154. }
  48155. highLimitValue = this._highLimitsCache[keyOffset];
  48156. offsetValue = this._offsetsCache[keyOffset];
  48157. }
  48158. }
  48159. if (offsetValue === undefined) {
  48160. switch (this._animation.dataType) {
  48161. // Float
  48162. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48163. offsetValue = 0;
  48164. break;
  48165. // Quaternion
  48166. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48167. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  48168. break;
  48169. // Vector3
  48170. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48171. offsetValue = BABYLON.Vector3.Zero();
  48172. break;
  48173. // Vector2
  48174. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48175. offsetValue = BABYLON.Vector2.Zero();
  48176. break;
  48177. // Size
  48178. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48179. offsetValue = BABYLON.Size.Zero();
  48180. break;
  48181. // Color3
  48182. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48183. offsetValue = BABYLON.Color3.Black();
  48184. }
  48185. }
  48186. // Compute value
  48187. var repeatCount = (ratio / range) >> 0;
  48188. var currentFrame = returnValue ? from + ratio % range : to;
  48189. // Need to normalize?
  48190. if (this._host && this._host.syncRoot) {
  48191. var syncRoot = this._host.syncRoot;
  48192. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  48193. currentFrame = from + (to - from) * hostNormalizedFrame;
  48194. }
  48195. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  48196. // Set value
  48197. this.setValue(currentValue, weight);
  48198. // Check events
  48199. var events = this._animation.getEvents();
  48200. for (var index = 0; index < events.length; index++) {
  48201. // Make sure current frame has passed event frame and that event frame is within the current range
  48202. // Also, handle both forward and reverse animations
  48203. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  48204. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  48205. var event = events[index];
  48206. if (!event.isDone) {
  48207. // If event should be done only once, remove it.
  48208. if (event.onlyOnce) {
  48209. events.splice(index, 1);
  48210. index--;
  48211. }
  48212. event.isDone = true;
  48213. event.action();
  48214. } // Don't do anything if the event has already be done.
  48215. }
  48216. else if (events[index].isDone && !events[index].onlyOnce) {
  48217. // reset event, the animation is looping
  48218. events[index].isDone = false;
  48219. }
  48220. }
  48221. if (!returnValue) {
  48222. this._stopped = true;
  48223. }
  48224. return returnValue;
  48225. };
  48226. return RuntimeAnimation;
  48227. }());
  48228. BABYLON.RuntimeAnimation = RuntimeAnimation;
  48229. })(BABYLON || (BABYLON = {}));
  48230. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  48231. "use strict";
  48232. var BABYLON;
  48233. (function (BABYLON) {
  48234. var Animatable = /** @class */ (function () {
  48235. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  48236. if (fromFrame === void 0) { fromFrame = 0; }
  48237. if (toFrame === void 0) { toFrame = 100; }
  48238. if (loopAnimation === void 0) { loopAnimation = false; }
  48239. if (speedRatio === void 0) { speedRatio = 1.0; }
  48240. this.target = target;
  48241. this.fromFrame = fromFrame;
  48242. this.toFrame = toFrame;
  48243. this.loopAnimation = loopAnimation;
  48244. this.onAnimationEnd = onAnimationEnd;
  48245. this._localDelayOffset = null;
  48246. this._pausedDelay = null;
  48247. this._runtimeAnimations = new Array();
  48248. this._paused = false;
  48249. this._speedRatio = 1;
  48250. this._weight = -1.0;
  48251. this.animationStarted = false;
  48252. if (animations) {
  48253. this.appendAnimations(target, animations);
  48254. }
  48255. this._speedRatio = speedRatio;
  48256. this._scene = scene;
  48257. scene._activeAnimatables.push(this);
  48258. }
  48259. Object.defineProperty(Animatable.prototype, "syncRoot", {
  48260. /**
  48261. * Gets the root Animatable used to synchronize and normalize animations
  48262. */
  48263. get: function () {
  48264. return this._syncRoot;
  48265. },
  48266. enumerable: true,
  48267. configurable: true
  48268. });
  48269. Object.defineProperty(Animatable.prototype, "masterFrame", {
  48270. /**
  48271. * Gets the current frame of the first RuntimeAnimation
  48272. * Used to synchronize Animatables
  48273. */
  48274. get: function () {
  48275. if (this._runtimeAnimations.length === 0) {
  48276. return 0;
  48277. }
  48278. return this._runtimeAnimations[0].currentFrame;
  48279. },
  48280. enumerable: true,
  48281. configurable: true
  48282. });
  48283. Object.defineProperty(Animatable.prototype, "weight", {
  48284. /**
  48285. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  48286. */
  48287. get: function () {
  48288. return this._weight;
  48289. },
  48290. set: function (value) {
  48291. if (value === -1) {
  48292. this._weight = -1;
  48293. return;
  48294. }
  48295. // Else weight must be in [0, 1] range
  48296. this._weight = Math.min(Math.max(value, 0), 1.0);
  48297. },
  48298. enumerable: true,
  48299. configurable: true
  48300. });
  48301. Object.defineProperty(Animatable.prototype, "speedRatio", {
  48302. /**
  48303. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  48304. */
  48305. get: function () {
  48306. return this._speedRatio;
  48307. },
  48308. set: function (value) {
  48309. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  48310. var animation = this._runtimeAnimations[index];
  48311. animation._prepareForSpeedRatioChange(value);
  48312. }
  48313. this._speedRatio = value;
  48314. },
  48315. enumerable: true,
  48316. configurable: true
  48317. });
  48318. // Methods
  48319. /**
  48320. * Synchronize and normalize current Animatable with a source Animatable.
  48321. * This is useful when using animation weights and when animations are not of the same length
  48322. * @param root defines the root Animatable to synchronize with
  48323. * @returns the current Animatable
  48324. */
  48325. Animatable.prototype.syncWith = function (root) {
  48326. this._syncRoot = root;
  48327. if (root) {
  48328. // Make sure this animatable will animate after the root
  48329. var index = this._scene._activeAnimatables.indexOf(this);
  48330. if (index > -1) {
  48331. this._scene._activeAnimatables.splice(index, 1);
  48332. this._scene._activeAnimatables.push(this);
  48333. }
  48334. }
  48335. return this;
  48336. };
  48337. Animatable.prototype.getAnimations = function () {
  48338. return this._runtimeAnimations;
  48339. };
  48340. Animatable.prototype.appendAnimations = function (target, animations) {
  48341. for (var index = 0; index < animations.length; index++) {
  48342. var animation = animations[index];
  48343. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  48344. }
  48345. };
  48346. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  48347. var runtimeAnimations = this._runtimeAnimations;
  48348. for (var index = 0; index < runtimeAnimations.length; index++) {
  48349. if (runtimeAnimations[index].animation.targetProperty === property) {
  48350. return runtimeAnimations[index].animation;
  48351. }
  48352. }
  48353. return null;
  48354. };
  48355. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  48356. var runtimeAnimations = this._runtimeAnimations;
  48357. for (var index = 0; index < runtimeAnimations.length; index++) {
  48358. if (runtimeAnimations[index].animation.targetProperty === property) {
  48359. return runtimeAnimations[index];
  48360. }
  48361. }
  48362. return null;
  48363. };
  48364. Animatable.prototype.reset = function () {
  48365. var runtimeAnimations = this._runtimeAnimations;
  48366. for (var index = 0; index < runtimeAnimations.length; index++) {
  48367. runtimeAnimations[index].reset();
  48368. }
  48369. // Reset to original value
  48370. for (index = 0; index < runtimeAnimations.length; index++) {
  48371. var animation = runtimeAnimations[index];
  48372. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  48373. }
  48374. this._localDelayOffset = null;
  48375. this._pausedDelay = null;
  48376. };
  48377. Animatable.prototype.enableBlending = function (blendingSpeed) {
  48378. var runtimeAnimations = this._runtimeAnimations;
  48379. for (var index = 0; index < runtimeAnimations.length; index++) {
  48380. runtimeAnimations[index].animation.enableBlending = true;
  48381. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  48382. }
  48383. };
  48384. Animatable.prototype.disableBlending = function () {
  48385. var runtimeAnimations = this._runtimeAnimations;
  48386. for (var index = 0; index < runtimeAnimations.length; index++) {
  48387. runtimeAnimations[index].animation.enableBlending = false;
  48388. }
  48389. };
  48390. Animatable.prototype.goToFrame = function (frame) {
  48391. var runtimeAnimations = this._runtimeAnimations;
  48392. if (runtimeAnimations[0]) {
  48393. var fps = runtimeAnimations[0].animation.framePerSecond;
  48394. var currentFrame = runtimeAnimations[0].currentFrame;
  48395. var adjustTime = frame - currentFrame;
  48396. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  48397. if (this._localDelayOffset === null) {
  48398. this._localDelayOffset = 0;
  48399. }
  48400. this._localDelayOffset -= delay;
  48401. }
  48402. for (var index = 0; index < runtimeAnimations.length; index++) {
  48403. runtimeAnimations[index].goToFrame(frame);
  48404. }
  48405. };
  48406. Animatable.prototype.pause = function () {
  48407. if (this._paused) {
  48408. return;
  48409. }
  48410. this._paused = true;
  48411. };
  48412. Animatable.prototype.restart = function () {
  48413. this._paused = false;
  48414. };
  48415. Animatable.prototype.stop = function (animationName) {
  48416. if (animationName) {
  48417. var idx = this._scene._activeAnimatables.indexOf(this);
  48418. if (idx > -1) {
  48419. var runtimeAnimations = this._runtimeAnimations;
  48420. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  48421. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  48422. continue;
  48423. }
  48424. runtimeAnimations[index].dispose();
  48425. runtimeAnimations.splice(index, 1);
  48426. }
  48427. if (runtimeAnimations.length == 0) {
  48428. this._scene._activeAnimatables.splice(idx, 1);
  48429. if (this.onAnimationEnd) {
  48430. this.onAnimationEnd();
  48431. }
  48432. }
  48433. }
  48434. }
  48435. else {
  48436. var index = this._scene._activeAnimatables.indexOf(this);
  48437. if (index > -1) {
  48438. this._scene._activeAnimatables.splice(index, 1);
  48439. var runtimeAnimations = this._runtimeAnimations;
  48440. for (var index = 0; index < runtimeAnimations.length; index++) {
  48441. runtimeAnimations[index].dispose();
  48442. }
  48443. if (this.onAnimationEnd) {
  48444. this.onAnimationEnd();
  48445. }
  48446. }
  48447. }
  48448. };
  48449. Animatable.prototype._animate = function (delay) {
  48450. if (this._paused) {
  48451. this.animationStarted = false;
  48452. if (this._pausedDelay === null) {
  48453. this._pausedDelay = delay;
  48454. }
  48455. return true;
  48456. }
  48457. if (this._localDelayOffset === null) {
  48458. this._localDelayOffset = delay;
  48459. this._pausedDelay = null;
  48460. }
  48461. else if (this._pausedDelay !== null) {
  48462. this._localDelayOffset += delay - this._pausedDelay;
  48463. this._pausedDelay = null;
  48464. }
  48465. if (this._weight === 0) {
  48466. return true;
  48467. }
  48468. // Animating
  48469. var running = false;
  48470. var runtimeAnimations = this._runtimeAnimations;
  48471. var index;
  48472. for (index = 0; index < runtimeAnimations.length; index++) {
  48473. var animation = runtimeAnimations[index];
  48474. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  48475. running = running || isRunning;
  48476. }
  48477. this.animationStarted = running;
  48478. if (!running) {
  48479. // Remove from active animatables
  48480. index = this._scene._activeAnimatables.indexOf(this);
  48481. this._scene._activeAnimatables.splice(index, 1);
  48482. // Dispose all runtime animations
  48483. for (index = 0; index < runtimeAnimations.length; index++) {
  48484. runtimeAnimations[index].dispose();
  48485. }
  48486. }
  48487. if (!running && this.onAnimationEnd) {
  48488. this.onAnimationEnd();
  48489. this.onAnimationEnd = null;
  48490. }
  48491. return running;
  48492. };
  48493. return Animatable;
  48494. }());
  48495. BABYLON.Animatable = Animatable;
  48496. })(BABYLON || (BABYLON = {}));
  48497. //# sourceMappingURL=babylon.animatable.js.map
  48498. "use strict";
  48499. var BABYLON;
  48500. (function (BABYLON) {
  48501. var EasingFunction = /** @class */ (function () {
  48502. function EasingFunction() {
  48503. // Properties
  48504. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  48505. }
  48506. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  48507. get: function () {
  48508. return EasingFunction._EASINGMODE_EASEIN;
  48509. },
  48510. enumerable: true,
  48511. configurable: true
  48512. });
  48513. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  48514. get: function () {
  48515. return EasingFunction._EASINGMODE_EASEOUT;
  48516. },
  48517. enumerable: true,
  48518. configurable: true
  48519. });
  48520. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  48521. get: function () {
  48522. return EasingFunction._EASINGMODE_EASEINOUT;
  48523. },
  48524. enumerable: true,
  48525. configurable: true
  48526. });
  48527. EasingFunction.prototype.setEasingMode = function (easingMode) {
  48528. var n = Math.min(Math.max(easingMode, 0), 2);
  48529. this._easingMode = n;
  48530. };
  48531. EasingFunction.prototype.getEasingMode = function () {
  48532. return this._easingMode;
  48533. };
  48534. EasingFunction.prototype.easeInCore = function (gradient) {
  48535. throw new Error('You must implement this method');
  48536. };
  48537. EasingFunction.prototype.ease = function (gradient) {
  48538. switch (this._easingMode) {
  48539. case EasingFunction.EASINGMODE_EASEIN:
  48540. return this.easeInCore(gradient);
  48541. case EasingFunction.EASINGMODE_EASEOUT:
  48542. return (1 - this.easeInCore(1 - gradient));
  48543. }
  48544. if (gradient >= 0.5) {
  48545. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  48546. }
  48547. return (this.easeInCore(gradient * 2) * 0.5);
  48548. };
  48549. //Statics
  48550. EasingFunction._EASINGMODE_EASEIN = 0;
  48551. EasingFunction._EASINGMODE_EASEOUT = 1;
  48552. EasingFunction._EASINGMODE_EASEINOUT = 2;
  48553. return EasingFunction;
  48554. }());
  48555. BABYLON.EasingFunction = EasingFunction;
  48556. var CircleEase = /** @class */ (function (_super) {
  48557. __extends(CircleEase, _super);
  48558. function CircleEase() {
  48559. return _super !== null && _super.apply(this, arguments) || this;
  48560. }
  48561. CircleEase.prototype.easeInCore = function (gradient) {
  48562. gradient = Math.max(0, Math.min(1, gradient));
  48563. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  48564. };
  48565. return CircleEase;
  48566. }(EasingFunction));
  48567. BABYLON.CircleEase = CircleEase;
  48568. var BackEase = /** @class */ (function (_super) {
  48569. __extends(BackEase, _super);
  48570. function BackEase(amplitude) {
  48571. if (amplitude === void 0) { amplitude = 1; }
  48572. var _this = _super.call(this) || this;
  48573. _this.amplitude = amplitude;
  48574. return _this;
  48575. }
  48576. BackEase.prototype.easeInCore = function (gradient) {
  48577. var num = Math.max(0, this.amplitude);
  48578. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  48579. };
  48580. return BackEase;
  48581. }(EasingFunction));
  48582. BABYLON.BackEase = BackEase;
  48583. var BounceEase = /** @class */ (function (_super) {
  48584. __extends(BounceEase, _super);
  48585. function BounceEase(bounces, bounciness) {
  48586. if (bounces === void 0) { bounces = 3; }
  48587. if (bounciness === void 0) { bounciness = 2; }
  48588. var _this = _super.call(this) || this;
  48589. _this.bounces = bounces;
  48590. _this.bounciness = bounciness;
  48591. return _this;
  48592. }
  48593. BounceEase.prototype.easeInCore = function (gradient) {
  48594. var y = Math.max(0.0, this.bounces);
  48595. var bounciness = this.bounciness;
  48596. if (bounciness <= 1.0) {
  48597. bounciness = 1.001;
  48598. }
  48599. var num9 = Math.pow(bounciness, y);
  48600. var num5 = 1.0 - bounciness;
  48601. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  48602. var num15 = gradient * num4;
  48603. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  48604. var num3 = Math.floor(num65);
  48605. var num13 = num3 + 1.0;
  48606. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  48607. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  48608. var num7 = (num8 + num12) * 0.5;
  48609. var num6 = gradient - num7;
  48610. var num2 = num7 - num8;
  48611. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  48612. };
  48613. return BounceEase;
  48614. }(EasingFunction));
  48615. BABYLON.BounceEase = BounceEase;
  48616. var CubicEase = /** @class */ (function (_super) {
  48617. __extends(CubicEase, _super);
  48618. function CubicEase() {
  48619. return _super !== null && _super.apply(this, arguments) || this;
  48620. }
  48621. CubicEase.prototype.easeInCore = function (gradient) {
  48622. return (gradient * gradient * gradient);
  48623. };
  48624. return CubicEase;
  48625. }(EasingFunction));
  48626. BABYLON.CubicEase = CubicEase;
  48627. var ElasticEase = /** @class */ (function (_super) {
  48628. __extends(ElasticEase, _super);
  48629. function ElasticEase(oscillations, springiness) {
  48630. if (oscillations === void 0) { oscillations = 3; }
  48631. if (springiness === void 0) { springiness = 3; }
  48632. var _this = _super.call(this) || this;
  48633. _this.oscillations = oscillations;
  48634. _this.springiness = springiness;
  48635. return _this;
  48636. }
  48637. ElasticEase.prototype.easeInCore = function (gradient) {
  48638. var num2;
  48639. var num3 = Math.max(0.0, this.oscillations);
  48640. var num = Math.max(0.0, this.springiness);
  48641. if (num == 0) {
  48642. num2 = gradient;
  48643. }
  48644. else {
  48645. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48646. }
  48647. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48648. };
  48649. return ElasticEase;
  48650. }(EasingFunction));
  48651. BABYLON.ElasticEase = ElasticEase;
  48652. var ExponentialEase = /** @class */ (function (_super) {
  48653. __extends(ExponentialEase, _super);
  48654. function ExponentialEase(exponent) {
  48655. if (exponent === void 0) { exponent = 2; }
  48656. var _this = _super.call(this) || this;
  48657. _this.exponent = exponent;
  48658. return _this;
  48659. }
  48660. ExponentialEase.prototype.easeInCore = function (gradient) {
  48661. if (this.exponent <= 0) {
  48662. return gradient;
  48663. }
  48664. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48665. };
  48666. return ExponentialEase;
  48667. }(EasingFunction));
  48668. BABYLON.ExponentialEase = ExponentialEase;
  48669. var PowerEase = /** @class */ (function (_super) {
  48670. __extends(PowerEase, _super);
  48671. function PowerEase(power) {
  48672. if (power === void 0) { power = 2; }
  48673. var _this = _super.call(this) || this;
  48674. _this.power = power;
  48675. return _this;
  48676. }
  48677. PowerEase.prototype.easeInCore = function (gradient) {
  48678. var y = Math.max(0.0, this.power);
  48679. return Math.pow(gradient, y);
  48680. };
  48681. return PowerEase;
  48682. }(EasingFunction));
  48683. BABYLON.PowerEase = PowerEase;
  48684. var QuadraticEase = /** @class */ (function (_super) {
  48685. __extends(QuadraticEase, _super);
  48686. function QuadraticEase() {
  48687. return _super !== null && _super.apply(this, arguments) || this;
  48688. }
  48689. QuadraticEase.prototype.easeInCore = function (gradient) {
  48690. return (gradient * gradient);
  48691. };
  48692. return QuadraticEase;
  48693. }(EasingFunction));
  48694. BABYLON.QuadraticEase = QuadraticEase;
  48695. var QuarticEase = /** @class */ (function (_super) {
  48696. __extends(QuarticEase, _super);
  48697. function QuarticEase() {
  48698. return _super !== null && _super.apply(this, arguments) || this;
  48699. }
  48700. QuarticEase.prototype.easeInCore = function (gradient) {
  48701. return (gradient * gradient * gradient * gradient);
  48702. };
  48703. return QuarticEase;
  48704. }(EasingFunction));
  48705. BABYLON.QuarticEase = QuarticEase;
  48706. var QuinticEase = /** @class */ (function (_super) {
  48707. __extends(QuinticEase, _super);
  48708. function QuinticEase() {
  48709. return _super !== null && _super.apply(this, arguments) || this;
  48710. }
  48711. QuinticEase.prototype.easeInCore = function (gradient) {
  48712. return (gradient * gradient * gradient * gradient * gradient);
  48713. };
  48714. return QuinticEase;
  48715. }(EasingFunction));
  48716. BABYLON.QuinticEase = QuinticEase;
  48717. var SineEase = /** @class */ (function (_super) {
  48718. __extends(SineEase, _super);
  48719. function SineEase() {
  48720. return _super !== null && _super.apply(this, arguments) || this;
  48721. }
  48722. SineEase.prototype.easeInCore = function (gradient) {
  48723. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48724. };
  48725. return SineEase;
  48726. }(EasingFunction));
  48727. BABYLON.SineEase = SineEase;
  48728. var BezierCurveEase = /** @class */ (function (_super) {
  48729. __extends(BezierCurveEase, _super);
  48730. function BezierCurveEase(x1, y1, x2, y2) {
  48731. if (x1 === void 0) { x1 = 0; }
  48732. if (y1 === void 0) { y1 = 0; }
  48733. if (x2 === void 0) { x2 = 1; }
  48734. if (y2 === void 0) { y2 = 1; }
  48735. var _this = _super.call(this) || this;
  48736. _this.x1 = x1;
  48737. _this.y1 = y1;
  48738. _this.x2 = x2;
  48739. _this.y2 = y2;
  48740. return _this;
  48741. }
  48742. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48743. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48744. };
  48745. return BezierCurveEase;
  48746. }(EasingFunction));
  48747. BABYLON.BezierCurveEase = BezierCurveEase;
  48748. })(BABYLON || (BABYLON = {}));
  48749. //# sourceMappingURL=babylon.easing.js.map
  48750. "use strict";
  48751. var BABYLON;
  48752. (function (BABYLON) {
  48753. /**
  48754. * A Condition applied to an Action
  48755. */
  48756. var Condition = /** @class */ (function () {
  48757. /**
  48758. * Creates a new Condition
  48759. * @param actionManager the manager of the action the condition is applied to
  48760. */
  48761. function Condition(actionManager) {
  48762. this._actionManager = actionManager;
  48763. }
  48764. /**
  48765. * Check if the current condition is valid
  48766. * @returns a boolean
  48767. */
  48768. Condition.prototype.isValid = function () {
  48769. return true;
  48770. };
  48771. /**
  48772. * Internal only
  48773. * @ignore
  48774. */
  48775. Condition.prototype._getProperty = function (propertyPath) {
  48776. return this._actionManager._getProperty(propertyPath);
  48777. };
  48778. /**
  48779. * Internal only
  48780. * @ignore
  48781. */
  48782. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48783. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48784. };
  48785. /**
  48786. * Serialize placeholder for child classes
  48787. * @returns the serialized object
  48788. */
  48789. Condition.prototype.serialize = function () {
  48790. };
  48791. /**
  48792. * Internal only
  48793. * @ignore
  48794. */
  48795. Condition.prototype._serialize = function (serializedCondition) {
  48796. return {
  48797. type: 2,
  48798. children: [],
  48799. name: serializedCondition.name,
  48800. properties: serializedCondition.properties
  48801. };
  48802. };
  48803. return Condition;
  48804. }());
  48805. BABYLON.Condition = Condition;
  48806. /**
  48807. * Defines specific conditional operators as extensions of Condition
  48808. */
  48809. var ValueCondition = /** @class */ (function (_super) {
  48810. __extends(ValueCondition, _super);
  48811. /**
  48812. * Creates a new ValueCondition
  48813. * @param actionManager manager for the action the condition applies to
  48814. * @param target for the action
  48815. * @param propertyPath path to specify the property of the target the conditional operator uses
  48816. * @param value the vale compared by the conditional operator against the current value of the property
  48817. * @param operator the conditional operator, default {BABYLON.ValueCondition.IsEqual}
  48818. */
  48819. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48820. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48821. var _this = _super.call(this, actionManager) || this;
  48822. _this.propertyPath = propertyPath;
  48823. _this.value = value;
  48824. _this.operator = operator;
  48825. _this._target = target;
  48826. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48827. _this._property = _this._getProperty(_this.propertyPath);
  48828. return _this;
  48829. }
  48830. Object.defineProperty(ValueCondition, "IsEqual", {
  48831. /**
  48832. * returns the number for IsEqual
  48833. */
  48834. get: function () {
  48835. return ValueCondition._IsEqual;
  48836. },
  48837. enumerable: true,
  48838. configurable: true
  48839. });
  48840. Object.defineProperty(ValueCondition, "IsDifferent", {
  48841. /**
  48842. * Returns the number for IsDifferent
  48843. */
  48844. get: function () {
  48845. return ValueCondition._IsDifferent;
  48846. },
  48847. enumerable: true,
  48848. configurable: true
  48849. });
  48850. Object.defineProperty(ValueCondition, "IsGreater", {
  48851. /**
  48852. * Returns the number for IsGreater
  48853. */
  48854. get: function () {
  48855. return ValueCondition._IsGreater;
  48856. },
  48857. enumerable: true,
  48858. configurable: true
  48859. });
  48860. Object.defineProperty(ValueCondition, "IsLesser", {
  48861. /**
  48862. * Returns the number for IsLesser
  48863. */
  48864. get: function () {
  48865. return ValueCondition._IsLesser;
  48866. },
  48867. enumerable: true,
  48868. configurable: true
  48869. });
  48870. /**
  48871. * Compares the given value with the property value for the specified conditional operator
  48872. * @returns the result of the comparison
  48873. */
  48874. ValueCondition.prototype.isValid = function () {
  48875. switch (this.operator) {
  48876. case ValueCondition.IsGreater:
  48877. return this._effectiveTarget[this._property] > this.value;
  48878. case ValueCondition.IsLesser:
  48879. return this._effectiveTarget[this._property] < this.value;
  48880. case ValueCondition.IsEqual:
  48881. case ValueCondition.IsDifferent:
  48882. var check;
  48883. if (this.value.equals) {
  48884. check = this.value.equals(this._effectiveTarget[this._property]);
  48885. }
  48886. else {
  48887. check = this.value === this._effectiveTarget[this._property];
  48888. }
  48889. return this.operator === ValueCondition.IsEqual ? check : !check;
  48890. }
  48891. return false;
  48892. };
  48893. /**
  48894. * Serialize the ValueCondition into a JSON compatible object
  48895. * @returns serialization object
  48896. */
  48897. ValueCondition.prototype.serialize = function () {
  48898. return this._serialize({
  48899. name: "ValueCondition",
  48900. properties: [
  48901. BABYLON.Action._GetTargetProperty(this._target),
  48902. { name: "propertyPath", value: this.propertyPath },
  48903. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48904. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48905. ]
  48906. });
  48907. };
  48908. /**
  48909. * Gets the name of the conditional operator for the ValueCondition
  48910. * @param operator the conditional operator
  48911. * @returns the name
  48912. */
  48913. ValueCondition.GetOperatorName = function (operator) {
  48914. switch (operator) {
  48915. case ValueCondition._IsEqual: return "IsEqual";
  48916. case ValueCondition._IsDifferent: return "IsDifferent";
  48917. case ValueCondition._IsGreater: return "IsGreater";
  48918. case ValueCondition._IsLesser: return "IsLesser";
  48919. default: return "";
  48920. }
  48921. };
  48922. /**
  48923. * Internal only
  48924. * @ignore
  48925. */
  48926. ValueCondition._IsEqual = 0;
  48927. /**
  48928. * Internal only
  48929. * @ignore
  48930. */
  48931. ValueCondition._IsDifferent = 1;
  48932. /**
  48933. * Internal only
  48934. * @ignore
  48935. */
  48936. ValueCondition._IsGreater = 2;
  48937. /**
  48938. * Internal only
  48939. * @ignore
  48940. */
  48941. ValueCondition._IsLesser = 3;
  48942. return ValueCondition;
  48943. }(Condition));
  48944. BABYLON.ValueCondition = ValueCondition;
  48945. /**
  48946. * Defines a predicate condition as an extension of Condition
  48947. */
  48948. var PredicateCondition = /** @class */ (function (_super) {
  48949. __extends(PredicateCondition, _super);
  48950. /**
  48951. * Creates a new {BABYLON.PredicateCondition}
  48952. * @param actionManager manager for the action the condition applies to
  48953. * @param predicate
  48954. */
  48955. function PredicateCondition(actionManager, predicate) {
  48956. var _this = _super.call(this, actionManager) || this;
  48957. _this.predicate = predicate;
  48958. return _this;
  48959. }
  48960. /**
  48961. * @returns the validity of the predicate condition
  48962. */
  48963. PredicateCondition.prototype.isValid = function () {
  48964. return this.predicate();
  48965. };
  48966. return PredicateCondition;
  48967. }(Condition));
  48968. BABYLON.PredicateCondition = PredicateCondition;
  48969. /**
  48970. * Defines a state condition as an extension of {BABYLON.Condition}
  48971. */
  48972. var StateCondition = /** @class */ (function (_super) {
  48973. __extends(StateCondition, _super);
  48974. /**
  48975. * Creates a new {BABYLON.StateCondition}
  48976. * @param actionManager manager for the action the condition applies to
  48977. * @param target of the condition
  48978. * @param value to compare with target state
  48979. */
  48980. function StateCondition(actionManager, target, value) {
  48981. var _this = _super.call(this, actionManager) || this;
  48982. _this.value = value;
  48983. _this._target = target;
  48984. return _this;
  48985. }
  48986. /**
  48987. * @returns the validity of the state
  48988. */
  48989. StateCondition.prototype.isValid = function () {
  48990. return this._target.state === this.value;
  48991. };
  48992. /**
  48993. * Serialize the {BABYLON.StateCondition} into a JSON compatible object
  48994. * @returns serialization object
  48995. */
  48996. StateCondition.prototype.serialize = function () {
  48997. return this._serialize({
  48998. name: "StateCondition",
  48999. properties: [
  49000. BABYLON.Action._GetTargetProperty(this._target),
  49001. { name: "value", value: this.value }
  49002. ]
  49003. });
  49004. };
  49005. return StateCondition;
  49006. }(Condition));
  49007. BABYLON.StateCondition = StateCondition;
  49008. })(BABYLON || (BABYLON = {}));
  49009. //# sourceMappingURL=babylon.condition.js.map
  49010. "use strict";
  49011. var BABYLON;
  49012. (function (BABYLON) {
  49013. /**
  49014. * The action to be carried out following a trigger
  49015. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  49016. */
  49017. var Action = /** @class */ (function () {
  49018. /**
  49019. * Creates a new Action
  49020. * @param triggerOptions the trigger, with or without parameters, for the action
  49021. * @param condition an optional determinant of action
  49022. */
  49023. function Action(triggerOptions, condition) {
  49024. this.triggerOptions = triggerOptions;
  49025. /**
  49026. * An event triggered prior to action being executed.
  49027. * @type Observable
  49028. */
  49029. this.onBeforeExecuteObservable = new BABYLON.Observable();
  49030. if (triggerOptions.parameter) {
  49031. this.trigger = triggerOptions.trigger;
  49032. this._triggerParameter = triggerOptions.parameter;
  49033. }
  49034. else {
  49035. this.trigger = triggerOptions;
  49036. }
  49037. this._nextActiveAction = this;
  49038. this._condition = condition;
  49039. }
  49040. /**
  49041. * Internal only
  49042. * @ignore
  49043. */
  49044. Action.prototype._prepare = function () {
  49045. };
  49046. /**
  49047. * Gets the trigger parameters
  49048. * @returns the trigger parameters
  49049. */
  49050. Action.prototype.getTriggerParameter = function () {
  49051. return this._triggerParameter;
  49052. };
  49053. /**
  49054. * Internal only - executes current action event
  49055. * @ignore
  49056. */
  49057. Action.prototype._executeCurrent = function (evt) {
  49058. if (this._nextActiveAction._condition) {
  49059. var condition = this._nextActiveAction._condition;
  49060. var currentRenderId = this._actionManager.getScene().getRenderId();
  49061. // We cache the current evaluation for the current frame
  49062. if (condition._evaluationId === currentRenderId) {
  49063. if (!condition._currentResult) {
  49064. return;
  49065. }
  49066. }
  49067. else {
  49068. condition._evaluationId = currentRenderId;
  49069. if (!condition.isValid()) {
  49070. condition._currentResult = false;
  49071. return;
  49072. }
  49073. condition._currentResult = true;
  49074. }
  49075. }
  49076. this.onBeforeExecuteObservable.notifyObservers(this);
  49077. this._nextActiveAction.execute(evt);
  49078. this.skipToNextActiveAction();
  49079. };
  49080. /**
  49081. * Execute placeholder for child classes
  49082. * @param evt optional action event
  49083. */
  49084. Action.prototype.execute = function (evt) {
  49085. };
  49086. /**
  49087. * Skips to next active action
  49088. */
  49089. Action.prototype.skipToNextActiveAction = function () {
  49090. if (this._nextActiveAction._child) {
  49091. if (!this._nextActiveAction._child._actionManager) {
  49092. this._nextActiveAction._child._actionManager = this._actionManager;
  49093. }
  49094. this._nextActiveAction = this._nextActiveAction._child;
  49095. }
  49096. else {
  49097. this._nextActiveAction = this;
  49098. }
  49099. };
  49100. /**
  49101. * Adds action to chain of actions, may be a DoNothingAction
  49102. * @param index The index of the attribute.
  49103. * @returns The action passed in
  49104. * @see https://www.babylonjs-playground.com/#1T30HR#0
  49105. */
  49106. Action.prototype.then = function (action) {
  49107. this._child = action;
  49108. action._actionManager = this._actionManager;
  49109. action._prepare();
  49110. return action;
  49111. };
  49112. /**
  49113. * Internal only
  49114. * @ignore
  49115. */
  49116. Action.prototype._getProperty = function (propertyPath) {
  49117. return this._actionManager._getProperty(propertyPath);
  49118. };
  49119. /**
  49120. * Internal only
  49121. * @ignore
  49122. */
  49123. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  49124. return this._actionManager._getEffectiveTarget(target, propertyPath);
  49125. };
  49126. /**
  49127. * Serialize placeholder for child classes
  49128. * @param parent of child
  49129. * @returns the serialized object
  49130. */
  49131. Action.prototype.serialize = function (parent) {
  49132. };
  49133. /**
  49134. * Internal only called by serialize
  49135. * @ignore
  49136. */
  49137. Action.prototype._serialize = function (serializedAction, parent) {
  49138. var serializationObject = {
  49139. type: 1,
  49140. children: [],
  49141. name: serializedAction.name,
  49142. properties: serializedAction.properties || []
  49143. };
  49144. // Serialize child
  49145. if (this._child) {
  49146. this._child.serialize(serializationObject);
  49147. }
  49148. // Check if "this" has a condition
  49149. if (this._condition) {
  49150. var serializedCondition = this._condition.serialize();
  49151. serializedCondition.children.push(serializationObject);
  49152. if (parent) {
  49153. parent.children.push(serializedCondition);
  49154. }
  49155. return serializedCondition;
  49156. }
  49157. if (parent) {
  49158. parent.children.push(serializationObject);
  49159. }
  49160. return serializationObject;
  49161. };
  49162. /**
  49163. * Internal only
  49164. * @ignore
  49165. */
  49166. Action._SerializeValueAsString = function (value) {
  49167. if (typeof value === "number") {
  49168. return value.toString();
  49169. }
  49170. if (typeof value === "boolean") {
  49171. return value ? "true" : "false";
  49172. }
  49173. if (value instanceof BABYLON.Vector2) {
  49174. return value.x + ", " + value.y;
  49175. }
  49176. if (value instanceof BABYLON.Vector3) {
  49177. return value.x + ", " + value.y + ", " + value.z;
  49178. }
  49179. if (value instanceof BABYLON.Color3) {
  49180. return value.r + ", " + value.g + ", " + value.b;
  49181. }
  49182. if (value instanceof BABYLON.Color4) {
  49183. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  49184. }
  49185. return value; // string
  49186. };
  49187. /**
  49188. * Internal only
  49189. * @ignore
  49190. */
  49191. Action._GetTargetProperty = function (target) {
  49192. return {
  49193. name: "target",
  49194. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  49195. : target instanceof BABYLON.Light ? "LightProperties"
  49196. : target instanceof BABYLON.Camera ? "CameraProperties"
  49197. : "SceneProperties",
  49198. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  49199. };
  49200. };
  49201. return Action;
  49202. }());
  49203. BABYLON.Action = Action;
  49204. })(BABYLON || (BABYLON = {}));
  49205. //# sourceMappingURL=babylon.action.js.map
  49206. "use strict";
  49207. var BABYLON;
  49208. (function (BABYLON) {
  49209. /**
  49210. * ActionEvent is the event being sent when an action is triggered.
  49211. */
  49212. var ActionEvent = /** @class */ (function () {
  49213. /**
  49214. * @param source The mesh or sprite that triggered the action.
  49215. * @param pointerX The X mouse cursor position at the time of the event
  49216. * @param pointerY The Y mouse cursor position at the time of the event
  49217. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  49218. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  49219. */
  49220. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  49221. this.source = source;
  49222. this.pointerX = pointerX;
  49223. this.pointerY = pointerY;
  49224. this.meshUnderPointer = meshUnderPointer;
  49225. this.sourceEvent = sourceEvent;
  49226. this.additionalData = additionalData;
  49227. }
  49228. /**
  49229. * Helper function to auto-create an ActionEvent from a source mesh.
  49230. * @param source The source mesh that triggered the event
  49231. * @param evt {Event} The original (browser) event
  49232. */
  49233. ActionEvent.CreateNew = function (source, evt, additionalData) {
  49234. var scene = source.getScene();
  49235. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49236. };
  49237. /**
  49238. * Helper function to auto-create an ActionEvent from a source mesh.
  49239. * @param source The source sprite that triggered the event
  49240. * @param scene Scene associated with the sprite
  49241. * @param evt {Event} The original (browser) event
  49242. */
  49243. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  49244. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49245. };
  49246. /**
  49247. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  49248. * @param scene the scene where the event occurred
  49249. * @param evt {Event} The original (browser) event
  49250. */
  49251. ActionEvent.CreateNewFromScene = function (scene, evt) {
  49252. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  49253. };
  49254. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  49255. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  49256. };
  49257. return ActionEvent;
  49258. }());
  49259. BABYLON.ActionEvent = ActionEvent;
  49260. /**
  49261. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  49262. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  49263. */
  49264. var ActionManager = /** @class */ (function () {
  49265. function ActionManager(scene) {
  49266. // Members
  49267. this.actions = new Array();
  49268. this.hoverCursor = '';
  49269. this._scene = scene;
  49270. scene._actionManagers.push(this);
  49271. }
  49272. Object.defineProperty(ActionManager, "NothingTrigger", {
  49273. get: function () {
  49274. return ActionManager._NothingTrigger;
  49275. },
  49276. enumerable: true,
  49277. configurable: true
  49278. });
  49279. Object.defineProperty(ActionManager, "OnPickTrigger", {
  49280. get: function () {
  49281. return ActionManager._OnPickTrigger;
  49282. },
  49283. enumerable: true,
  49284. configurable: true
  49285. });
  49286. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  49287. get: function () {
  49288. return ActionManager._OnLeftPickTrigger;
  49289. },
  49290. enumerable: true,
  49291. configurable: true
  49292. });
  49293. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  49294. get: function () {
  49295. return ActionManager._OnRightPickTrigger;
  49296. },
  49297. enumerable: true,
  49298. configurable: true
  49299. });
  49300. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  49301. get: function () {
  49302. return ActionManager._OnCenterPickTrigger;
  49303. },
  49304. enumerable: true,
  49305. configurable: true
  49306. });
  49307. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  49308. get: function () {
  49309. return ActionManager._OnPickDownTrigger;
  49310. },
  49311. enumerable: true,
  49312. configurable: true
  49313. });
  49314. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  49315. get: function () {
  49316. return ActionManager._OnDoublePickTrigger;
  49317. },
  49318. enumerable: true,
  49319. configurable: true
  49320. });
  49321. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  49322. get: function () {
  49323. return ActionManager._OnPickUpTrigger;
  49324. },
  49325. enumerable: true,
  49326. configurable: true
  49327. });
  49328. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  49329. /// This trigger will only be raised if you also declared a OnPickDown
  49330. get: function () {
  49331. return ActionManager._OnPickOutTrigger;
  49332. },
  49333. enumerable: true,
  49334. configurable: true
  49335. });
  49336. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  49337. get: function () {
  49338. return ActionManager._OnLongPressTrigger;
  49339. },
  49340. enumerable: true,
  49341. configurable: true
  49342. });
  49343. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  49344. get: function () {
  49345. return ActionManager._OnPointerOverTrigger;
  49346. },
  49347. enumerable: true,
  49348. configurable: true
  49349. });
  49350. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  49351. get: function () {
  49352. return ActionManager._OnPointerOutTrigger;
  49353. },
  49354. enumerable: true,
  49355. configurable: true
  49356. });
  49357. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  49358. get: function () {
  49359. return ActionManager._OnEveryFrameTrigger;
  49360. },
  49361. enumerable: true,
  49362. configurable: true
  49363. });
  49364. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  49365. get: function () {
  49366. return ActionManager._OnIntersectionEnterTrigger;
  49367. },
  49368. enumerable: true,
  49369. configurable: true
  49370. });
  49371. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  49372. get: function () {
  49373. return ActionManager._OnIntersectionExitTrigger;
  49374. },
  49375. enumerable: true,
  49376. configurable: true
  49377. });
  49378. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  49379. get: function () {
  49380. return ActionManager._OnKeyDownTrigger;
  49381. },
  49382. enumerable: true,
  49383. configurable: true
  49384. });
  49385. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  49386. get: function () {
  49387. return ActionManager._OnKeyUpTrigger;
  49388. },
  49389. enumerable: true,
  49390. configurable: true
  49391. });
  49392. // Methods
  49393. ActionManager.prototype.dispose = function () {
  49394. var index = this._scene._actionManagers.indexOf(this);
  49395. for (var i = 0; i < this.actions.length; i++) {
  49396. var action = this.actions[i];
  49397. ActionManager.Triggers[action.trigger]--;
  49398. if (ActionManager.Triggers[action.trigger] === 0) {
  49399. delete ActionManager.Triggers[action.trigger];
  49400. }
  49401. }
  49402. if (index > -1) {
  49403. this._scene._actionManagers.splice(index, 1);
  49404. }
  49405. };
  49406. ActionManager.prototype.getScene = function () {
  49407. return this._scene;
  49408. };
  49409. /**
  49410. * Does this action manager handles actions of any of the given triggers
  49411. * @param {number[]} triggers - the triggers to be tested
  49412. * @return {boolean} whether one (or more) of the triggers is handeled
  49413. */
  49414. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  49415. for (var index = 0; index < this.actions.length; index++) {
  49416. var action = this.actions[index];
  49417. if (triggers.indexOf(action.trigger) > -1) {
  49418. return true;
  49419. }
  49420. }
  49421. return false;
  49422. };
  49423. /**
  49424. * Does this action manager handles actions of a given trigger
  49425. * @param {number} trigger - the trigger to be tested
  49426. * @return {boolean} whether the trigger is handeled
  49427. */
  49428. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  49429. for (var index = 0; index < this.actions.length; index++) {
  49430. var action = this.actions[index];
  49431. if (action.trigger === trigger) {
  49432. return true;
  49433. }
  49434. }
  49435. return false;
  49436. };
  49437. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  49438. /**
  49439. * Does this action manager has pointer triggers
  49440. * @return {boolean} whether or not it has pointer triggers
  49441. */
  49442. get: function () {
  49443. for (var index = 0; index < this.actions.length; index++) {
  49444. var action = this.actions[index];
  49445. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  49446. return true;
  49447. }
  49448. }
  49449. return false;
  49450. },
  49451. enumerable: true,
  49452. configurable: true
  49453. });
  49454. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  49455. /**
  49456. * Does this action manager has pick triggers
  49457. * @return {boolean} whether or not it has pick triggers
  49458. */
  49459. get: function () {
  49460. for (var index = 0; index < this.actions.length; index++) {
  49461. var action = this.actions[index];
  49462. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  49463. return true;
  49464. }
  49465. }
  49466. return false;
  49467. },
  49468. enumerable: true,
  49469. configurable: true
  49470. });
  49471. Object.defineProperty(ActionManager, "HasTriggers", {
  49472. /**
  49473. * Does exist one action manager with at least one trigger
  49474. * @return {boolean} whether or not it exists one action manager with one trigger
  49475. **/
  49476. get: function () {
  49477. for (var t in ActionManager.Triggers) {
  49478. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49479. return true;
  49480. }
  49481. }
  49482. return false;
  49483. },
  49484. enumerable: true,
  49485. configurable: true
  49486. });
  49487. Object.defineProperty(ActionManager, "HasPickTriggers", {
  49488. /**
  49489. * Does exist one action manager with at least one pick trigger
  49490. * @return {boolean} whether or not it exists one action manager with one pick trigger
  49491. **/
  49492. get: function () {
  49493. for (var t in ActionManager.Triggers) {
  49494. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49495. var t_int = parseInt(t);
  49496. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  49497. return true;
  49498. }
  49499. }
  49500. }
  49501. return false;
  49502. },
  49503. enumerable: true,
  49504. configurable: true
  49505. });
  49506. /**
  49507. * Does exist one action manager that handles actions of a given trigger
  49508. * @param {number} trigger - the trigger to be tested
  49509. * @return {boolean} whether the trigger is handeled by at least one action manager
  49510. **/
  49511. ActionManager.HasSpecificTrigger = function (trigger) {
  49512. for (var t in ActionManager.Triggers) {
  49513. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49514. var t_int = parseInt(t);
  49515. if (t_int === trigger) {
  49516. return true;
  49517. }
  49518. }
  49519. }
  49520. return false;
  49521. };
  49522. /**
  49523. * Registers an action to this action manager
  49524. * @param {BABYLON.Action} action - the action to be registered
  49525. * @return {BABYLON.Action} the action amended (prepared) after registration
  49526. */
  49527. ActionManager.prototype.registerAction = function (action) {
  49528. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  49529. if (this.getScene().actionManager !== this) {
  49530. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  49531. return null;
  49532. }
  49533. }
  49534. this.actions.push(action);
  49535. if (ActionManager.Triggers[action.trigger]) {
  49536. ActionManager.Triggers[action.trigger]++;
  49537. }
  49538. else {
  49539. ActionManager.Triggers[action.trigger] = 1;
  49540. }
  49541. action._actionManager = this;
  49542. action._prepare();
  49543. return action;
  49544. };
  49545. /**
  49546. * Unregisters an action to this action manager
  49547. * @param action The action to be unregistered
  49548. * @return whether the action has been unregistered
  49549. */
  49550. ActionManager.prototype.unregisterAction = function (action) {
  49551. var index = this.actions.indexOf(action);
  49552. if (index !== -1) {
  49553. this.actions.splice(index, 1);
  49554. ActionManager.Triggers[action.trigger] -= 1;
  49555. if (ActionManager.Triggers[action.trigger] === 0) {
  49556. delete ActionManager.Triggers[action.trigger];
  49557. }
  49558. delete action._actionManager;
  49559. return true;
  49560. }
  49561. return false;
  49562. };
  49563. /**
  49564. * Process a specific trigger
  49565. * @param {number} trigger - the trigger to process
  49566. * @param evt {BABYLON.ActionEvent} the event details to be processed
  49567. */
  49568. ActionManager.prototype.processTrigger = function (trigger, evt) {
  49569. for (var index = 0; index < this.actions.length; index++) {
  49570. var action = this.actions[index];
  49571. if (action.trigger === trigger) {
  49572. if (evt) {
  49573. if (trigger === ActionManager.OnKeyUpTrigger
  49574. || trigger === ActionManager.OnKeyDownTrigger) {
  49575. var parameter = action.getTriggerParameter();
  49576. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  49577. if (!parameter.toLowerCase) {
  49578. continue;
  49579. }
  49580. var lowerCase = parameter.toLowerCase();
  49581. if (lowerCase !== evt.sourceEvent.key) {
  49582. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  49583. var actualkey = String.fromCharCode(unicode).toLowerCase();
  49584. if (actualkey !== lowerCase) {
  49585. continue;
  49586. }
  49587. }
  49588. }
  49589. }
  49590. }
  49591. action._executeCurrent(evt);
  49592. }
  49593. }
  49594. };
  49595. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  49596. var properties = propertyPath.split(".");
  49597. for (var index = 0; index < properties.length - 1; index++) {
  49598. target = target[properties[index]];
  49599. }
  49600. return target;
  49601. };
  49602. ActionManager.prototype._getProperty = function (propertyPath) {
  49603. var properties = propertyPath.split(".");
  49604. return properties[properties.length - 1];
  49605. };
  49606. ActionManager.prototype.serialize = function (name) {
  49607. var root = {
  49608. children: new Array(),
  49609. name: name,
  49610. type: 3,
  49611. properties: new Array() // Empty for root but required
  49612. };
  49613. for (var i = 0; i < this.actions.length; i++) {
  49614. var triggerObject = {
  49615. type: 0,
  49616. children: new Array(),
  49617. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  49618. properties: new Array()
  49619. };
  49620. var triggerOptions = this.actions[i].triggerOptions;
  49621. if (triggerOptions && typeof triggerOptions !== "number") {
  49622. if (triggerOptions.parameter instanceof BABYLON.Node) {
  49623. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  49624. }
  49625. else {
  49626. var parameter = {};
  49627. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  49628. if (triggerOptions.parameter.mesh) {
  49629. parameter._meshId = triggerOptions.parameter.mesh.id;
  49630. }
  49631. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  49632. }
  49633. }
  49634. // Serialize child action, recursively
  49635. this.actions[i].serialize(triggerObject);
  49636. // Add serialized trigger
  49637. root.children.push(triggerObject);
  49638. }
  49639. return root;
  49640. };
  49641. ActionManager.Parse = function (parsedActions, object, scene) {
  49642. var actionManager = new ActionManager(scene);
  49643. if (object === null)
  49644. scene.actionManager = actionManager;
  49645. else
  49646. object.actionManager = actionManager;
  49647. // instanciate a new object
  49648. var instanciate = function (name, params) {
  49649. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  49650. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  49651. newInstance.constructor.apply(newInstance, params);
  49652. return newInstance;
  49653. };
  49654. var parseParameter = function (name, value, target, propertyPath) {
  49655. if (propertyPath === null) {
  49656. // String, boolean or float
  49657. var floatValue = parseFloat(value);
  49658. if (value === "true" || value === "false")
  49659. return value === "true";
  49660. else
  49661. return isNaN(floatValue) ? value : floatValue;
  49662. }
  49663. var effectiveTarget = propertyPath.split(".");
  49664. var values = value.split(",");
  49665. // Get effective Target
  49666. for (var i = 0; i < effectiveTarget.length; i++) {
  49667. target = target[effectiveTarget[i]];
  49668. }
  49669. // Return appropriate value with its type
  49670. if (typeof (target) === "boolean")
  49671. return values[0] === "true";
  49672. if (typeof (target) === "string")
  49673. return values[0];
  49674. // Parameters with multiple values such as Vector3 etc.
  49675. var split = new Array();
  49676. for (var i = 0; i < values.length; i++)
  49677. split.push(parseFloat(values[i]));
  49678. if (target instanceof BABYLON.Vector3)
  49679. return BABYLON.Vector3.FromArray(split);
  49680. if (target instanceof BABYLON.Vector4)
  49681. return BABYLON.Vector4.FromArray(split);
  49682. if (target instanceof BABYLON.Color3)
  49683. return BABYLON.Color3.FromArray(split);
  49684. if (target instanceof BABYLON.Color4)
  49685. return BABYLON.Color4.FromArray(split);
  49686. return parseFloat(values[0]);
  49687. };
  49688. // traverse graph per trigger
  49689. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  49690. if (combineArray === void 0) { combineArray = null; }
  49691. if (parsedAction.detached)
  49692. return;
  49693. var parameters = new Array();
  49694. var target = null;
  49695. var propertyPath = null;
  49696. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  49697. // Parameters
  49698. if (parsedAction.type === 2)
  49699. parameters.push(actionManager);
  49700. else
  49701. parameters.push(trigger);
  49702. if (combine) {
  49703. var actions = new Array();
  49704. for (var j = 0; j < parsedAction.combine.length; j++) {
  49705. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  49706. }
  49707. parameters.push(actions);
  49708. }
  49709. else {
  49710. for (var i = 0; i < parsedAction.properties.length; i++) {
  49711. var value = parsedAction.properties[i].value;
  49712. var name = parsedAction.properties[i].name;
  49713. var targetType = parsedAction.properties[i].targetType;
  49714. if (name === "target")
  49715. if (targetType !== null && targetType === "SceneProperties")
  49716. value = target = scene;
  49717. else
  49718. value = target = scene.getNodeByName(value);
  49719. else if (name === "parent")
  49720. value = scene.getNodeByName(value);
  49721. else if (name === "sound")
  49722. value = scene.getSoundByName(value);
  49723. else if (name !== "propertyPath") {
  49724. if (parsedAction.type === 2 && name === "operator")
  49725. value = BABYLON.ValueCondition[value];
  49726. else
  49727. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  49728. }
  49729. else {
  49730. propertyPath = value;
  49731. }
  49732. parameters.push(value);
  49733. }
  49734. }
  49735. if (combineArray === null) {
  49736. parameters.push(condition);
  49737. }
  49738. else {
  49739. parameters.push(null);
  49740. }
  49741. // If interpolate value action
  49742. if (parsedAction.name === "InterpolateValueAction") {
  49743. var param = parameters[parameters.length - 2];
  49744. parameters[parameters.length - 1] = param;
  49745. parameters[parameters.length - 2] = condition;
  49746. }
  49747. // Action or condition(s) and not CombineAction
  49748. var newAction = instanciate(parsedAction.name, parameters);
  49749. if (newAction instanceof BABYLON.Condition && condition !== null) {
  49750. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  49751. if (action)
  49752. action.then(nothing);
  49753. else
  49754. actionManager.registerAction(nothing);
  49755. action = nothing;
  49756. }
  49757. if (combineArray === null) {
  49758. if (newAction instanceof BABYLON.Condition) {
  49759. condition = newAction;
  49760. newAction = action;
  49761. }
  49762. else {
  49763. condition = null;
  49764. if (action)
  49765. action.then(newAction);
  49766. else
  49767. actionManager.registerAction(newAction);
  49768. }
  49769. }
  49770. else {
  49771. combineArray.push(newAction);
  49772. }
  49773. for (var i = 0; i < parsedAction.children.length; i++)
  49774. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  49775. };
  49776. // triggers
  49777. for (var i = 0; i < parsedActions.children.length; i++) {
  49778. var triggerParams;
  49779. var trigger = parsedActions.children[i];
  49780. if (trigger.properties.length > 0) {
  49781. var param = trigger.properties[0].value;
  49782. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  49783. if (value._meshId) {
  49784. value.mesh = scene.getMeshByID(value._meshId);
  49785. }
  49786. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  49787. }
  49788. else
  49789. triggerParams = ActionManager[trigger.name];
  49790. for (var j = 0; j < trigger.children.length; j++) {
  49791. if (!trigger.detached)
  49792. traverse(trigger.children[j], triggerParams, null, null);
  49793. }
  49794. }
  49795. };
  49796. ActionManager.GetTriggerName = function (trigger) {
  49797. switch (trigger) {
  49798. case 0: return "NothingTrigger";
  49799. case 1: return "OnPickTrigger";
  49800. case 2: return "OnLeftPickTrigger";
  49801. case 3: return "OnRightPickTrigger";
  49802. case 4: return "OnCenterPickTrigger";
  49803. case 5: return "OnPickDownTrigger";
  49804. case 6: return "OnPickUpTrigger";
  49805. case 7: return "OnLongPressTrigger";
  49806. case 8: return "OnPointerOverTrigger";
  49807. case 9: return "OnPointerOutTrigger";
  49808. case 10: return "OnEveryFrameTrigger";
  49809. case 11: return "OnIntersectionEnterTrigger";
  49810. case 12: return "OnIntersectionExitTrigger";
  49811. case 13: return "OnKeyDownTrigger";
  49812. case 14: return "OnKeyUpTrigger";
  49813. case 15: return "OnPickOutTrigger";
  49814. default: return "";
  49815. }
  49816. };
  49817. // Statics
  49818. ActionManager._NothingTrigger = 0;
  49819. ActionManager._OnPickTrigger = 1;
  49820. ActionManager._OnLeftPickTrigger = 2;
  49821. ActionManager._OnRightPickTrigger = 3;
  49822. ActionManager._OnCenterPickTrigger = 4;
  49823. ActionManager._OnPickDownTrigger = 5;
  49824. ActionManager._OnDoublePickTrigger = 6;
  49825. ActionManager._OnPickUpTrigger = 7;
  49826. ActionManager._OnLongPressTrigger = 8;
  49827. ActionManager._OnPointerOverTrigger = 9;
  49828. ActionManager._OnPointerOutTrigger = 10;
  49829. ActionManager._OnEveryFrameTrigger = 11;
  49830. ActionManager._OnIntersectionEnterTrigger = 12;
  49831. ActionManager._OnIntersectionExitTrigger = 13;
  49832. ActionManager._OnKeyDownTrigger = 14;
  49833. ActionManager._OnKeyUpTrigger = 15;
  49834. ActionManager._OnPickOutTrigger = 16;
  49835. ActionManager.Triggers = {};
  49836. return ActionManager;
  49837. }());
  49838. BABYLON.ActionManager = ActionManager;
  49839. })(BABYLON || (BABYLON = {}));
  49840. //# sourceMappingURL=babylon.actionManager.js.map
  49841. "use strict";
  49842. var BABYLON;
  49843. (function (BABYLON) {
  49844. var InterpolateValueAction = /** @class */ (function (_super) {
  49845. __extends(InterpolateValueAction, _super);
  49846. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49847. if (duration === void 0) { duration = 1000; }
  49848. var _this = _super.call(this, triggerOptions, condition) || this;
  49849. _this.propertyPath = propertyPath;
  49850. _this.value = value;
  49851. _this.duration = duration;
  49852. _this.stopOtherAnimations = stopOtherAnimations;
  49853. _this.onInterpolationDone = onInterpolationDone;
  49854. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49855. _this._target = _this._effectiveTarget = target;
  49856. return _this;
  49857. }
  49858. InterpolateValueAction.prototype._prepare = function () {
  49859. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49860. this._property = this._getProperty(this.propertyPath);
  49861. };
  49862. InterpolateValueAction.prototype.execute = function () {
  49863. var _this = this;
  49864. var scene = this._actionManager.getScene();
  49865. var keys = [
  49866. {
  49867. frame: 0,
  49868. value: this._effectiveTarget[this._property]
  49869. }, {
  49870. frame: 100,
  49871. value: this.value
  49872. }
  49873. ];
  49874. var dataType;
  49875. if (typeof this.value === "number") {
  49876. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49877. }
  49878. else if (this.value instanceof BABYLON.Color3) {
  49879. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49880. }
  49881. else if (this.value instanceof BABYLON.Vector3) {
  49882. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49883. }
  49884. else if (this.value instanceof BABYLON.Matrix) {
  49885. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49886. }
  49887. else if (this.value instanceof BABYLON.Quaternion) {
  49888. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49889. }
  49890. else {
  49891. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49892. return;
  49893. }
  49894. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49895. animation.setKeys(keys);
  49896. if (this.stopOtherAnimations) {
  49897. scene.stopAnimation(this._effectiveTarget);
  49898. }
  49899. var wrapper = function () {
  49900. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49901. if (_this.onInterpolationDone) {
  49902. _this.onInterpolationDone();
  49903. }
  49904. };
  49905. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49906. };
  49907. InterpolateValueAction.prototype.serialize = function (parent) {
  49908. return _super.prototype._serialize.call(this, {
  49909. name: "InterpolateValueAction",
  49910. properties: [
  49911. BABYLON.Action._GetTargetProperty(this._target),
  49912. { name: "propertyPath", value: this.propertyPath },
  49913. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49914. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49915. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49916. ]
  49917. }, parent);
  49918. };
  49919. return InterpolateValueAction;
  49920. }(BABYLON.Action));
  49921. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49922. })(BABYLON || (BABYLON = {}));
  49923. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49924. "use strict";
  49925. var BABYLON;
  49926. (function (BABYLON) {
  49927. var SwitchBooleanAction = /** @class */ (function (_super) {
  49928. __extends(SwitchBooleanAction, _super);
  49929. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49930. var _this = _super.call(this, triggerOptions, condition) || this;
  49931. _this.propertyPath = propertyPath;
  49932. _this._target = _this._effectiveTarget = target;
  49933. return _this;
  49934. }
  49935. SwitchBooleanAction.prototype._prepare = function () {
  49936. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49937. this._property = this._getProperty(this.propertyPath);
  49938. };
  49939. SwitchBooleanAction.prototype.execute = function () {
  49940. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49941. };
  49942. SwitchBooleanAction.prototype.serialize = function (parent) {
  49943. return _super.prototype._serialize.call(this, {
  49944. name: "SwitchBooleanAction",
  49945. properties: [
  49946. BABYLON.Action._GetTargetProperty(this._target),
  49947. { name: "propertyPath", value: this.propertyPath }
  49948. ]
  49949. }, parent);
  49950. };
  49951. return SwitchBooleanAction;
  49952. }(BABYLON.Action));
  49953. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49954. var SetStateAction = /** @class */ (function (_super) {
  49955. __extends(SetStateAction, _super);
  49956. function SetStateAction(triggerOptions, target, value, condition) {
  49957. var _this = _super.call(this, triggerOptions, condition) || this;
  49958. _this.value = value;
  49959. _this._target = target;
  49960. return _this;
  49961. }
  49962. SetStateAction.prototype.execute = function () {
  49963. this._target.state = this.value;
  49964. };
  49965. SetStateAction.prototype.serialize = function (parent) {
  49966. return _super.prototype._serialize.call(this, {
  49967. name: "SetStateAction",
  49968. properties: [
  49969. BABYLON.Action._GetTargetProperty(this._target),
  49970. { name: "value", value: this.value }
  49971. ]
  49972. }, parent);
  49973. };
  49974. return SetStateAction;
  49975. }(BABYLON.Action));
  49976. BABYLON.SetStateAction = SetStateAction;
  49977. var SetValueAction = /** @class */ (function (_super) {
  49978. __extends(SetValueAction, _super);
  49979. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49980. var _this = _super.call(this, triggerOptions, condition) || this;
  49981. _this.propertyPath = propertyPath;
  49982. _this.value = value;
  49983. _this._target = _this._effectiveTarget = target;
  49984. return _this;
  49985. }
  49986. SetValueAction.prototype._prepare = function () {
  49987. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49988. this._property = this._getProperty(this.propertyPath);
  49989. };
  49990. SetValueAction.prototype.execute = function () {
  49991. this._effectiveTarget[this._property] = this.value;
  49992. if (this._target.markAsDirty) {
  49993. this._target.markAsDirty(this._property);
  49994. }
  49995. };
  49996. SetValueAction.prototype.serialize = function (parent) {
  49997. return _super.prototype._serialize.call(this, {
  49998. name: "SetValueAction",
  49999. properties: [
  50000. BABYLON.Action._GetTargetProperty(this._target),
  50001. { name: "propertyPath", value: this.propertyPath },
  50002. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  50003. ]
  50004. }, parent);
  50005. };
  50006. return SetValueAction;
  50007. }(BABYLON.Action));
  50008. BABYLON.SetValueAction = SetValueAction;
  50009. var IncrementValueAction = /** @class */ (function (_super) {
  50010. __extends(IncrementValueAction, _super);
  50011. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  50012. var _this = _super.call(this, triggerOptions, condition) || this;
  50013. _this.propertyPath = propertyPath;
  50014. _this.value = value;
  50015. _this._target = _this._effectiveTarget = target;
  50016. return _this;
  50017. }
  50018. IncrementValueAction.prototype._prepare = function () {
  50019. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  50020. this._property = this._getProperty(this.propertyPath);
  50021. if (typeof this._effectiveTarget[this._property] !== "number") {
  50022. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  50023. }
  50024. };
  50025. IncrementValueAction.prototype.execute = function () {
  50026. this._effectiveTarget[this._property] += this.value;
  50027. if (this._target.markAsDirty) {
  50028. this._target.markAsDirty(this._property);
  50029. }
  50030. };
  50031. IncrementValueAction.prototype.serialize = function (parent) {
  50032. return _super.prototype._serialize.call(this, {
  50033. name: "IncrementValueAction",
  50034. properties: [
  50035. BABYLON.Action._GetTargetProperty(this._target),
  50036. { name: "propertyPath", value: this.propertyPath },
  50037. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  50038. ]
  50039. }, parent);
  50040. };
  50041. return IncrementValueAction;
  50042. }(BABYLON.Action));
  50043. BABYLON.IncrementValueAction = IncrementValueAction;
  50044. var PlayAnimationAction = /** @class */ (function (_super) {
  50045. __extends(PlayAnimationAction, _super);
  50046. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  50047. var _this = _super.call(this, triggerOptions, condition) || this;
  50048. _this.from = from;
  50049. _this.to = to;
  50050. _this.loop = loop;
  50051. _this._target = target;
  50052. return _this;
  50053. }
  50054. PlayAnimationAction.prototype._prepare = function () {
  50055. };
  50056. PlayAnimationAction.prototype.execute = function () {
  50057. var scene = this._actionManager.getScene();
  50058. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  50059. };
  50060. PlayAnimationAction.prototype.serialize = function (parent) {
  50061. return _super.prototype._serialize.call(this, {
  50062. name: "PlayAnimationAction",
  50063. properties: [
  50064. BABYLON.Action._GetTargetProperty(this._target),
  50065. { name: "from", value: String(this.from) },
  50066. { name: "to", value: String(this.to) },
  50067. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  50068. ]
  50069. }, parent);
  50070. };
  50071. return PlayAnimationAction;
  50072. }(BABYLON.Action));
  50073. BABYLON.PlayAnimationAction = PlayAnimationAction;
  50074. var StopAnimationAction = /** @class */ (function (_super) {
  50075. __extends(StopAnimationAction, _super);
  50076. function StopAnimationAction(triggerOptions, target, condition) {
  50077. var _this = _super.call(this, triggerOptions, condition) || this;
  50078. _this._target = target;
  50079. return _this;
  50080. }
  50081. StopAnimationAction.prototype._prepare = function () {
  50082. };
  50083. StopAnimationAction.prototype.execute = function () {
  50084. var scene = this._actionManager.getScene();
  50085. scene.stopAnimation(this._target);
  50086. };
  50087. StopAnimationAction.prototype.serialize = function (parent) {
  50088. return _super.prototype._serialize.call(this, {
  50089. name: "StopAnimationAction",
  50090. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  50091. }, parent);
  50092. };
  50093. return StopAnimationAction;
  50094. }(BABYLON.Action));
  50095. BABYLON.StopAnimationAction = StopAnimationAction;
  50096. var DoNothingAction = /** @class */ (function (_super) {
  50097. __extends(DoNothingAction, _super);
  50098. function DoNothingAction(triggerOptions, condition) {
  50099. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  50100. return _super.call(this, triggerOptions, condition) || this;
  50101. }
  50102. DoNothingAction.prototype.execute = function () {
  50103. };
  50104. DoNothingAction.prototype.serialize = function (parent) {
  50105. return _super.prototype._serialize.call(this, {
  50106. name: "DoNothingAction",
  50107. properties: []
  50108. }, parent);
  50109. };
  50110. return DoNothingAction;
  50111. }(BABYLON.Action));
  50112. BABYLON.DoNothingAction = DoNothingAction;
  50113. var CombineAction = /** @class */ (function (_super) {
  50114. __extends(CombineAction, _super);
  50115. function CombineAction(triggerOptions, children, condition) {
  50116. var _this = _super.call(this, triggerOptions, condition) || this;
  50117. _this.children = children;
  50118. return _this;
  50119. }
  50120. CombineAction.prototype._prepare = function () {
  50121. for (var index = 0; index < this.children.length; index++) {
  50122. this.children[index]._actionManager = this._actionManager;
  50123. this.children[index]._prepare();
  50124. }
  50125. };
  50126. CombineAction.prototype.execute = function (evt) {
  50127. for (var index = 0; index < this.children.length; index++) {
  50128. this.children[index].execute(evt);
  50129. }
  50130. };
  50131. CombineAction.prototype.serialize = function (parent) {
  50132. var serializationObject = _super.prototype._serialize.call(this, {
  50133. name: "CombineAction",
  50134. properties: [],
  50135. combine: []
  50136. }, parent);
  50137. for (var i = 0; i < this.children.length; i++) {
  50138. serializationObject.combine.push(this.children[i].serialize(null));
  50139. }
  50140. return serializationObject;
  50141. };
  50142. return CombineAction;
  50143. }(BABYLON.Action));
  50144. BABYLON.CombineAction = CombineAction;
  50145. var ExecuteCodeAction = /** @class */ (function (_super) {
  50146. __extends(ExecuteCodeAction, _super);
  50147. function ExecuteCodeAction(triggerOptions, func, condition) {
  50148. var _this = _super.call(this, triggerOptions, condition) || this;
  50149. _this.func = func;
  50150. return _this;
  50151. }
  50152. ExecuteCodeAction.prototype.execute = function (evt) {
  50153. this.func(evt);
  50154. };
  50155. return ExecuteCodeAction;
  50156. }(BABYLON.Action));
  50157. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  50158. var SetParentAction = /** @class */ (function (_super) {
  50159. __extends(SetParentAction, _super);
  50160. function SetParentAction(triggerOptions, target, parent, condition) {
  50161. var _this = _super.call(this, triggerOptions, condition) || this;
  50162. _this._target = target;
  50163. _this._parent = parent;
  50164. return _this;
  50165. }
  50166. SetParentAction.prototype._prepare = function () {
  50167. };
  50168. SetParentAction.prototype.execute = function () {
  50169. if (this._target.parent === this._parent) {
  50170. return;
  50171. }
  50172. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  50173. invertParentWorldMatrix.invert();
  50174. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  50175. this._target.parent = this._parent;
  50176. };
  50177. SetParentAction.prototype.serialize = function (parent) {
  50178. return _super.prototype._serialize.call(this, {
  50179. name: "SetParentAction",
  50180. properties: [
  50181. BABYLON.Action._GetTargetProperty(this._target),
  50182. BABYLON.Action._GetTargetProperty(this._parent),
  50183. ]
  50184. }, parent);
  50185. };
  50186. return SetParentAction;
  50187. }(BABYLON.Action));
  50188. BABYLON.SetParentAction = SetParentAction;
  50189. var PlaySoundAction = /** @class */ (function (_super) {
  50190. __extends(PlaySoundAction, _super);
  50191. function PlaySoundAction(triggerOptions, sound, condition) {
  50192. var _this = _super.call(this, triggerOptions, condition) || this;
  50193. _this._sound = sound;
  50194. return _this;
  50195. }
  50196. PlaySoundAction.prototype._prepare = function () {
  50197. };
  50198. PlaySoundAction.prototype.execute = function () {
  50199. if (this._sound !== undefined)
  50200. this._sound.play();
  50201. };
  50202. PlaySoundAction.prototype.serialize = function (parent) {
  50203. return _super.prototype._serialize.call(this, {
  50204. name: "PlaySoundAction",
  50205. properties: [{ name: "sound", value: this._sound.name }]
  50206. }, parent);
  50207. };
  50208. return PlaySoundAction;
  50209. }(BABYLON.Action));
  50210. BABYLON.PlaySoundAction = PlaySoundAction;
  50211. var StopSoundAction = /** @class */ (function (_super) {
  50212. __extends(StopSoundAction, _super);
  50213. function StopSoundAction(triggerOptions, sound, condition) {
  50214. var _this = _super.call(this, triggerOptions, condition) || this;
  50215. _this._sound = sound;
  50216. return _this;
  50217. }
  50218. StopSoundAction.prototype._prepare = function () {
  50219. };
  50220. StopSoundAction.prototype.execute = function () {
  50221. if (this._sound !== undefined)
  50222. this._sound.stop();
  50223. };
  50224. StopSoundAction.prototype.serialize = function (parent) {
  50225. return _super.prototype._serialize.call(this, {
  50226. name: "StopSoundAction",
  50227. properties: [{ name: "sound", value: this._sound.name }]
  50228. }, parent);
  50229. };
  50230. return StopSoundAction;
  50231. }(BABYLON.Action));
  50232. BABYLON.StopSoundAction = StopSoundAction;
  50233. })(BABYLON || (BABYLON = {}));
  50234. //# sourceMappingURL=babylon.directActions.js.map
  50235. "use strict";
  50236. var BABYLON;
  50237. (function (BABYLON) {
  50238. var SpriteManager = /** @class */ (function () {
  50239. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  50240. if (epsilon === void 0) { epsilon = 0.01; }
  50241. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50242. this.name = name;
  50243. this.sprites = new Array();
  50244. this.renderingGroupId = 0;
  50245. this.layerMask = 0x0FFFFFFF;
  50246. this.fogEnabled = true;
  50247. this.isPickable = false;
  50248. /**
  50249. * An event triggered when the manager is disposed.
  50250. * @type {BABYLON.Observable}
  50251. */
  50252. this.onDisposeObservable = new BABYLON.Observable();
  50253. this._vertexBuffers = {};
  50254. this._capacity = capacity;
  50255. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  50256. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50257. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50258. if (cellSize.width && cellSize.height) {
  50259. this.cellWidth = cellSize.width;
  50260. this.cellHeight = cellSize.height;
  50261. }
  50262. else if (cellSize !== undefined) {
  50263. this.cellWidth = cellSize;
  50264. this.cellHeight = cellSize;
  50265. }
  50266. else {
  50267. return;
  50268. }
  50269. this._epsilon = epsilon;
  50270. this._scene = scene;
  50271. this._scene.spriteManagers.push(this);
  50272. var indices = [];
  50273. var index = 0;
  50274. for (var count = 0; count < capacity; count++) {
  50275. indices.push(index);
  50276. indices.push(index + 1);
  50277. indices.push(index + 2);
  50278. indices.push(index);
  50279. indices.push(index + 2);
  50280. indices.push(index + 3);
  50281. index += 4;
  50282. }
  50283. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  50284. // VBO
  50285. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  50286. this._vertexData = new Float32Array(capacity * 16 * 4);
  50287. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  50288. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  50289. var options = this._buffer.createVertexBuffer("options", 4, 4);
  50290. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  50291. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  50292. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50293. this._vertexBuffers["options"] = options;
  50294. this._vertexBuffers["cellInfo"] = cellInfo;
  50295. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50296. // Effects
  50297. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  50298. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  50299. }
  50300. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  50301. set: function (callback) {
  50302. if (this._onDisposeObserver) {
  50303. this.onDisposeObservable.remove(this._onDisposeObserver);
  50304. }
  50305. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50306. },
  50307. enumerable: true,
  50308. configurable: true
  50309. });
  50310. Object.defineProperty(SpriteManager.prototype, "texture", {
  50311. get: function () {
  50312. return this._spriteTexture;
  50313. },
  50314. set: function (value) {
  50315. this._spriteTexture = value;
  50316. },
  50317. enumerable: true,
  50318. configurable: true
  50319. });
  50320. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  50321. var arrayOffset = index * 16;
  50322. if (offsetX === 0)
  50323. offsetX = this._epsilon;
  50324. else if (offsetX === 1)
  50325. offsetX = 1 - this._epsilon;
  50326. if (offsetY === 0)
  50327. offsetY = this._epsilon;
  50328. else if (offsetY === 1)
  50329. offsetY = 1 - this._epsilon;
  50330. this._vertexData[arrayOffset] = sprite.position.x;
  50331. this._vertexData[arrayOffset + 1] = sprite.position.y;
  50332. this._vertexData[arrayOffset + 2] = sprite.position.z;
  50333. this._vertexData[arrayOffset + 3] = sprite.angle;
  50334. this._vertexData[arrayOffset + 4] = sprite.width;
  50335. this._vertexData[arrayOffset + 5] = sprite.height;
  50336. this._vertexData[arrayOffset + 6] = offsetX;
  50337. this._vertexData[arrayOffset + 7] = offsetY;
  50338. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  50339. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  50340. var offset = (sprite.cellIndex / rowSize) >> 0;
  50341. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  50342. this._vertexData[arrayOffset + 11] = offset;
  50343. // Color
  50344. this._vertexData[arrayOffset + 12] = sprite.color.r;
  50345. this._vertexData[arrayOffset + 13] = sprite.color.g;
  50346. this._vertexData[arrayOffset + 14] = sprite.color.b;
  50347. this._vertexData[arrayOffset + 15] = sprite.color.a;
  50348. };
  50349. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  50350. var count = Math.min(this._capacity, this.sprites.length);
  50351. var min = BABYLON.Vector3.Zero();
  50352. var max = BABYLON.Vector3.Zero();
  50353. var distance = Number.MAX_VALUE;
  50354. var currentSprite = null;
  50355. var cameraSpacePosition = BABYLON.Vector3.Zero();
  50356. var cameraView = camera.getViewMatrix();
  50357. for (var index = 0; index < count; index++) {
  50358. var sprite = this.sprites[index];
  50359. if (!sprite) {
  50360. continue;
  50361. }
  50362. if (predicate) {
  50363. if (!predicate(sprite)) {
  50364. continue;
  50365. }
  50366. }
  50367. else if (!sprite.isPickable) {
  50368. continue;
  50369. }
  50370. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  50371. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  50372. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  50373. if (ray.intersectsBoxMinMax(min, max)) {
  50374. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  50375. if (distance > currentDistance) {
  50376. distance = currentDistance;
  50377. currentSprite = sprite;
  50378. if (fastCheck) {
  50379. break;
  50380. }
  50381. }
  50382. }
  50383. }
  50384. if (currentSprite) {
  50385. var result = new BABYLON.PickingInfo();
  50386. result.hit = true;
  50387. result.pickedSprite = currentSprite;
  50388. result.distance = distance;
  50389. return result;
  50390. }
  50391. return null;
  50392. };
  50393. SpriteManager.prototype.render = function () {
  50394. // Check
  50395. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  50396. return;
  50397. var engine = this._scene.getEngine();
  50398. var baseSize = this._spriteTexture.getBaseSize();
  50399. // Sprites
  50400. var deltaTime = engine.getDeltaTime();
  50401. var max = Math.min(this._capacity, this.sprites.length);
  50402. var rowSize = baseSize.width / this.cellWidth;
  50403. var offset = 0;
  50404. for (var index = 0; index < max; index++) {
  50405. var sprite = this.sprites[index];
  50406. if (!sprite) {
  50407. continue;
  50408. }
  50409. sprite._animate(deltaTime);
  50410. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  50411. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  50412. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  50413. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  50414. }
  50415. this._buffer.update(this._vertexData);
  50416. // Render
  50417. var effect = this._effectBase;
  50418. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50419. effect = this._effectFog;
  50420. }
  50421. engine.enableEffect(effect);
  50422. var viewMatrix = this._scene.getViewMatrix();
  50423. effect.setTexture("diffuseSampler", this._spriteTexture);
  50424. effect.setMatrix("view", viewMatrix);
  50425. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50426. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  50427. // Fog
  50428. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50429. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  50430. effect.setColor3("vFogColor", this._scene.fogColor);
  50431. }
  50432. // VBOs
  50433. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50434. // Draw order
  50435. engine.setDepthFunctionToLessOrEqual();
  50436. effect.setBool("alphaTest", true);
  50437. engine.setColorWrite(false);
  50438. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50439. engine.setColorWrite(true);
  50440. effect.setBool("alphaTest", false);
  50441. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50442. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50443. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50444. };
  50445. SpriteManager.prototype.dispose = function () {
  50446. if (this._buffer) {
  50447. this._buffer.dispose();
  50448. this._buffer = null;
  50449. }
  50450. if (this._indexBuffer) {
  50451. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50452. this._indexBuffer = null;
  50453. }
  50454. if (this._spriteTexture) {
  50455. this._spriteTexture.dispose();
  50456. this._spriteTexture = null;
  50457. }
  50458. // Remove from scene
  50459. var index = this._scene.spriteManagers.indexOf(this);
  50460. this._scene.spriteManagers.splice(index, 1);
  50461. // Callback
  50462. this.onDisposeObservable.notifyObservers(this);
  50463. this.onDisposeObservable.clear();
  50464. };
  50465. return SpriteManager;
  50466. }());
  50467. BABYLON.SpriteManager = SpriteManager;
  50468. })(BABYLON || (BABYLON = {}));
  50469. //# sourceMappingURL=babylon.spriteManager.js.map
  50470. "use strict";
  50471. var BABYLON;
  50472. (function (BABYLON) {
  50473. var Sprite = /** @class */ (function () {
  50474. function Sprite(name, manager) {
  50475. this.name = name;
  50476. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50477. this.width = 1.0;
  50478. this.height = 1.0;
  50479. this.angle = 0;
  50480. this.cellIndex = 0;
  50481. this.invertU = 0;
  50482. this.invertV = 0;
  50483. this.animations = new Array();
  50484. this.isPickable = false;
  50485. this._animationStarted = false;
  50486. this._loopAnimation = false;
  50487. this._fromIndex = 0;
  50488. this._toIndex = 0;
  50489. this._delay = 0;
  50490. this._direction = 1;
  50491. this._time = 0;
  50492. this._manager = manager;
  50493. this._manager.sprites.push(this);
  50494. this.position = BABYLON.Vector3.Zero();
  50495. }
  50496. Object.defineProperty(Sprite.prototype, "size", {
  50497. get: function () {
  50498. return this.width;
  50499. },
  50500. set: function (value) {
  50501. this.width = value;
  50502. this.height = value;
  50503. },
  50504. enumerable: true,
  50505. configurable: true
  50506. });
  50507. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  50508. this._fromIndex = from;
  50509. this._toIndex = to;
  50510. this._loopAnimation = loop;
  50511. this._delay = delay;
  50512. this._animationStarted = true;
  50513. this._direction = from < to ? 1 : -1;
  50514. this.cellIndex = from;
  50515. this._time = 0;
  50516. this._onAnimationEnd = onAnimationEnd;
  50517. };
  50518. Sprite.prototype.stopAnimation = function () {
  50519. this._animationStarted = false;
  50520. };
  50521. Sprite.prototype._animate = function (deltaTime) {
  50522. if (!this._animationStarted)
  50523. return;
  50524. this._time += deltaTime;
  50525. if (this._time > this._delay) {
  50526. this._time = this._time % this._delay;
  50527. this.cellIndex += this._direction;
  50528. if (this.cellIndex > this._toIndex) {
  50529. if (this._loopAnimation) {
  50530. this.cellIndex = this._fromIndex;
  50531. }
  50532. else {
  50533. this.cellIndex = this._toIndex;
  50534. this._animationStarted = false;
  50535. if (this._onAnimationEnd) {
  50536. this._onAnimationEnd();
  50537. }
  50538. if (this.disposeWhenFinishedAnimating) {
  50539. this.dispose();
  50540. }
  50541. }
  50542. }
  50543. }
  50544. };
  50545. Sprite.prototype.dispose = function () {
  50546. for (var i = 0; i < this._manager.sprites.length; i++) {
  50547. if (this._manager.sprites[i] == this) {
  50548. this._manager.sprites.splice(i, 1);
  50549. }
  50550. }
  50551. };
  50552. return Sprite;
  50553. }());
  50554. BABYLON.Sprite = Sprite;
  50555. })(BABYLON || (BABYLON = {}));
  50556. //# sourceMappingURL=babylon.sprite.js.map
  50557. "use strict";
  50558. var BABYLON;
  50559. (function (BABYLON) {
  50560. var IntersectionInfo = /** @class */ (function () {
  50561. function IntersectionInfo(bu, bv, distance) {
  50562. this.bu = bu;
  50563. this.bv = bv;
  50564. this.distance = distance;
  50565. this.faceId = 0;
  50566. this.subMeshId = 0;
  50567. }
  50568. return IntersectionInfo;
  50569. }());
  50570. BABYLON.IntersectionInfo = IntersectionInfo;
  50571. var PickingInfo = /** @class */ (function () {
  50572. function PickingInfo() {
  50573. this.hit = false;
  50574. this.distance = 0;
  50575. this.pickedPoint = null;
  50576. this.pickedMesh = null;
  50577. this.bu = 0;
  50578. this.bv = 0;
  50579. this.faceId = -1;
  50580. this.subMeshId = 0;
  50581. this.pickedSprite = null;
  50582. }
  50583. // Methods
  50584. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  50585. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  50586. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  50587. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50588. return null;
  50589. }
  50590. var indices = this.pickedMesh.getIndices();
  50591. if (!indices) {
  50592. return null;
  50593. }
  50594. var result;
  50595. if (useVerticesNormals) {
  50596. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50597. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  50598. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  50599. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  50600. normal0 = normal0.scale(this.bu);
  50601. normal1 = normal1.scale(this.bv);
  50602. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  50603. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  50604. }
  50605. else {
  50606. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50607. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  50608. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  50609. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  50610. var p1p2 = vertex1.subtract(vertex2);
  50611. var p3p2 = vertex3.subtract(vertex2);
  50612. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  50613. }
  50614. if (useWorldCoordinates) {
  50615. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  50616. }
  50617. return BABYLON.Vector3.Normalize(result);
  50618. };
  50619. PickingInfo.prototype.getTextureCoordinates = function () {
  50620. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50621. return null;
  50622. }
  50623. var indices = this.pickedMesh.getIndices();
  50624. if (!indices) {
  50625. return null;
  50626. }
  50627. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50628. if (!uvs) {
  50629. return null;
  50630. }
  50631. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  50632. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  50633. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  50634. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  50635. uv1 = uv1.scale(this.bu);
  50636. uv2 = uv2.scale(this.bv);
  50637. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  50638. };
  50639. return PickingInfo;
  50640. }());
  50641. BABYLON.PickingInfo = PickingInfo;
  50642. })(BABYLON || (BABYLON = {}));
  50643. //# sourceMappingURL=babylon.pickingInfo.js.map
  50644. "use strict";
  50645. var BABYLON;
  50646. (function (BABYLON) {
  50647. var Ray = /** @class */ (function () {
  50648. function Ray(origin, direction, length) {
  50649. if (length === void 0) { length = Number.MAX_VALUE; }
  50650. this.origin = origin;
  50651. this.direction = direction;
  50652. this.length = length;
  50653. }
  50654. // Methods
  50655. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  50656. var d = 0.0;
  50657. var maxValue = Number.MAX_VALUE;
  50658. var inv;
  50659. var min;
  50660. var max;
  50661. var temp;
  50662. if (Math.abs(this.direction.x) < 0.0000001) {
  50663. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  50664. return false;
  50665. }
  50666. }
  50667. else {
  50668. inv = 1.0 / this.direction.x;
  50669. min = (minimum.x - this.origin.x) * inv;
  50670. max = (maximum.x - this.origin.x) * inv;
  50671. if (max === -Infinity) {
  50672. max = Infinity;
  50673. }
  50674. if (min > max) {
  50675. temp = min;
  50676. min = max;
  50677. max = temp;
  50678. }
  50679. d = Math.max(min, d);
  50680. maxValue = Math.min(max, maxValue);
  50681. if (d > maxValue) {
  50682. return false;
  50683. }
  50684. }
  50685. if (Math.abs(this.direction.y) < 0.0000001) {
  50686. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  50687. return false;
  50688. }
  50689. }
  50690. else {
  50691. inv = 1.0 / this.direction.y;
  50692. min = (minimum.y - this.origin.y) * inv;
  50693. max = (maximum.y - this.origin.y) * inv;
  50694. if (max === -Infinity) {
  50695. max = Infinity;
  50696. }
  50697. if (min > max) {
  50698. temp = min;
  50699. min = max;
  50700. max = temp;
  50701. }
  50702. d = Math.max(min, d);
  50703. maxValue = Math.min(max, maxValue);
  50704. if (d > maxValue) {
  50705. return false;
  50706. }
  50707. }
  50708. if (Math.abs(this.direction.z) < 0.0000001) {
  50709. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  50710. return false;
  50711. }
  50712. }
  50713. else {
  50714. inv = 1.0 / this.direction.z;
  50715. min = (minimum.z - this.origin.z) * inv;
  50716. max = (maximum.z - this.origin.z) * inv;
  50717. if (max === -Infinity) {
  50718. max = Infinity;
  50719. }
  50720. if (min > max) {
  50721. temp = min;
  50722. min = max;
  50723. max = temp;
  50724. }
  50725. d = Math.max(min, d);
  50726. maxValue = Math.min(max, maxValue);
  50727. if (d > maxValue) {
  50728. return false;
  50729. }
  50730. }
  50731. return true;
  50732. };
  50733. Ray.prototype.intersectsBox = function (box) {
  50734. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  50735. };
  50736. Ray.prototype.intersectsSphere = function (sphere) {
  50737. var x = sphere.center.x - this.origin.x;
  50738. var y = sphere.center.y - this.origin.y;
  50739. var z = sphere.center.z - this.origin.z;
  50740. var pyth = (x * x) + (y * y) + (z * z);
  50741. var rr = sphere.radius * sphere.radius;
  50742. if (pyth <= rr) {
  50743. return true;
  50744. }
  50745. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  50746. if (dot < 0.0) {
  50747. return false;
  50748. }
  50749. var temp = pyth - (dot * dot);
  50750. return temp <= rr;
  50751. };
  50752. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  50753. if (!this._edge1) {
  50754. this._edge1 = BABYLON.Vector3.Zero();
  50755. this._edge2 = BABYLON.Vector3.Zero();
  50756. this._pvec = BABYLON.Vector3.Zero();
  50757. this._tvec = BABYLON.Vector3.Zero();
  50758. this._qvec = BABYLON.Vector3.Zero();
  50759. }
  50760. vertex1.subtractToRef(vertex0, this._edge1);
  50761. vertex2.subtractToRef(vertex0, this._edge2);
  50762. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  50763. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  50764. if (det === 0) {
  50765. return null;
  50766. }
  50767. var invdet = 1 / det;
  50768. this.origin.subtractToRef(vertex0, this._tvec);
  50769. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  50770. if (bu < 0 || bu > 1.0) {
  50771. return null;
  50772. }
  50773. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  50774. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  50775. if (bv < 0 || bu + bv > 1.0) {
  50776. return null;
  50777. }
  50778. //check if the distance is longer than the predefined length.
  50779. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  50780. if (distance > this.length) {
  50781. return null;
  50782. }
  50783. return new BABYLON.IntersectionInfo(bu, bv, distance);
  50784. };
  50785. Ray.prototype.intersectsPlane = function (plane) {
  50786. var distance;
  50787. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  50788. if (Math.abs(result1) < 9.99999997475243E-07) {
  50789. return null;
  50790. }
  50791. else {
  50792. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  50793. distance = (-plane.d - result2) / result1;
  50794. if (distance < 0.0) {
  50795. if (distance < -9.99999997475243E-07) {
  50796. return null;
  50797. }
  50798. else {
  50799. return 0;
  50800. }
  50801. }
  50802. return distance;
  50803. }
  50804. };
  50805. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  50806. var tm = BABYLON.Tmp.Matrix[0];
  50807. mesh.getWorldMatrix().invertToRef(tm);
  50808. if (this._tmpRay) {
  50809. Ray.TransformToRef(this, tm, this._tmpRay);
  50810. }
  50811. else {
  50812. this._tmpRay = Ray.Transform(this, tm);
  50813. }
  50814. return mesh.intersects(this._tmpRay, fastCheck);
  50815. };
  50816. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50817. if (results) {
  50818. results.length = 0;
  50819. }
  50820. else {
  50821. results = [];
  50822. }
  50823. for (var i = 0; i < meshes.length; i++) {
  50824. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50825. if (pickInfo.hit) {
  50826. results.push(pickInfo);
  50827. }
  50828. }
  50829. results.sort(this._comparePickingInfo);
  50830. return results;
  50831. };
  50832. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50833. if (pickingInfoA.distance < pickingInfoB.distance) {
  50834. return -1;
  50835. }
  50836. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50837. return 1;
  50838. }
  50839. else {
  50840. return 0;
  50841. }
  50842. };
  50843. /**
  50844. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50845. * @param sega the first point of the segment to test the intersection against
  50846. * @param segb the second point of the segment to test the intersection against
  50847. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50848. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50849. */
  50850. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50851. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50852. var u = segb.subtract(sega);
  50853. var v = rsegb.subtract(this.origin);
  50854. var w = sega.subtract(this.origin);
  50855. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50856. var b = BABYLON.Vector3.Dot(u, v);
  50857. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50858. var d = BABYLON.Vector3.Dot(u, w);
  50859. var e = BABYLON.Vector3.Dot(v, w);
  50860. var D = a * c - b * b; // always >= 0
  50861. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50862. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50863. // compute the line parameters of the two closest points
  50864. if (D < Ray.smallnum) {
  50865. sN = 0.0; // force using point P0 on segment S1
  50866. sD = 1.0; // to prevent possible division by 0.0 later
  50867. tN = e;
  50868. tD = c;
  50869. }
  50870. else {
  50871. sN = (b * e - c * d);
  50872. tN = (a * e - b * d);
  50873. if (sN < 0.0) {
  50874. sN = 0.0;
  50875. tN = e;
  50876. tD = c;
  50877. }
  50878. else if (sN > sD) {
  50879. sN = sD;
  50880. tN = e + b;
  50881. tD = c;
  50882. }
  50883. }
  50884. if (tN < 0.0) {
  50885. tN = 0.0;
  50886. // recompute sc for this edge
  50887. if (-d < 0.0) {
  50888. sN = 0.0;
  50889. }
  50890. else if (-d > a)
  50891. sN = sD;
  50892. else {
  50893. sN = -d;
  50894. sD = a;
  50895. }
  50896. }
  50897. else if (tN > tD) {
  50898. tN = tD;
  50899. // recompute sc for this edge
  50900. if ((-d + b) < 0.0) {
  50901. sN = 0;
  50902. }
  50903. else if ((-d + b) > a) {
  50904. sN = sD;
  50905. }
  50906. else {
  50907. sN = (-d + b);
  50908. sD = a;
  50909. }
  50910. }
  50911. // finally do the division to get sc and tc
  50912. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50913. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50914. // get the difference of the two closest points
  50915. var qtc = v.multiplyByFloats(tc, tc, tc);
  50916. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50917. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50918. if (isIntersected) {
  50919. return qtc.length();
  50920. }
  50921. return -1;
  50922. };
  50923. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50924. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50925. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50926. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50927. this.direction.normalize();
  50928. return this;
  50929. };
  50930. // Statics
  50931. Ray.Zero = function () {
  50932. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50933. };
  50934. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50935. var result = Ray.Zero();
  50936. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50937. };
  50938. /**
  50939. * 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
  50940. * transformed to the given world matrix.
  50941. * @param origin The origin point
  50942. * @param end The end point
  50943. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50944. */
  50945. Ray.CreateNewFromTo = function (origin, end, world) {
  50946. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50947. var direction = end.subtract(origin);
  50948. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50949. direction.normalize();
  50950. return Ray.Transform(new Ray(origin, direction, length), world);
  50951. };
  50952. Ray.Transform = function (ray, matrix) {
  50953. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50954. Ray.TransformToRef(ray, matrix, result);
  50955. return result;
  50956. };
  50957. Ray.TransformToRef = function (ray, matrix, result) {
  50958. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50959. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50960. result.length = ray.length;
  50961. var dir = result.direction;
  50962. var len = dir.length();
  50963. if (!(len === 0 || len === 1)) {
  50964. var num = 1.0 / len;
  50965. dir.x *= num;
  50966. dir.y *= num;
  50967. dir.z *= num;
  50968. result.length *= len;
  50969. }
  50970. };
  50971. Ray.smallnum = 0.00000001;
  50972. Ray.rayl = 10e8;
  50973. return Ray;
  50974. }());
  50975. BABYLON.Ray = Ray;
  50976. })(BABYLON || (BABYLON = {}));
  50977. //# sourceMappingURL=babylon.ray.js.map
  50978. "use strict";
  50979. var BABYLON;
  50980. (function (BABYLON) {
  50981. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50982. if (boxMin.x > sphereCenter.x + sphereRadius)
  50983. return false;
  50984. if (sphereCenter.x - sphereRadius > boxMax.x)
  50985. return false;
  50986. if (boxMin.y > sphereCenter.y + sphereRadius)
  50987. return false;
  50988. if (sphereCenter.y - sphereRadius > boxMax.y)
  50989. return false;
  50990. if (boxMin.z > sphereCenter.z + sphereRadius)
  50991. return false;
  50992. if (sphereCenter.z - sphereRadius > boxMax.z)
  50993. return false;
  50994. return true;
  50995. };
  50996. var getLowestRoot = (function () {
  50997. var result = { root: 0, found: false };
  50998. return function (a, b, c, maxR) {
  50999. result.root = 0;
  51000. result.found = false;
  51001. var determinant = b * b - 4.0 * a * c;
  51002. if (determinant < 0)
  51003. return result;
  51004. var sqrtD = Math.sqrt(determinant);
  51005. var r1 = (-b - sqrtD) / (2.0 * a);
  51006. var r2 = (-b + sqrtD) / (2.0 * a);
  51007. if (r1 > r2) {
  51008. var temp = r2;
  51009. r2 = r1;
  51010. r1 = temp;
  51011. }
  51012. if (r1 > 0 && r1 < maxR) {
  51013. result.root = r1;
  51014. result.found = true;
  51015. return result;
  51016. }
  51017. if (r2 > 0 && r2 < maxR) {
  51018. result.root = r2;
  51019. result.found = true;
  51020. return result;
  51021. }
  51022. return result;
  51023. };
  51024. })();
  51025. var Collider = /** @class */ (function () {
  51026. function Collider() {
  51027. this._collisionPoint = BABYLON.Vector3.Zero();
  51028. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  51029. this._tempVector = BABYLON.Vector3.Zero();
  51030. this._tempVector2 = BABYLON.Vector3.Zero();
  51031. this._tempVector3 = BABYLON.Vector3.Zero();
  51032. this._tempVector4 = BABYLON.Vector3.Zero();
  51033. this._edge = BABYLON.Vector3.Zero();
  51034. this._baseToVertex = BABYLON.Vector3.Zero();
  51035. this._destinationPoint = BABYLON.Vector3.Zero();
  51036. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  51037. this._displacementVector = BABYLON.Vector3.Zero();
  51038. this._radius = BABYLON.Vector3.One();
  51039. this._retry = 0;
  51040. this._basePointWorld = BABYLON.Vector3.Zero();
  51041. this._velocityWorld = BABYLON.Vector3.Zero();
  51042. this._normalizedVelocity = BABYLON.Vector3.Zero();
  51043. this._collisionMask = -1;
  51044. }
  51045. Object.defineProperty(Collider.prototype, "collisionMask", {
  51046. get: function () {
  51047. return this._collisionMask;
  51048. },
  51049. set: function (mask) {
  51050. this._collisionMask = !isNaN(mask) ? mask : -1;
  51051. },
  51052. enumerable: true,
  51053. configurable: true
  51054. });
  51055. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  51056. /**
  51057. * Gets the plane normal used to compute the sliding response (in local space)
  51058. */
  51059. get: function () {
  51060. return this._slidePlaneNormal;
  51061. },
  51062. enumerable: true,
  51063. configurable: true
  51064. });
  51065. // Methods
  51066. Collider.prototype._initialize = function (source, dir, e) {
  51067. this._velocity = dir;
  51068. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  51069. this._basePoint = source;
  51070. source.multiplyToRef(this._radius, this._basePointWorld);
  51071. dir.multiplyToRef(this._radius, this._velocityWorld);
  51072. this._velocityWorldLength = this._velocityWorld.length();
  51073. this._epsilon = e;
  51074. this.collisionFound = false;
  51075. };
  51076. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  51077. pa.subtractToRef(point, this._tempVector);
  51078. pb.subtractToRef(point, this._tempVector2);
  51079. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  51080. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51081. if (d < 0)
  51082. return false;
  51083. pc.subtractToRef(point, this._tempVector3);
  51084. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  51085. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51086. if (d < 0)
  51087. return false;
  51088. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  51089. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51090. return d >= 0;
  51091. };
  51092. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  51093. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  51094. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  51095. if (distance > this._velocityWorldLength + max + sphereRadius) {
  51096. return false;
  51097. }
  51098. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  51099. return false;
  51100. return true;
  51101. };
  51102. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  51103. var t0;
  51104. var embeddedInPlane = false;
  51105. //defensive programming, actually not needed.
  51106. if (!trianglePlaneArray) {
  51107. trianglePlaneArray = [];
  51108. }
  51109. if (!trianglePlaneArray[faceIndex]) {
  51110. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  51111. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  51112. }
  51113. var trianglePlane = trianglePlaneArray[faceIndex];
  51114. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  51115. return;
  51116. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  51117. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  51118. if (normalDotVelocity == 0) {
  51119. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  51120. return;
  51121. embeddedInPlane = true;
  51122. t0 = 0;
  51123. }
  51124. else {
  51125. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  51126. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  51127. if (t0 > t1) {
  51128. var temp = t1;
  51129. t1 = t0;
  51130. t0 = temp;
  51131. }
  51132. if (t0 > 1.0 || t1 < 0.0)
  51133. return;
  51134. if (t0 < 0)
  51135. t0 = 0;
  51136. if (t0 > 1.0)
  51137. t0 = 1.0;
  51138. }
  51139. this._collisionPoint.copyFromFloats(0, 0, 0);
  51140. var found = false;
  51141. var t = 1.0;
  51142. if (!embeddedInPlane) {
  51143. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  51144. this._velocity.scaleToRef(t0, this._tempVector);
  51145. this._planeIntersectionPoint.addInPlace(this._tempVector);
  51146. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  51147. found = true;
  51148. t = t0;
  51149. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  51150. }
  51151. }
  51152. if (!found) {
  51153. var velocitySquaredLength = this._velocity.lengthSquared();
  51154. var a = velocitySquaredLength;
  51155. this._basePoint.subtractToRef(p1, this._tempVector);
  51156. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51157. var c = this._tempVector.lengthSquared() - 1.0;
  51158. var lowestRoot = getLowestRoot(a, b, c, t);
  51159. if (lowestRoot.found) {
  51160. t = lowestRoot.root;
  51161. found = true;
  51162. this._collisionPoint.copyFrom(p1);
  51163. }
  51164. this._basePoint.subtractToRef(p2, this._tempVector);
  51165. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51166. c = this._tempVector.lengthSquared() - 1.0;
  51167. lowestRoot = getLowestRoot(a, b, c, t);
  51168. if (lowestRoot.found) {
  51169. t = lowestRoot.root;
  51170. found = true;
  51171. this._collisionPoint.copyFrom(p2);
  51172. }
  51173. this._basePoint.subtractToRef(p3, this._tempVector);
  51174. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51175. c = this._tempVector.lengthSquared() - 1.0;
  51176. lowestRoot = getLowestRoot(a, b, c, t);
  51177. if (lowestRoot.found) {
  51178. t = lowestRoot.root;
  51179. found = true;
  51180. this._collisionPoint.copyFrom(p3);
  51181. }
  51182. p2.subtractToRef(p1, this._edge);
  51183. p1.subtractToRef(this._basePoint, this._baseToVertex);
  51184. var edgeSquaredLength = this._edge.lengthSquared();
  51185. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51186. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51187. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51188. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51189. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51190. lowestRoot = getLowestRoot(a, b, c, t);
  51191. if (lowestRoot.found) {
  51192. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51193. if (f >= 0.0 && f <= 1.0) {
  51194. t = lowestRoot.root;
  51195. found = true;
  51196. this._edge.scaleInPlace(f);
  51197. p1.addToRef(this._edge, this._collisionPoint);
  51198. }
  51199. }
  51200. p3.subtractToRef(p2, this._edge);
  51201. p2.subtractToRef(this._basePoint, this._baseToVertex);
  51202. edgeSquaredLength = this._edge.lengthSquared();
  51203. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51204. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51205. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51206. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51207. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51208. lowestRoot = getLowestRoot(a, b, c, t);
  51209. if (lowestRoot.found) {
  51210. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51211. if (f >= 0.0 && f <= 1.0) {
  51212. t = lowestRoot.root;
  51213. found = true;
  51214. this._edge.scaleInPlace(f);
  51215. p2.addToRef(this._edge, this._collisionPoint);
  51216. }
  51217. }
  51218. p1.subtractToRef(p3, this._edge);
  51219. p3.subtractToRef(this._basePoint, this._baseToVertex);
  51220. edgeSquaredLength = this._edge.lengthSquared();
  51221. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51222. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51223. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51224. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51225. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51226. lowestRoot = getLowestRoot(a, b, c, t);
  51227. if (lowestRoot.found) {
  51228. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51229. if (f >= 0.0 && f <= 1.0) {
  51230. t = lowestRoot.root;
  51231. found = true;
  51232. this._edge.scaleInPlace(f);
  51233. p3.addToRef(this._edge, this._collisionPoint);
  51234. }
  51235. }
  51236. }
  51237. if (found) {
  51238. var distToCollision = t * this._velocity.length();
  51239. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  51240. if (!this.intersectionPoint) {
  51241. this.intersectionPoint = this._collisionPoint.clone();
  51242. }
  51243. else {
  51244. this.intersectionPoint.copyFrom(this._collisionPoint);
  51245. }
  51246. this._nearestDistance = distToCollision;
  51247. this.collisionFound = true;
  51248. }
  51249. }
  51250. };
  51251. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  51252. for (var i = indexStart; i < indexEnd; i += 3) {
  51253. var p1 = pts[indices[i] - decal];
  51254. var p2 = pts[indices[i + 1] - decal];
  51255. var p3 = pts[indices[i + 2] - decal];
  51256. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  51257. }
  51258. };
  51259. Collider.prototype._getResponse = function (pos, vel) {
  51260. pos.addToRef(vel, this._destinationPoint);
  51261. vel.scaleInPlace((this._nearestDistance / vel.length()));
  51262. this._basePoint.addToRef(vel, pos);
  51263. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  51264. this._slidePlaneNormal.normalize();
  51265. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  51266. pos.addInPlace(this._displacementVector);
  51267. this.intersectionPoint.addInPlace(this._displacementVector);
  51268. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  51269. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  51270. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  51271. };
  51272. return Collider;
  51273. }());
  51274. BABYLON.Collider = Collider;
  51275. })(BABYLON || (BABYLON = {}));
  51276. //# sourceMappingURL=babylon.collider.js.map
  51277. "use strict";
  51278. var BABYLON;
  51279. (function (BABYLON) {
  51280. //WebWorker code will be inserted to this variable.
  51281. BABYLON.CollisionWorker = "";
  51282. var WorkerTaskType;
  51283. (function (WorkerTaskType) {
  51284. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  51285. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  51286. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  51287. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  51288. var WorkerReplyType;
  51289. (function (WorkerReplyType) {
  51290. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  51291. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  51292. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  51293. var CollisionCoordinatorWorker = /** @class */ (function () {
  51294. function CollisionCoordinatorWorker() {
  51295. var _this = this;
  51296. this._scaledPosition = BABYLON.Vector3.Zero();
  51297. this._scaledVelocity = BABYLON.Vector3.Zero();
  51298. this.onMeshUpdated = function (transformNode) {
  51299. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  51300. };
  51301. this.onGeometryUpdated = function (geometry) {
  51302. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  51303. };
  51304. this._afterRender = function () {
  51305. if (!_this._init)
  51306. return;
  51307. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  51308. return;
  51309. }
  51310. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  51311. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  51312. if (_this._runningUpdated > 4) {
  51313. return;
  51314. }
  51315. ++_this._runningUpdated;
  51316. var payload = {
  51317. updatedMeshes: _this._addUpdateMeshesList,
  51318. updatedGeometries: _this._addUpdateGeometriesList,
  51319. removedGeometries: _this._toRemoveGeometryArray,
  51320. removedMeshes: _this._toRemoveMeshesArray
  51321. };
  51322. var message = {
  51323. payload: payload,
  51324. taskType: WorkerTaskType.UPDATE
  51325. };
  51326. var serializable = [];
  51327. for (var id in payload.updatedGeometries) {
  51328. if (payload.updatedGeometries.hasOwnProperty(id)) {
  51329. //prepare transferables
  51330. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  51331. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  51332. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  51333. }
  51334. }
  51335. _this._worker.postMessage(message, serializable);
  51336. _this._addUpdateMeshesList = {};
  51337. _this._addUpdateGeometriesList = {};
  51338. _this._toRemoveGeometryArray = [];
  51339. _this._toRemoveMeshesArray = [];
  51340. };
  51341. this._onMessageFromWorker = function (e) {
  51342. var returnData = e.data;
  51343. if (returnData.error != WorkerReplyType.SUCCESS) {
  51344. //TODO what errors can be returned from the worker?
  51345. BABYLON.Tools.Warn("error returned from worker!");
  51346. return;
  51347. }
  51348. switch (returnData.taskType) {
  51349. case WorkerTaskType.INIT:
  51350. _this._init = true;
  51351. //Update the worked with ALL of the scene's current state
  51352. _this._scene.meshes.forEach(function (mesh) {
  51353. _this.onMeshAdded(mesh);
  51354. });
  51355. _this._scene.getGeometries().forEach(function (geometry) {
  51356. _this.onGeometryAdded(geometry);
  51357. });
  51358. break;
  51359. case WorkerTaskType.UPDATE:
  51360. _this._runningUpdated--;
  51361. break;
  51362. case WorkerTaskType.COLLIDE:
  51363. var returnPayload = returnData.payload;
  51364. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  51365. return;
  51366. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  51367. if (callback) {
  51368. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  51369. if (mesh) {
  51370. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  51371. }
  51372. }
  51373. //cleanup
  51374. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  51375. break;
  51376. }
  51377. };
  51378. this._collisionsCallbackArray = [];
  51379. this._init = false;
  51380. this._runningUpdated = 0;
  51381. this._addUpdateMeshesList = {};
  51382. this._addUpdateGeometriesList = {};
  51383. this._toRemoveGeometryArray = [];
  51384. this._toRemoveMeshesArray = [];
  51385. }
  51386. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51387. if (!this._init)
  51388. return;
  51389. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  51390. return;
  51391. position.divideToRef(collider._radius, this._scaledPosition);
  51392. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51393. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  51394. var payload = {
  51395. collider: {
  51396. position: this._scaledPosition.asArray(),
  51397. velocity: this._scaledVelocity.asArray(),
  51398. radius: collider._radius.asArray()
  51399. },
  51400. collisionId: collisionIndex,
  51401. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  51402. maximumRetry: maximumRetry
  51403. };
  51404. var message = {
  51405. payload: payload,
  51406. taskType: WorkerTaskType.COLLIDE
  51407. };
  51408. this._worker.postMessage(message);
  51409. };
  51410. CollisionCoordinatorWorker.prototype.init = function (scene) {
  51411. this._scene = scene;
  51412. this._scene.registerAfterRender(this._afterRender);
  51413. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  51414. this._worker = new Worker(workerUrl);
  51415. this._worker.onmessage = this._onMessageFromWorker;
  51416. var message = {
  51417. payload: {},
  51418. taskType: WorkerTaskType.INIT
  51419. };
  51420. this._worker.postMessage(message);
  51421. };
  51422. CollisionCoordinatorWorker.prototype.destroy = function () {
  51423. this._scene.unregisterAfterRender(this._afterRender);
  51424. this._worker.terminate();
  51425. };
  51426. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  51427. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  51428. this.onMeshUpdated(mesh);
  51429. };
  51430. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  51431. this._toRemoveMeshesArray.push(mesh.uniqueId);
  51432. };
  51433. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  51434. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  51435. geometry.onGeometryUpdated = this.onGeometryUpdated;
  51436. this.onGeometryUpdated(geometry);
  51437. };
  51438. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  51439. this._toRemoveGeometryArray.push(geometry.id);
  51440. };
  51441. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  51442. var submeshes = [];
  51443. if (mesh.subMeshes) {
  51444. submeshes = mesh.subMeshes.map(function (sm, idx) {
  51445. var boundingInfo = sm.getBoundingInfo();
  51446. return {
  51447. position: idx,
  51448. verticesStart: sm.verticesStart,
  51449. verticesCount: sm.verticesCount,
  51450. indexStart: sm.indexStart,
  51451. indexCount: sm.indexCount,
  51452. hasMaterial: !!sm.getMaterial(),
  51453. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51454. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51455. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51456. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  51457. };
  51458. });
  51459. }
  51460. var geometryId = null;
  51461. if (mesh instanceof BABYLON.Mesh) {
  51462. var geometry = mesh.geometry;
  51463. geometryId = geometry ? geometry.id : null;
  51464. }
  51465. else if (mesh instanceof BABYLON.InstancedMesh) {
  51466. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  51467. geometryId = geometry ? geometry.id : null;
  51468. }
  51469. var boundingInfo = mesh.getBoundingInfo();
  51470. return {
  51471. uniqueId: mesh.uniqueId,
  51472. id: mesh.id,
  51473. name: mesh.name,
  51474. geometryId: geometryId,
  51475. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51476. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51477. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51478. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  51479. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  51480. subMeshes: submeshes,
  51481. checkCollisions: mesh.checkCollisions
  51482. };
  51483. };
  51484. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  51485. return {
  51486. id: geometry.id,
  51487. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  51488. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  51489. indices: new Uint32Array(geometry.getIndices() || []),
  51490. };
  51491. };
  51492. return CollisionCoordinatorWorker;
  51493. }());
  51494. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  51495. var CollisionCoordinatorLegacy = /** @class */ (function () {
  51496. function CollisionCoordinatorLegacy() {
  51497. this._scaledPosition = BABYLON.Vector3.Zero();
  51498. this._scaledVelocity = BABYLON.Vector3.Zero();
  51499. this._finalPosition = BABYLON.Vector3.Zero();
  51500. }
  51501. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51502. position.divideToRef(collider._radius, this._scaledPosition);
  51503. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51504. collider.collidedMesh = null;
  51505. collider._retry = 0;
  51506. collider._initialVelocity = this._scaledVelocity;
  51507. collider._initialPosition = this._scaledPosition;
  51508. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  51509. this._finalPosition.multiplyInPlace(collider._radius);
  51510. //run the callback
  51511. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  51512. };
  51513. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  51514. this._scene = scene;
  51515. };
  51516. CollisionCoordinatorLegacy.prototype.destroy = function () {
  51517. //Legacy need no destruction method.
  51518. };
  51519. //No update in legacy mode
  51520. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  51521. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  51522. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  51523. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  51524. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  51525. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  51526. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  51527. if (excludedMesh === void 0) { excludedMesh = null; }
  51528. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  51529. if (collider._retry >= maximumRetry) {
  51530. finalPosition.copyFrom(position);
  51531. return;
  51532. }
  51533. // Check if this is a mesh else camera or -1
  51534. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  51535. collider._initialize(position, velocity, closeDistance);
  51536. // Check all meshes
  51537. for (var index = 0; index < this._scene.meshes.length; index++) {
  51538. var mesh = this._scene.meshes[index];
  51539. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  51540. mesh._checkCollision(collider);
  51541. }
  51542. }
  51543. if (!collider.collisionFound) {
  51544. position.addToRef(velocity, finalPosition);
  51545. return;
  51546. }
  51547. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  51548. collider._getResponse(position, velocity);
  51549. }
  51550. if (velocity.length() <= closeDistance) {
  51551. finalPosition.copyFrom(position);
  51552. return;
  51553. }
  51554. collider._retry++;
  51555. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  51556. };
  51557. return CollisionCoordinatorLegacy;
  51558. }());
  51559. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  51560. })(BABYLON || (BABYLON = {}));
  51561. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  51562. "use strict";
  51563. var BABYLON;
  51564. (function (BABYLON) {
  51565. /**
  51566. * A particle represents one of the element emitted by a particle system.
  51567. * This is mainly define by its coordinates, direction, velocity and age.
  51568. */
  51569. var Particle = /** @class */ (function () {
  51570. /**
  51571. * Creates a new instance of @see Particle
  51572. * @param particleSystem the particle system the particle belongs to
  51573. */
  51574. function Particle(
  51575. /**
  51576. * particleSystem the particle system the particle belongs to.
  51577. */
  51578. particleSystem) {
  51579. this.particleSystem = particleSystem;
  51580. /**
  51581. * The world position of the particle in the scene.
  51582. */
  51583. this.position = BABYLON.Vector3.Zero();
  51584. /**
  51585. * The world direction of the particle in the scene.
  51586. */
  51587. this.direction = BABYLON.Vector3.Zero();
  51588. /**
  51589. * The color of the particle.
  51590. */
  51591. this.color = new BABYLON.Color4(0, 0, 0, 0);
  51592. /**
  51593. * The color change of the particle per step.
  51594. */
  51595. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  51596. /**
  51597. * Defines how long will the life of the particle be.
  51598. */
  51599. this.lifeTime = 1.0;
  51600. /**
  51601. * The current age of the particle.
  51602. */
  51603. this.age = 0;
  51604. /**
  51605. * The current size of the particle.
  51606. */
  51607. this.size = 0;
  51608. /**
  51609. * The current angle of the particle.
  51610. */
  51611. this.angle = 0;
  51612. /**
  51613. * Defines how fast is the angle changing.
  51614. */
  51615. this.angularSpeed = 0;
  51616. /**
  51617. * Defines the cell index used by the particle to be rendered from a sprite.
  51618. */
  51619. this.cellIndex = 0;
  51620. this._currentFrameCounter = 0;
  51621. if (!this.particleSystem.isAnimationSheetEnabled) {
  51622. return;
  51623. }
  51624. this.updateCellInfoFromSystem();
  51625. }
  51626. Particle.prototype.updateCellInfoFromSystem = function () {
  51627. this.cellIndex = this.particleSystem.startSpriteCellID;
  51628. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  51629. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  51630. }
  51631. else {
  51632. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  51633. }
  51634. };
  51635. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  51636. // (ageOffset / scaledUpdateSpeed) / available cells
  51637. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  51638. this._currentFrameCounter += scaledUpdateSpeed;
  51639. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  51640. this._currentFrameCounter = 0;
  51641. this.cellIndex++;
  51642. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51643. this.cellIndex = this.particleSystem.endSpriteCellID;
  51644. }
  51645. }
  51646. };
  51647. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  51648. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  51649. this.cellIndex++;
  51650. this._currentFrameCounter = 0;
  51651. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51652. if (this.particleSystem.spriteCellLoop) {
  51653. this.cellIndex = this.particleSystem.startSpriteCellID;
  51654. }
  51655. else {
  51656. this.cellIndex = this.particleSystem.endSpriteCellID;
  51657. }
  51658. }
  51659. }
  51660. else {
  51661. this._currentFrameCounter++;
  51662. }
  51663. };
  51664. /**
  51665. * Copy the properties of particle to another one.
  51666. * @param other the particle to copy the information to.
  51667. */
  51668. Particle.prototype.copyTo = function (other) {
  51669. other.position.copyFrom(this.position);
  51670. other.direction.copyFrom(this.direction);
  51671. other.color.copyFrom(this.color);
  51672. other.colorStep.copyFrom(this.colorStep);
  51673. other.lifeTime = this.lifeTime;
  51674. other.age = this.age;
  51675. other.size = this.size;
  51676. other.angle = this.angle;
  51677. other.angularSpeed = this.angularSpeed;
  51678. other.particleSystem = this.particleSystem;
  51679. other.cellIndex = this.cellIndex;
  51680. };
  51681. return Particle;
  51682. }());
  51683. BABYLON.Particle = Particle;
  51684. })(BABYLON || (BABYLON = {}));
  51685. //# sourceMappingURL=babylon.particle.js.map
  51686. "use strict";
  51687. var BABYLON;
  51688. (function (BABYLON) {
  51689. /**
  51690. * This represents a particle system in Babylon.
  51691. * 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.
  51692. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  51693. * @example https://doc.babylonjs.com/babylon101/particles
  51694. */
  51695. var ParticleSystem = /** @class */ (function () {
  51696. /**
  51697. * Instantiates a particle system.
  51698. * 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.
  51699. * @param name The name of the particle system
  51700. * @param capacity The max number of particles alive at the same time
  51701. * @param scene The scene the particle system belongs to
  51702. * @param customEffect a custom effect used to change the way particles are rendered by default
  51703. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  51704. * @param epsilon Offset used to render the particles
  51705. */
  51706. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  51707. if (customEffect === void 0) { customEffect = null; }
  51708. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  51709. if (epsilon === void 0) { epsilon = 0.01; }
  51710. var _this = this;
  51711. /**
  51712. * List of animations used by the particle system.
  51713. */
  51714. this.animations = [];
  51715. /**
  51716. * The rendering group used by the Particle system to chose when to render.
  51717. */
  51718. this.renderingGroupId = 0;
  51719. /**
  51720. * The emitter represents the Mesh or position we are attaching the particle system to.
  51721. */
  51722. this.emitter = null;
  51723. /**
  51724. * The maximum number of particles to emit per frame
  51725. */
  51726. this.emitRate = 10;
  51727. /**
  51728. * If you want to launch only a few particles at once, that can be done, as well.
  51729. */
  51730. this.manualEmitCount = -1;
  51731. /**
  51732. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51733. */
  51734. this.updateSpeed = 0.01;
  51735. /**
  51736. * The amount of time the particle system is running (depends of the overall update speed).
  51737. */
  51738. this.targetStopDuration = 0;
  51739. /**
  51740. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  51741. */
  51742. this.disposeOnStop = false;
  51743. /**
  51744. * Minimum power of emitting particles.
  51745. */
  51746. this.minEmitPower = 1;
  51747. /**
  51748. * Maximum power of emitting particles.
  51749. */
  51750. this.maxEmitPower = 1;
  51751. /**
  51752. * Minimum life time of emitting particles.
  51753. */
  51754. this.minLifeTime = 1;
  51755. /**
  51756. * Maximum life time of emitting particles.
  51757. */
  51758. this.maxLifeTime = 1;
  51759. /**
  51760. * Minimum Size of emitting particles.
  51761. */
  51762. this.minSize = 1;
  51763. /**
  51764. * Maximum Size of emitting particles.
  51765. */
  51766. this.maxSize = 1;
  51767. /**
  51768. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  51769. */
  51770. this.minAngularSpeed = 0;
  51771. /**
  51772. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  51773. */
  51774. this.maxAngularSpeed = 0;
  51775. /**
  51776. * The layer mask we are rendering the particles through.
  51777. */
  51778. this.layerMask = 0x0FFFFFFF;
  51779. /**
  51780. * This can help using your own shader to render the particle system.
  51781. * The according effect will be created
  51782. */
  51783. this.customShader = null;
  51784. /**
  51785. * By default particle system starts as soon as they are created. This prevents the
  51786. * automatic start to happen and let you decide when to start emitting particles.
  51787. */
  51788. this.preventAutoStart = false;
  51789. /**
  51790. * Callback triggered when the particle animation is ending.
  51791. */
  51792. this.onAnimationEnd = null;
  51793. /**
  51794. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51795. */
  51796. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  51797. /**
  51798. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  51799. * to override the particles.
  51800. */
  51801. this.forceDepthWrite = false;
  51802. /**
  51803. * You can use gravity if you want to give an orientation to your particles.
  51804. */
  51805. this.gravity = BABYLON.Vector3.Zero();
  51806. /**
  51807. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51808. */
  51809. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51810. /**
  51811. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51812. */
  51813. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51814. /**
  51815. * Color the particle will have at the end of its lifetime.
  51816. */
  51817. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51818. /**
  51819. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51820. */
  51821. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51822. /**
  51823. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51824. */
  51825. this.spriteCellLoop = true;
  51826. /**
  51827. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51828. */
  51829. this.spriteCellChangeSpeed = 0;
  51830. /**
  51831. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51832. */
  51833. this.startSpriteCellID = 0;
  51834. /**
  51835. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51836. */
  51837. this.endSpriteCellID = 0;
  51838. /**
  51839. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51840. */
  51841. this.spriteCellWidth = 0;
  51842. /**
  51843. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51844. */
  51845. this.spriteCellHeight = 0;
  51846. /**
  51847. * An event triggered when the system is disposed.
  51848. */
  51849. this.onDisposeObservable = new BABYLON.Observable();
  51850. this._particles = new Array();
  51851. this._stockParticles = new Array();
  51852. this._newPartsExcess = 0;
  51853. this._vertexBuffers = {};
  51854. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51855. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51856. this._scaledDirection = BABYLON.Vector3.Zero();
  51857. this._scaledGravity = BABYLON.Vector3.Zero();
  51858. this._currentRenderId = -1;
  51859. this._started = false;
  51860. this._stopped = false;
  51861. this._actualFrame = 0;
  51862. this._vertexBufferSize = 11;
  51863. // start of sub system methods
  51864. /**
  51865. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51866. * Its lifetime will start back at 0.
  51867. */
  51868. this.recycleParticle = function (particle) {
  51869. var lastParticle = _this._particles.pop();
  51870. if (lastParticle !== particle) {
  51871. lastParticle.copyTo(particle);
  51872. }
  51873. _this._stockParticles.push(lastParticle);
  51874. };
  51875. this._createParticle = function () {
  51876. var particle;
  51877. if (_this._stockParticles.length !== 0) {
  51878. particle = _this._stockParticles.pop();
  51879. particle.age = 0;
  51880. particle.cellIndex = _this.startSpriteCellID;
  51881. }
  51882. else {
  51883. particle = new BABYLON.Particle(_this);
  51884. }
  51885. return particle;
  51886. };
  51887. this._emitFromParticle = function (particle) {
  51888. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51889. return;
  51890. }
  51891. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51892. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51893. subSystem._rootParticleSystem = _this;
  51894. _this.activeSubSystems.push(subSystem);
  51895. subSystem.start();
  51896. };
  51897. this._appendParticleVertexes = null;
  51898. this.id = name;
  51899. this.name = name;
  51900. this._capacity = capacity;
  51901. this._epsilon = epsilon;
  51902. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51903. if (isAnimationSheetEnabled) {
  51904. this._vertexBufferSize = 12;
  51905. }
  51906. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51907. this._customEffect = customEffect;
  51908. scene.particleSystems.push(this);
  51909. this._createIndexBuffer();
  51910. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51911. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51912. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51913. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51914. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51915. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51916. if (this._isAnimationSheetEnabled) {
  51917. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51918. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51919. }
  51920. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51921. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51922. this._vertexBuffers["options"] = options;
  51923. // Default emitter type
  51924. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51925. this.updateFunction = function (particles) {
  51926. for (var index = 0; index < particles.length; index++) {
  51927. var particle = particles[index];
  51928. particle.age += _this._scaledUpdateSpeed;
  51929. if (particle.age >= particle.lifeTime) {
  51930. _this._emitFromParticle(particle);
  51931. _this.recycleParticle(particle);
  51932. index--;
  51933. continue;
  51934. }
  51935. else {
  51936. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51937. particle.color.addInPlace(_this._scaledColorStep);
  51938. if (particle.color.a < 0)
  51939. particle.color.a = 0;
  51940. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51941. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51942. particle.position.addInPlace(_this._scaledDirection);
  51943. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51944. particle.direction.addInPlace(_this._scaledGravity);
  51945. if (_this._isAnimationSheetEnabled) {
  51946. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51947. }
  51948. }
  51949. }
  51950. };
  51951. }
  51952. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51953. /**
  51954. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51955. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51956. */
  51957. get: function () {
  51958. if (this.particleEmitterType.direction1) {
  51959. return this.particleEmitterType.direction1;
  51960. }
  51961. return BABYLON.Vector3.Zero();
  51962. },
  51963. set: function (value) {
  51964. if (this.particleEmitterType.direction1) {
  51965. this.particleEmitterType.direction1 = value;
  51966. }
  51967. },
  51968. enumerable: true,
  51969. configurable: true
  51970. });
  51971. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51972. /**
  51973. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51974. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51975. */
  51976. get: function () {
  51977. if (this.particleEmitterType.direction2) {
  51978. return this.particleEmitterType.direction2;
  51979. }
  51980. return BABYLON.Vector3.Zero();
  51981. },
  51982. set: function (value) {
  51983. if (this.particleEmitterType.direction2) {
  51984. this.particleEmitterType.direction2 = value;
  51985. }
  51986. },
  51987. enumerable: true,
  51988. configurable: true
  51989. });
  51990. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51991. /**
  51992. * 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.
  51993. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51994. */
  51995. get: function () {
  51996. if (this.particleEmitterType.minEmitBox) {
  51997. return this.particleEmitterType.minEmitBox;
  51998. }
  51999. return BABYLON.Vector3.Zero();
  52000. },
  52001. set: function (value) {
  52002. if (this.particleEmitterType.minEmitBox) {
  52003. this.particleEmitterType.minEmitBox = value;
  52004. }
  52005. },
  52006. enumerable: true,
  52007. configurable: true
  52008. });
  52009. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  52010. /**
  52011. * 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.
  52012. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52013. */
  52014. get: function () {
  52015. if (this.particleEmitterType.maxEmitBox) {
  52016. return this.particleEmitterType.maxEmitBox;
  52017. }
  52018. return BABYLON.Vector3.Zero();
  52019. },
  52020. set: function (value) {
  52021. if (this.particleEmitterType.maxEmitBox) {
  52022. this.particleEmitterType.maxEmitBox = value;
  52023. }
  52024. },
  52025. enumerable: true,
  52026. configurable: true
  52027. });
  52028. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  52029. /**
  52030. * Sets a callback that will be triggered when the system is disposed.
  52031. */
  52032. set: function (callback) {
  52033. if (this._onDisposeObserver) {
  52034. this.onDisposeObservable.remove(this._onDisposeObserver);
  52035. }
  52036. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  52037. },
  52038. enumerable: true,
  52039. configurable: true
  52040. });
  52041. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  52042. /**
  52043. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  52044. */
  52045. get: function () {
  52046. return this._isAnimationSheetEnabled;
  52047. },
  52048. enumerable: true,
  52049. configurable: true
  52050. });
  52051. Object.defineProperty(ParticleSystem.prototype, "particles", {
  52052. //end of Sub-emitter
  52053. /**
  52054. * Gets the current list of active particles
  52055. */
  52056. get: function () {
  52057. return this._particles;
  52058. },
  52059. enumerable: true,
  52060. configurable: true
  52061. });
  52062. /**
  52063. * Returns the string "ParticleSystem"
  52064. * @returns a string containing the class name
  52065. */
  52066. ParticleSystem.prototype.getClassName = function () {
  52067. return "ParticleSystem";
  52068. };
  52069. ParticleSystem.prototype._createIndexBuffer = function () {
  52070. var indices = [];
  52071. var index = 0;
  52072. for (var count = 0; count < this._capacity; count++) {
  52073. indices.push(index);
  52074. indices.push(index + 1);
  52075. indices.push(index + 2);
  52076. indices.push(index);
  52077. indices.push(index + 2);
  52078. indices.push(index + 3);
  52079. index += 4;
  52080. }
  52081. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  52082. };
  52083. /**
  52084. * Gets the maximum number of particles active at the same time.
  52085. * @returns The max number of active particles.
  52086. */
  52087. ParticleSystem.prototype.getCapacity = function () {
  52088. return this._capacity;
  52089. };
  52090. /**
  52091. * Gets Wether there are still active particles in the system.
  52092. * @returns True if it is alive, otherwise false.
  52093. */
  52094. ParticleSystem.prototype.isAlive = function () {
  52095. return this._alive;
  52096. };
  52097. /**
  52098. * Gets Wether the system has been started.
  52099. * @returns True if it has been started, otherwise false.
  52100. */
  52101. ParticleSystem.prototype.isStarted = function () {
  52102. return this._started;
  52103. };
  52104. /**
  52105. * Starts the particle system and begins to emit.
  52106. */
  52107. ParticleSystem.prototype.start = function () {
  52108. this._started = true;
  52109. this._stopped = false;
  52110. this._actualFrame = 0;
  52111. if (this.subEmitters && this.subEmitters.length != 0) {
  52112. this.activeSubSystems = new Array();
  52113. }
  52114. };
  52115. /**
  52116. * Stops the particle system.
  52117. * @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.
  52118. */
  52119. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  52120. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  52121. this._stopped = true;
  52122. if (stopSubEmitters) {
  52123. this._stopSubEmitters();
  52124. }
  52125. };
  52126. // animation sheet
  52127. /**
  52128. * Remove all active particles
  52129. */
  52130. ParticleSystem.prototype.reset = function () {
  52131. this._stockParticles = [];
  52132. this._particles = [];
  52133. };
  52134. /**
  52135. * @ignore (for internal use only)
  52136. */
  52137. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  52138. var offset = index * this._vertexBufferSize;
  52139. this._vertexData[offset] = particle.position.x;
  52140. this._vertexData[offset + 1] = particle.position.y;
  52141. this._vertexData[offset + 2] = particle.position.z;
  52142. this._vertexData[offset + 3] = particle.color.r;
  52143. this._vertexData[offset + 4] = particle.color.g;
  52144. this._vertexData[offset + 5] = particle.color.b;
  52145. this._vertexData[offset + 6] = particle.color.a;
  52146. this._vertexData[offset + 7] = particle.angle;
  52147. this._vertexData[offset + 8] = particle.size;
  52148. this._vertexData[offset + 9] = offsetX;
  52149. this._vertexData[offset + 10] = offsetY;
  52150. };
  52151. /**
  52152. * @ignore (for internal use only)
  52153. */
  52154. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  52155. if (offsetX === 0)
  52156. offsetX = this._epsilon;
  52157. else if (offsetX === 1)
  52158. offsetX = 1 - this._epsilon;
  52159. if (offsetY === 0)
  52160. offsetY = this._epsilon;
  52161. else if (offsetY === 1)
  52162. offsetY = 1 - this._epsilon;
  52163. var offset = index * this._vertexBufferSize;
  52164. this._vertexData[offset] = particle.position.x;
  52165. this._vertexData[offset + 1] = particle.position.y;
  52166. this._vertexData[offset + 2] = particle.position.z;
  52167. this._vertexData[offset + 3] = particle.color.r;
  52168. this._vertexData[offset + 4] = particle.color.g;
  52169. this._vertexData[offset + 5] = particle.color.b;
  52170. this._vertexData[offset + 6] = particle.color.a;
  52171. this._vertexData[offset + 7] = particle.angle;
  52172. this._vertexData[offset + 8] = particle.size;
  52173. this._vertexData[offset + 9] = offsetX;
  52174. this._vertexData[offset + 10] = offsetY;
  52175. this._vertexData[offset + 11] = particle.cellIndex;
  52176. };
  52177. ParticleSystem.prototype._stopSubEmitters = function () {
  52178. if (!this.activeSubSystems) {
  52179. return;
  52180. }
  52181. this.activeSubSystems.forEach(function (subSystem) {
  52182. subSystem.stop(true);
  52183. });
  52184. this.activeSubSystems = new Array();
  52185. };
  52186. ParticleSystem.prototype._removeFromRoot = function () {
  52187. if (!this._rootParticleSystem) {
  52188. return;
  52189. }
  52190. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  52191. if (index !== -1) {
  52192. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  52193. }
  52194. };
  52195. // end of sub system methods
  52196. ParticleSystem.prototype._update = function (newParticles) {
  52197. // Update current
  52198. this._alive = this._particles.length > 0;
  52199. this.updateFunction(this._particles);
  52200. // Add new ones
  52201. var worldMatrix;
  52202. if (this.emitter.position) {
  52203. var emitterMesh = this.emitter;
  52204. worldMatrix = emitterMesh.getWorldMatrix();
  52205. }
  52206. else {
  52207. var emitterPosition = this.emitter;
  52208. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52209. }
  52210. var particle;
  52211. for (var index = 0; index < newParticles; index++) {
  52212. if (this._particles.length === this._capacity) {
  52213. break;
  52214. }
  52215. particle = this._createParticle();
  52216. this._particles.push(particle);
  52217. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  52218. if (this.startPositionFunction) {
  52219. this.startPositionFunction(worldMatrix, particle.position, particle);
  52220. }
  52221. else {
  52222. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  52223. }
  52224. if (this.startDirectionFunction) {
  52225. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52226. }
  52227. else {
  52228. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52229. }
  52230. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  52231. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  52232. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  52233. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  52234. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  52235. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  52236. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  52237. }
  52238. };
  52239. ParticleSystem.prototype._getEffect = function () {
  52240. if (this._customEffect) {
  52241. return this._customEffect;
  52242. }
  52243. ;
  52244. var defines = [];
  52245. if (this._scene.clipPlane) {
  52246. defines.push("#define CLIPPLANE");
  52247. }
  52248. if (this._isAnimationSheetEnabled) {
  52249. defines.push("#define ANIMATESHEET");
  52250. }
  52251. // Effect
  52252. var join = defines.join("\n");
  52253. if (this._cachedDefines !== join) {
  52254. this._cachedDefines = join;
  52255. var attributesNamesOrOptions;
  52256. var effectCreationOption;
  52257. if (this._isAnimationSheetEnabled) {
  52258. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  52259. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  52260. }
  52261. else {
  52262. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  52263. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  52264. }
  52265. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  52266. }
  52267. return this._effect;
  52268. };
  52269. /**
  52270. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52271. */
  52272. ParticleSystem.prototype.animate = function () {
  52273. if (!this._started)
  52274. return;
  52275. var effect = this._getEffect();
  52276. // Check
  52277. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  52278. return;
  52279. if (this._currentRenderId === this._scene.getRenderId()) {
  52280. return;
  52281. }
  52282. this._currentRenderId = this._scene.getRenderId();
  52283. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  52284. // determine the number of particles we need to create
  52285. var newParticles;
  52286. if (this.manualEmitCount > -1) {
  52287. newParticles = this.manualEmitCount;
  52288. this._newPartsExcess = 0;
  52289. this.manualEmitCount = 0;
  52290. }
  52291. else {
  52292. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  52293. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  52294. }
  52295. if (this._newPartsExcess > 1.0) {
  52296. newParticles += this._newPartsExcess >> 0;
  52297. this._newPartsExcess -= this._newPartsExcess >> 0;
  52298. }
  52299. this._alive = false;
  52300. if (!this._stopped) {
  52301. this._actualFrame += this._scaledUpdateSpeed;
  52302. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52303. this.stop();
  52304. }
  52305. else {
  52306. newParticles = 0;
  52307. }
  52308. this._update(newParticles);
  52309. // Stopped?
  52310. if (this._stopped) {
  52311. if (!this._alive) {
  52312. this._started = false;
  52313. if (this.onAnimationEnd) {
  52314. this.onAnimationEnd();
  52315. }
  52316. if (this.disposeOnStop) {
  52317. this._scene._toBeDisposed.push(this);
  52318. }
  52319. }
  52320. }
  52321. // Animation sheet
  52322. if (this._isAnimationSheetEnabled) {
  52323. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  52324. }
  52325. else {
  52326. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  52327. }
  52328. // Update VBO
  52329. var offset = 0;
  52330. for (var index = 0; index < this._particles.length; index++) {
  52331. var particle = this._particles[index];
  52332. this._appendParticleVertexes(offset, particle);
  52333. offset += 4;
  52334. }
  52335. if (this._vertexBuffer) {
  52336. this._vertexBuffer.update(this._vertexData);
  52337. }
  52338. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  52339. this.stop();
  52340. }
  52341. };
  52342. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  52343. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  52344. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  52345. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  52346. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  52347. };
  52348. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  52349. this._appendParticleVertex(offset++, particle, 0, 0);
  52350. this._appendParticleVertex(offset++, particle, 1, 0);
  52351. this._appendParticleVertex(offset++, particle, 1, 1);
  52352. this._appendParticleVertex(offset++, particle, 0, 1);
  52353. };
  52354. /**
  52355. * Rebuilds the particle system.
  52356. */
  52357. ParticleSystem.prototype.rebuild = function () {
  52358. this._createIndexBuffer();
  52359. if (this._vertexBuffer) {
  52360. this._vertexBuffer._rebuild();
  52361. }
  52362. };
  52363. /**
  52364. * Is this system ready to be used/rendered
  52365. * @return true if the system is ready
  52366. */
  52367. ParticleSystem.prototype.isReady = function () {
  52368. var effect = this._getEffect();
  52369. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52370. return false;
  52371. }
  52372. return true;
  52373. };
  52374. /**
  52375. * Renders the particle system in its current state.
  52376. * @returns the current number of particles
  52377. */
  52378. ParticleSystem.prototype.render = function () {
  52379. var effect = this._getEffect();
  52380. // Check
  52381. if (!this.isReady() || !this._particles.length) {
  52382. return 0;
  52383. }
  52384. var engine = this._scene.getEngine();
  52385. // Render
  52386. engine.enableEffect(effect);
  52387. engine.setState(false);
  52388. var viewMatrix = this._scene.getViewMatrix();
  52389. effect.setTexture("diffuseSampler", this.particleTexture);
  52390. effect.setMatrix("view", viewMatrix);
  52391. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52392. if (this._isAnimationSheetEnabled && this.particleTexture) {
  52393. var baseSize = this.particleTexture.getBaseSize();
  52394. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  52395. }
  52396. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  52397. if (this._scene.clipPlane) {
  52398. var clipPlane = this._scene.clipPlane;
  52399. var invView = viewMatrix.clone();
  52400. invView.invert();
  52401. effect.setMatrix("invView", invView);
  52402. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52403. }
  52404. // VBOs
  52405. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52406. // Draw order
  52407. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  52408. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52409. }
  52410. else {
  52411. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52412. }
  52413. if (this.forceDepthWrite) {
  52414. engine.setDepthWrite(true);
  52415. }
  52416. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  52417. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52418. return this._particles.length;
  52419. };
  52420. /**
  52421. * Disposes the particle system and free the associated resources
  52422. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52423. */
  52424. ParticleSystem.prototype.dispose = function (disposeTexture) {
  52425. if (disposeTexture === void 0) { disposeTexture = true; }
  52426. if (this._vertexBuffer) {
  52427. this._vertexBuffer.dispose();
  52428. this._vertexBuffer = null;
  52429. }
  52430. if (this._indexBuffer) {
  52431. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52432. this._indexBuffer = null;
  52433. }
  52434. if (disposeTexture && this.particleTexture) {
  52435. this.particleTexture.dispose();
  52436. this.particleTexture = null;
  52437. }
  52438. this._removeFromRoot();
  52439. // Remove from scene
  52440. var index = this._scene.particleSystems.indexOf(this);
  52441. if (index > -1) {
  52442. this._scene.particleSystems.splice(index, 1);
  52443. }
  52444. // Callback
  52445. this.onDisposeObservable.notifyObservers(this);
  52446. this.onDisposeObservable.clear();
  52447. };
  52448. /**
  52449. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  52450. * @param radius The radius of the sphere to emit from
  52451. * @returns the emitter
  52452. */
  52453. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  52454. if (radius === void 0) { radius = 1; }
  52455. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  52456. this.particleEmitterType = particleEmitter;
  52457. return particleEmitter;
  52458. };
  52459. /**
  52460. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  52461. * @param radius The radius of the sphere to emit from
  52462. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  52463. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  52464. * @returns the emitter
  52465. */
  52466. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  52467. if (radius === void 0) { radius = 1; }
  52468. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  52469. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  52470. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  52471. this.particleEmitterType = particleEmitter;
  52472. return particleEmitter;
  52473. };
  52474. /**
  52475. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  52476. * @param radius The radius of the cone to emit from
  52477. * @param angle The base angle of the cone
  52478. * @returns the emitter
  52479. */
  52480. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  52481. if (radius === void 0) { radius = 1; }
  52482. if (angle === void 0) { angle = Math.PI / 4; }
  52483. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  52484. this.particleEmitterType = particleEmitter;
  52485. return particleEmitter;
  52486. };
  52487. // 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.
  52488. /**
  52489. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  52490. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  52491. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  52492. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52493. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52494. * @returns the emitter
  52495. */
  52496. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  52497. var particleEmitter = new BABYLON.BoxParticleEmitter();
  52498. this.particleEmitterType = particleEmitter;
  52499. this.direction1 = direction1;
  52500. this.direction2 = direction2;
  52501. this.minEmitBox = minEmitBox;
  52502. this.maxEmitBox = maxEmitBox;
  52503. return particleEmitter;
  52504. };
  52505. // Clone
  52506. /**
  52507. * Clones the particle system.
  52508. * @param name The name of the cloned object
  52509. * @param newEmitter The new emitter to use
  52510. * @returns the cloned particle system
  52511. */
  52512. ParticleSystem.prototype.clone = function (name, newEmitter) {
  52513. var custom = null;
  52514. var program = null;
  52515. if (this.customShader != null) {
  52516. program = this.customShader;
  52517. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52518. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52519. }
  52520. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  52521. result.customShader = program;
  52522. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  52523. if (newEmitter === undefined) {
  52524. newEmitter = this.emitter;
  52525. }
  52526. result.emitter = newEmitter;
  52527. if (this.particleTexture) {
  52528. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52529. }
  52530. if (!this.preventAutoStart) {
  52531. result.start();
  52532. }
  52533. return result;
  52534. };
  52535. /**
  52536. * Serializes the particle system to a JSON object.
  52537. * @returns the JSON object
  52538. */
  52539. ParticleSystem.prototype.serialize = function () {
  52540. var serializationObject = {};
  52541. serializationObject.name = this.name;
  52542. serializationObject.id = this.id;
  52543. // Emitter
  52544. if (this.emitter.position) {
  52545. var emitterMesh = this.emitter;
  52546. serializationObject.emitterId = emitterMesh.id;
  52547. }
  52548. else {
  52549. var emitterPosition = this.emitter;
  52550. serializationObject.emitter = emitterPosition.asArray();
  52551. }
  52552. serializationObject.capacity = this.getCapacity();
  52553. if (this.particleTexture) {
  52554. serializationObject.textureName = this.particleTexture.name;
  52555. }
  52556. // Animations
  52557. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52558. // Particle system
  52559. serializationObject.minAngularSpeed = this.minAngularSpeed;
  52560. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  52561. serializationObject.minSize = this.minSize;
  52562. serializationObject.maxSize = this.maxSize;
  52563. serializationObject.minEmitPower = this.minEmitPower;
  52564. serializationObject.maxEmitPower = this.maxEmitPower;
  52565. serializationObject.minLifeTime = this.minLifeTime;
  52566. serializationObject.maxLifeTime = this.maxLifeTime;
  52567. serializationObject.emitRate = this.emitRate;
  52568. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52569. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52570. serializationObject.gravity = this.gravity.asArray();
  52571. serializationObject.direction1 = this.direction1.asArray();
  52572. serializationObject.direction2 = this.direction2.asArray();
  52573. serializationObject.color1 = this.color1.asArray();
  52574. serializationObject.color2 = this.color2.asArray();
  52575. serializationObject.colorDead = this.colorDead.asArray();
  52576. serializationObject.updateSpeed = this.updateSpeed;
  52577. serializationObject.targetStopDuration = this.targetStopDuration;
  52578. serializationObject.textureMask = this.textureMask.asArray();
  52579. serializationObject.blendMode = this.blendMode;
  52580. serializationObject.customShader = this.customShader;
  52581. serializationObject.preventAutoStart = this.preventAutoStart;
  52582. serializationObject.startSpriteCellID = this.startSpriteCellID;
  52583. serializationObject.endSpriteCellID = this.endSpriteCellID;
  52584. serializationObject.spriteCellLoop = this.spriteCellLoop;
  52585. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  52586. serializationObject.spriteCellWidth = this.spriteCellWidth;
  52587. serializationObject.spriteCellHeight = this.spriteCellHeight;
  52588. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  52589. // Emitter
  52590. if (this.particleEmitterType) {
  52591. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52592. }
  52593. return serializationObject;
  52594. };
  52595. /**
  52596. * Parses a JSON object to create a particle system.
  52597. * @param parsedParticleSystem The JSON object to parse
  52598. * @param scene The scene to create the particle system in
  52599. * @param rootUrl The root url to use to load external dependencies like texture
  52600. * @returns the Parsed particle system
  52601. */
  52602. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52603. var name = parsedParticleSystem.name;
  52604. var custom = null;
  52605. var program = null;
  52606. if (parsedParticleSystem.customShader) {
  52607. program = parsedParticleSystem.customShader;
  52608. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52609. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52610. }
  52611. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  52612. particleSystem.customShader = program;
  52613. if (parsedParticleSystem.id) {
  52614. particleSystem.id = parsedParticleSystem.id;
  52615. }
  52616. // Auto start
  52617. if (parsedParticleSystem.preventAutoStart) {
  52618. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  52619. }
  52620. // Texture
  52621. if (parsedParticleSystem.textureName) {
  52622. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52623. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52624. }
  52625. // Emitter
  52626. if (parsedParticleSystem.emitterId) {
  52627. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52628. }
  52629. else {
  52630. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52631. }
  52632. // Animations
  52633. if (parsedParticleSystem.animations) {
  52634. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52635. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52636. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52637. }
  52638. }
  52639. if (parsedParticleSystem.autoAnimate) {
  52640. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  52641. }
  52642. // Particle system
  52643. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  52644. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  52645. particleSystem.minSize = parsedParticleSystem.minSize;
  52646. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52647. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52648. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52649. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52650. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52651. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52652. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  52653. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  52654. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52655. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  52656. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  52657. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52658. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52659. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52660. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52661. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52662. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  52663. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52664. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  52665. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  52666. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  52667. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  52668. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  52669. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  52670. if (!particleSystem.preventAutoStart) {
  52671. particleSystem.start();
  52672. }
  52673. return particleSystem;
  52674. };
  52675. /**
  52676. * Source color is added to the destination color without alpha affecting the result.
  52677. */
  52678. ParticleSystem.BLENDMODE_ONEONE = 0;
  52679. /**
  52680. * Blend current color and particle color using particle’s alpha.
  52681. */
  52682. ParticleSystem.BLENDMODE_STANDARD = 1;
  52683. return ParticleSystem;
  52684. }());
  52685. BABYLON.ParticleSystem = ParticleSystem;
  52686. })(BABYLON || (BABYLON = {}));
  52687. //# sourceMappingURL=babylon.particleSystem.js.map
  52688. "use strict";
  52689. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  52690. "use strict";
  52691. var BABYLON;
  52692. (function (BABYLON) {
  52693. /**
  52694. * Particle emitter emitting particles from the inside of a box.
  52695. * It emits the particles randomly between 2 given directions.
  52696. */
  52697. var BoxParticleEmitter = /** @class */ (function () {
  52698. /**
  52699. * Creates a new instance of @see BoxParticleEmitter
  52700. */
  52701. function BoxParticleEmitter() {
  52702. /**
  52703. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52704. */
  52705. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  52706. /**
  52707. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52708. */
  52709. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  52710. /**
  52711. * 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.
  52712. */
  52713. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  52714. /**
  52715. * 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.
  52716. */
  52717. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  52718. }
  52719. /**
  52720. * Called by the particle System when the direction is computed for the created particle.
  52721. * @param emitPower is the power of the particle (speed)
  52722. * @param worldMatrix is the world matrix of the particle system
  52723. * @param directionToUpdate is the direction vector to update with the result
  52724. * @param particle is the particle we are computed the direction for
  52725. */
  52726. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52727. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52728. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52729. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52730. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52731. };
  52732. /**
  52733. * Called by the particle System when the position is computed for the created particle.
  52734. * @param worldMatrix is the world matrix of the particle system
  52735. * @param positionToUpdate is the position vector to update with the result
  52736. * @param particle is the particle we are computed the position for
  52737. */
  52738. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52739. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  52740. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  52741. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  52742. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52743. };
  52744. /**
  52745. * Clones the current emitter and returns a copy of it
  52746. * @returns the new emitter
  52747. */
  52748. BoxParticleEmitter.prototype.clone = function () {
  52749. var newOne = new BoxParticleEmitter();
  52750. BABYLON.Tools.DeepCopy(this, newOne);
  52751. return newOne;
  52752. };
  52753. /**
  52754. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52755. * @param effect defines the update shader
  52756. */
  52757. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  52758. effect.setVector3("direction1", this.direction1);
  52759. effect.setVector3("direction2", this.direction2);
  52760. effect.setVector3("minEmitBox", this.minEmitBox);
  52761. effect.setVector3("maxEmitBox", this.maxEmitBox);
  52762. };
  52763. /**
  52764. * Returns a string to use to update the GPU particles update shader
  52765. * @returns a string containng the defines string
  52766. */
  52767. BoxParticleEmitter.prototype.getEffectDefines = function () {
  52768. return "#define BOXEMITTER";
  52769. };
  52770. /**
  52771. * Returns the string "BoxEmitter"
  52772. * @returns a string containing the class name
  52773. */
  52774. BoxParticleEmitter.prototype.getClassName = function () {
  52775. return "BoxEmitter";
  52776. };
  52777. /**
  52778. * Serializes the particle system to a JSON object.
  52779. * @returns the JSON object
  52780. */
  52781. BoxParticleEmitter.prototype.serialize = function () {
  52782. var serializationObject = {};
  52783. serializationObject.type = this.getClassName();
  52784. serializationObject.direction1 = this.direction1.asArray();
  52785. ;
  52786. serializationObject.direction2 = this.direction2.asArray();
  52787. ;
  52788. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52789. ;
  52790. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52791. ;
  52792. return serializationObject;
  52793. };
  52794. /**
  52795. * Parse properties from a JSON object
  52796. * @param serializationObject defines the JSON object
  52797. */
  52798. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  52799. this.direction1.copyFrom(serializationObject.direction1);
  52800. this.direction2.copyFrom(serializationObject.direction2);
  52801. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  52802. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  52803. };
  52804. return BoxParticleEmitter;
  52805. }());
  52806. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  52807. })(BABYLON || (BABYLON = {}));
  52808. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  52809. "use strict";
  52810. var BABYLON;
  52811. (function (BABYLON) {
  52812. /**
  52813. * Particle emitter emitting particles from the inside of a cone.
  52814. * It emits the particles alongside the cone volume from the base to the particle.
  52815. * The emission direction might be randomized.
  52816. */
  52817. var ConeParticleEmitter = /** @class */ (function () {
  52818. /**
  52819. * Creates a new instance of @see ConeParticleEmitter
  52820. * @param radius the radius of the emission cone (1 by default)
  52821. * @param angles the cone base angle (PI by default)
  52822. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52823. */
  52824. function ConeParticleEmitter(radius,
  52825. /**
  52826. * The radius of the emission cone.
  52827. */
  52828. angle,
  52829. /**
  52830. * The cone base angle.
  52831. */
  52832. directionRandomizer) {
  52833. if (radius === void 0) { radius = 1; }
  52834. if (angle === void 0) { angle = Math.PI; }
  52835. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52836. this.angle = angle;
  52837. this.directionRandomizer = directionRandomizer;
  52838. this.radius = radius;
  52839. }
  52840. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52841. /**
  52842. * Gets the radius of the emission cone.
  52843. */
  52844. get: function () {
  52845. return this._radius;
  52846. },
  52847. /**
  52848. * Sets the radius of the emission cone.
  52849. */
  52850. set: function (value) {
  52851. this._radius = value;
  52852. if (this.angle !== 0) {
  52853. this._height = value / Math.tan(this.angle / 2);
  52854. }
  52855. else {
  52856. this._height = 1;
  52857. }
  52858. },
  52859. enumerable: true,
  52860. configurable: true
  52861. });
  52862. /**
  52863. * Called by the particle System when the direction is computed for the created particle.
  52864. * @param emitPower is the power of the particle (speed)
  52865. * @param worldMatrix is the world matrix of the particle system
  52866. * @param directionToUpdate is the direction vector to update with the result
  52867. * @param particle is the particle we are computed the direction for
  52868. */
  52869. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52870. if (this.angle === 0) {
  52871. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52872. }
  52873. else {
  52874. // measure the direction Vector from the emitter to the particle.
  52875. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52876. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52877. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52878. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52879. direction.x += randX;
  52880. direction.y += randY;
  52881. direction.z += randZ;
  52882. direction.normalize();
  52883. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52884. }
  52885. };
  52886. /**
  52887. * Called by the particle System when the position is computed for the created particle.
  52888. * @param worldMatrix is the world matrix of the particle system
  52889. * @param positionToUpdate is the position vector to update with the result
  52890. * @param particle is the particle we are computed the position for
  52891. */
  52892. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52893. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52894. var h = BABYLON.Scalar.RandomRange(0, 1);
  52895. // Better distribution in a cone at normal angles.
  52896. h = 1 - h * h;
  52897. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52898. radius = radius * h;
  52899. var randX = radius * Math.sin(s);
  52900. var randZ = radius * Math.cos(s);
  52901. var randY = h * this._height;
  52902. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52903. };
  52904. /**
  52905. * Clones the current emitter and returns a copy of it
  52906. * @returns the new emitter
  52907. */
  52908. ConeParticleEmitter.prototype.clone = function () {
  52909. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52910. BABYLON.Tools.DeepCopy(this, newOne);
  52911. return newOne;
  52912. };
  52913. /**
  52914. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52915. * @param effect defines the update shader
  52916. */
  52917. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52918. effect.setFloat("radius", this.radius);
  52919. effect.setFloat("angle", this.angle);
  52920. effect.setFloat("height", this._height);
  52921. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52922. };
  52923. /**
  52924. * Returns a string to use to update the GPU particles update shader
  52925. * @returns a string containng the defines string
  52926. */
  52927. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52928. return "#define CONEEMITTER";
  52929. };
  52930. /**
  52931. * Returns the string "BoxEmitter"
  52932. * @returns a string containing the class name
  52933. */
  52934. ConeParticleEmitter.prototype.getClassName = function () {
  52935. return "ConeEmitter";
  52936. };
  52937. /**
  52938. * Serializes the particle system to a JSON object.
  52939. * @returns the JSON object
  52940. */
  52941. ConeParticleEmitter.prototype.serialize = function () {
  52942. var serializationObject = {};
  52943. serializationObject.type = this.getClassName();
  52944. serializationObject.radius = this.radius;
  52945. serializationObject.angle = this.angle;
  52946. serializationObject.directionRandomizer = this.directionRandomizer;
  52947. return serializationObject;
  52948. };
  52949. /**
  52950. * Parse properties from a JSON object
  52951. * @param serializationObject defines the JSON object
  52952. */
  52953. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52954. this.radius = serializationObject.radius;
  52955. this.angle = serializationObject.angle;
  52956. this.directionRandomizer = serializationObject.directionRandomizer;
  52957. };
  52958. return ConeParticleEmitter;
  52959. }());
  52960. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52961. })(BABYLON || (BABYLON = {}));
  52962. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52963. "use strict";
  52964. var BABYLON;
  52965. (function (BABYLON) {
  52966. /**
  52967. * Particle emitter emitting particles from the inside of a sphere.
  52968. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52969. */
  52970. var SphereParticleEmitter = /** @class */ (function () {
  52971. /**
  52972. * Creates a new instance of @see SphereParticleEmitter
  52973. * @param radius the radius of the emission sphere (1 by default)
  52974. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52975. */
  52976. function SphereParticleEmitter(
  52977. /**
  52978. * The radius of the emission sphere.
  52979. */
  52980. radius,
  52981. /**
  52982. * How much to randomize the particle direction [0-1].
  52983. */
  52984. directionRandomizer) {
  52985. if (radius === void 0) { radius = 1; }
  52986. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52987. this.radius = radius;
  52988. this.directionRandomizer = directionRandomizer;
  52989. }
  52990. /**
  52991. * Called by the particle System when the direction is computed for the created particle.
  52992. * @param emitPower is the power of the particle (speed)
  52993. * @param worldMatrix is the world matrix of the particle system
  52994. * @param directionToUpdate is the direction vector to update with the result
  52995. * @param particle is the particle we are computed the direction for
  52996. */
  52997. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52998. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52999. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53000. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53001. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53002. direction.x += randX;
  53003. direction.y += randY;
  53004. direction.z += randZ;
  53005. direction.normalize();
  53006. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  53007. };
  53008. /**
  53009. * Called by the particle System when the position is computed for the created particle.
  53010. * @param worldMatrix is the world matrix of the particle system
  53011. * @param positionToUpdate is the position vector to update with the result
  53012. * @param particle is the particle we are computed the position for
  53013. */
  53014. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  53015. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  53016. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  53017. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  53018. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  53019. var randY = randRadius * Math.cos(theta);
  53020. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  53021. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  53022. };
  53023. /**
  53024. * Clones the current emitter and returns a copy of it
  53025. * @returns the new emitter
  53026. */
  53027. SphereParticleEmitter.prototype.clone = function () {
  53028. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  53029. BABYLON.Tools.DeepCopy(this, newOne);
  53030. return newOne;
  53031. };
  53032. /**
  53033. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53034. * @param effect defines the update shader
  53035. */
  53036. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  53037. effect.setFloat("radius", this.radius);
  53038. effect.setFloat("directionRandomizer", this.directionRandomizer);
  53039. };
  53040. /**
  53041. * Returns a string to use to update the GPU particles update shader
  53042. * @returns a string containng the defines string
  53043. */
  53044. SphereParticleEmitter.prototype.getEffectDefines = function () {
  53045. return "#define SPHEREEMITTER";
  53046. };
  53047. /**
  53048. * Returns the string "SphereParticleEmitter"
  53049. * @returns a string containing the class name
  53050. */
  53051. SphereParticleEmitter.prototype.getClassName = function () {
  53052. return "SphereParticleEmitter";
  53053. };
  53054. /**
  53055. * Serializes the particle system to a JSON object.
  53056. * @returns the JSON object
  53057. */
  53058. SphereParticleEmitter.prototype.serialize = function () {
  53059. var serializationObject = {};
  53060. serializationObject.type = this.getClassName();
  53061. serializationObject.radius = this.radius;
  53062. serializationObject.directionRandomizer = this.directionRandomizer;
  53063. return serializationObject;
  53064. };
  53065. /**
  53066. * Parse properties from a JSON object
  53067. * @param serializationObject defines the JSON object
  53068. */
  53069. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  53070. this.radius = serializationObject.radius;
  53071. this.directionRandomizer = serializationObject.directionRandomizer;
  53072. };
  53073. return SphereParticleEmitter;
  53074. }());
  53075. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  53076. /**
  53077. * Particle emitter emitting particles from the inside of a sphere.
  53078. * It emits the particles randomly between two vectors.
  53079. */
  53080. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  53081. __extends(SphereDirectedParticleEmitter, _super);
  53082. /**
  53083. * Creates a new instance of @see SphereDirectedParticleEmitter
  53084. * @param radius the radius of the emission sphere (1 by default)
  53085. * @param direction1 the min limit of the emission direction (up vector by default)
  53086. * @param direction2 the max limit of the emission direction (up vector by default)
  53087. */
  53088. function SphereDirectedParticleEmitter(radius,
  53089. /**
  53090. * The min limit of the emission direction.
  53091. */
  53092. direction1,
  53093. /**
  53094. * The max limit of the emission direction.
  53095. */
  53096. direction2) {
  53097. if (radius === void 0) { radius = 1; }
  53098. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  53099. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  53100. var _this = _super.call(this, radius) || this;
  53101. _this.direction1 = direction1;
  53102. _this.direction2 = direction2;
  53103. return _this;
  53104. }
  53105. /**
  53106. * Called by the particle System when the direction is computed for the created particle.
  53107. * @param emitPower is the power of the particle (speed)
  53108. * @param worldMatrix is the world matrix of the particle system
  53109. * @param directionToUpdate is the direction vector to update with the result
  53110. * @param particle is the particle we are computed the direction for
  53111. */
  53112. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  53113. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  53114. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  53115. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  53116. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  53117. };
  53118. /**
  53119. * Clones the current emitter and returns a copy of it
  53120. * @returns the new emitter
  53121. */
  53122. SphereDirectedParticleEmitter.prototype.clone = function () {
  53123. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  53124. BABYLON.Tools.DeepCopy(this, newOne);
  53125. return newOne;
  53126. };
  53127. /**
  53128. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53129. * @param effect defines the update shader
  53130. */
  53131. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  53132. effect.setFloat("radius", this.radius);
  53133. effect.setVector3("direction1", this.direction1);
  53134. effect.setVector3("direction2", this.direction2);
  53135. };
  53136. /**
  53137. * Returns a string to use to update the GPU particles update shader
  53138. * @returns a string containng the defines string
  53139. */
  53140. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  53141. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  53142. };
  53143. /**
  53144. * Returns the string "SphereDirectedParticleEmitter"
  53145. * @returns a string containing the class name
  53146. */
  53147. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  53148. return "SphereDirectedParticleEmitter";
  53149. };
  53150. /**
  53151. * Serializes the particle system to a JSON object.
  53152. * @returns the JSON object
  53153. */
  53154. SphereDirectedParticleEmitter.prototype.serialize = function () {
  53155. var serializationObject = _super.prototype.serialize.call(this);
  53156. ;
  53157. serializationObject.direction1 = this.direction1.asArray();
  53158. ;
  53159. serializationObject.direction2 = this.direction2.asArray();
  53160. ;
  53161. return serializationObject;
  53162. };
  53163. /**
  53164. * Parse properties from a JSON object
  53165. * @param serializationObject defines the JSON object
  53166. */
  53167. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  53168. _super.prototype.parse.call(this, serializationObject);
  53169. this.direction1.copyFrom(serializationObject.direction1);
  53170. this.direction2.copyFrom(serializationObject.direction2);
  53171. };
  53172. return SphereDirectedParticleEmitter;
  53173. }(SphereParticleEmitter));
  53174. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  53175. })(BABYLON || (BABYLON = {}));
  53176. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  53177. "use strict";
  53178. var __assign = (this && this.__assign) || Object.assign || function(t) {
  53179. for (var s, i = 1, n = arguments.length; i < n; i++) {
  53180. s = arguments[i];
  53181. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  53182. t[p] = s[p];
  53183. }
  53184. return t;
  53185. };
  53186. var BABYLON;
  53187. (function (BABYLON) {
  53188. /**
  53189. * This represents a GPU particle system in Babylon
  53190. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  53191. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  53192. */
  53193. var GPUParticleSystem = /** @class */ (function () {
  53194. /**
  53195. * Instantiates a GPU particle system.
  53196. * 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.
  53197. * @param name The name of the particle system
  53198. * @param capacity The max number of particles alive at the same time
  53199. * @param scene The scene the particle system belongs to
  53200. */
  53201. function GPUParticleSystem(name, options, scene) {
  53202. /**
  53203. * The emitter represents the Mesh or position we are attaching the particle system to.
  53204. */
  53205. this.emitter = null;
  53206. /**
  53207. * The rendering group used by the Particle system to chose when to render.
  53208. */
  53209. this.renderingGroupId = 0;
  53210. /**
  53211. * The layer mask we are rendering the particles through.
  53212. */
  53213. this.layerMask = 0x0FFFFFFF;
  53214. this._targetIndex = 0;
  53215. this._currentRenderId = -1;
  53216. this._started = false;
  53217. this._stopped = false;
  53218. this._timeDelta = 0;
  53219. this._attributesStrideSize = 14;
  53220. this._actualFrame = 0;
  53221. /**
  53222. * List of animations used by the particle system.
  53223. */
  53224. this.animations = [];
  53225. /**
  53226. * An event triggered when the system is disposed.
  53227. */
  53228. this.onDisposeObservable = new BABYLON.Observable();
  53229. /**
  53230. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  53231. */
  53232. this.updateSpeed = 0.01;
  53233. /**
  53234. * The amount of time the particle system is running (depends of the overall update speed).
  53235. */
  53236. this.targetStopDuration = 0;
  53237. /**
  53238. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  53239. */
  53240. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  53241. /**
  53242. * Minimum life time of emitting particles.
  53243. */
  53244. this.minLifeTime = 1;
  53245. /**
  53246. * Maximum life time of emitting particles.
  53247. */
  53248. this.maxLifeTime = 1;
  53249. /**
  53250. * Minimum Size of emitting particles.
  53251. */
  53252. this.minSize = 1;
  53253. /**
  53254. * Maximum Size of emitting particles.
  53255. */
  53256. this.maxSize = 1;
  53257. /**
  53258. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53259. */
  53260. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53261. /**
  53262. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53263. */
  53264. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53265. /**
  53266. * Color the particle will have at the end of its lifetime.
  53267. */
  53268. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  53269. /**
  53270. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  53271. */
  53272. this.emitRate = 100;
  53273. /**
  53274. * You can use gravity if you want to give an orientation to your particles.
  53275. */
  53276. this.gravity = BABYLON.Vector3.Zero();
  53277. /**
  53278. * Minimum power of emitting particles.
  53279. */
  53280. this.minEmitPower = 1;
  53281. /**
  53282. * Maximum power of emitting particles.
  53283. */
  53284. this.maxEmitPower = 1;
  53285. /**
  53286. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  53287. * to override the particles.
  53288. */
  53289. this.forceDepthWrite = false;
  53290. this.id = name;
  53291. this.name = name;
  53292. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53293. this._engine = this._scene.getEngine();
  53294. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  53295. this._capacity = fullOptions.capacity;
  53296. this._activeCount = fullOptions.capacity;
  53297. this._currentActiveCount = 0;
  53298. this._scene.particleSystems.push(this);
  53299. this._updateEffectOptions = {
  53300. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  53301. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  53302. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  53303. uniformBuffersNames: [],
  53304. samplers: ["randomSampler"],
  53305. defines: "",
  53306. fallbacks: null,
  53307. onCompiled: null,
  53308. onError: null,
  53309. indexParameters: null,
  53310. maxSimultaneousLights: 0,
  53311. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  53312. };
  53313. // Random data
  53314. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  53315. var d = [];
  53316. for (var i = 0; i < maxTextureSize; ++i) {
  53317. d.push(Math.random());
  53318. d.push(Math.random());
  53319. d.push(Math.random());
  53320. d.push(Math.random());
  53321. }
  53322. 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);
  53323. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53324. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53325. this._randomTextureSize = maxTextureSize;
  53326. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  53327. }
  53328. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  53329. /**
  53330. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  53331. */
  53332. get: function () {
  53333. if (!BABYLON.Engine.LastCreatedEngine) {
  53334. return false;
  53335. }
  53336. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  53337. },
  53338. enumerable: true,
  53339. configurable: true
  53340. });
  53341. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  53342. /**
  53343. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53344. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53345. */
  53346. get: function () {
  53347. if (this.particleEmitterType.direction1) {
  53348. return this.particleEmitterType.direction1;
  53349. }
  53350. return BABYLON.Vector3.Zero();
  53351. },
  53352. set: function (value) {
  53353. if (this.particleEmitterType.direction1) {
  53354. this.particleEmitterType.direction1 = value;
  53355. }
  53356. },
  53357. enumerable: true,
  53358. configurable: true
  53359. });
  53360. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  53361. /**
  53362. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53363. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53364. */
  53365. get: function () {
  53366. if (this.particleEmitterType.direction2) {
  53367. return this.particleEmitterType.direction2;
  53368. }
  53369. return BABYLON.Vector3.Zero();
  53370. },
  53371. set: function (value) {
  53372. if (this.particleEmitterType.direction2) {
  53373. this.particleEmitterType.direction2 = value;
  53374. }
  53375. },
  53376. enumerable: true,
  53377. configurable: true
  53378. });
  53379. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  53380. /**
  53381. * 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.
  53382. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53383. */
  53384. get: function () {
  53385. if (this.particleEmitterType.minEmitBox) {
  53386. return this.particleEmitterType.minEmitBox;
  53387. }
  53388. return BABYLON.Vector3.Zero();
  53389. },
  53390. set: function (value) {
  53391. if (this.particleEmitterType.minEmitBox) {
  53392. this.particleEmitterType.minEmitBox = value;
  53393. }
  53394. },
  53395. enumerable: true,
  53396. configurable: true
  53397. });
  53398. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  53399. /**
  53400. * 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.
  53401. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53402. */
  53403. get: function () {
  53404. if (this.particleEmitterType.maxEmitBox) {
  53405. return this.particleEmitterType.maxEmitBox;
  53406. }
  53407. return BABYLON.Vector3.Zero();
  53408. },
  53409. set: function (value) {
  53410. if (this.particleEmitterType.maxEmitBox) {
  53411. this.particleEmitterType.maxEmitBox = value;
  53412. }
  53413. },
  53414. enumerable: true,
  53415. configurable: true
  53416. });
  53417. /**
  53418. * Gets the maximum number of particles active at the same time.
  53419. * @returns The max number of active particles.
  53420. */
  53421. GPUParticleSystem.prototype.getCapacity = function () {
  53422. return this._capacity;
  53423. };
  53424. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  53425. /**
  53426. * Gets or set the number of active particles
  53427. */
  53428. get: function () {
  53429. return this._activeCount;
  53430. },
  53431. set: function (value) {
  53432. this._activeCount = Math.min(value, this._capacity);
  53433. },
  53434. enumerable: true,
  53435. configurable: true
  53436. });
  53437. /**
  53438. * Is this system ready to be used/rendered
  53439. * @return true if the system is ready
  53440. */
  53441. GPUParticleSystem.prototype.isReady = function () {
  53442. if (!this._updateEffect) {
  53443. this._recreateUpdateEffect();
  53444. this._recreateRenderEffect();
  53445. return false;
  53446. }
  53447. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  53448. return false;
  53449. }
  53450. return true;
  53451. };
  53452. /**
  53453. * Gets Wether the system has been started.
  53454. * @returns True if it has been started, otherwise false.
  53455. */
  53456. GPUParticleSystem.prototype.isStarted = function () {
  53457. return this._started;
  53458. };
  53459. /**
  53460. * Starts the particle system and begins to emit.
  53461. */
  53462. GPUParticleSystem.prototype.start = function () {
  53463. this._started = true;
  53464. this._stopped = false;
  53465. };
  53466. /**
  53467. * Stops the particle system.
  53468. */
  53469. GPUParticleSystem.prototype.stop = function () {
  53470. this._stopped = true;
  53471. };
  53472. /**
  53473. * Remove all active particles
  53474. */
  53475. GPUParticleSystem.prototype.reset = function () {
  53476. this._releaseBuffers();
  53477. this._releaseVAOs();
  53478. this._currentActiveCount = 0;
  53479. this._targetIndex = 0;
  53480. };
  53481. /**
  53482. * Returns the string "GPUParticleSystem"
  53483. * @returns a string containing the class name
  53484. */
  53485. GPUParticleSystem.prototype.getClassName = function () {
  53486. return "GPUParticleSystem";
  53487. };
  53488. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  53489. var updateVertexBuffers = {};
  53490. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  53491. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  53492. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  53493. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  53494. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  53495. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  53496. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  53497. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  53498. this._engine.bindArrayBuffer(null);
  53499. return vao;
  53500. };
  53501. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  53502. var renderVertexBuffers = {};
  53503. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  53504. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  53505. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  53506. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  53507. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  53508. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  53509. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  53510. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  53511. this._engine.bindArrayBuffer(null);
  53512. return vao;
  53513. };
  53514. GPUParticleSystem.prototype._initialize = function (force) {
  53515. if (force === void 0) { force = false; }
  53516. if (this._buffer0 && !force) {
  53517. return;
  53518. }
  53519. var engine = this._scene.getEngine();
  53520. var data = new Array();
  53521. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  53522. // position
  53523. data.push(0.0);
  53524. data.push(0.0);
  53525. data.push(0.0);
  53526. // Age and life
  53527. data.push(0.0); // create the particle as a dead one to create a new one at start
  53528. data.push(0.0);
  53529. // Seed
  53530. data.push(Math.random());
  53531. // Size
  53532. data.push(0.0);
  53533. // color
  53534. data.push(0.0);
  53535. data.push(0.0);
  53536. data.push(0.0);
  53537. data.push(0.0);
  53538. // direction
  53539. data.push(0.0);
  53540. data.push(0.0);
  53541. data.push(0.0);
  53542. }
  53543. // Sprite data
  53544. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  53545. -0.5, 0.5, 0, 1,
  53546. -0.5, -0.5, 0, 0,
  53547. 0.5, -0.5, 1, 0]);
  53548. // Buffers
  53549. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53550. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53551. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  53552. // Update VAO
  53553. this._updateVAO = [];
  53554. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  53555. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  53556. // Render VAO
  53557. this._renderVAO = [];
  53558. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  53559. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  53560. // Links
  53561. this._sourceBuffer = this._buffer0;
  53562. this._targetBuffer = this._buffer1;
  53563. };
  53564. /** @ignore */
  53565. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  53566. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  53567. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  53568. return;
  53569. }
  53570. this._updateEffectOptions.defines = defines;
  53571. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  53572. };
  53573. /** @ignore */
  53574. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  53575. var defines = "";
  53576. if (this._scene.clipPlane) {
  53577. defines = "\n#define CLIPPLANE";
  53578. }
  53579. if (this._renderEffect && this._renderEffect.defines === defines) {
  53580. return;
  53581. }
  53582. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  53583. };
  53584. /**
  53585. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  53586. */
  53587. GPUParticleSystem.prototype.animate = function () {
  53588. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  53589. this._actualFrame += this._timeDelta;
  53590. if (!this._stopped) {
  53591. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  53592. this.stop();
  53593. }
  53594. }
  53595. };
  53596. /**
  53597. * Renders the particle system in its current state.
  53598. * @returns the current number of particles
  53599. */
  53600. GPUParticleSystem.prototype.render = function () {
  53601. if (!this._started) {
  53602. return 0;
  53603. }
  53604. this._recreateUpdateEffect();
  53605. this._recreateRenderEffect();
  53606. if (!this.isReady()) {
  53607. return 0;
  53608. }
  53609. if (this._currentRenderId === this._scene.getRenderId()) {
  53610. return 0;
  53611. }
  53612. this._currentRenderId = this._scene.getRenderId();
  53613. // Get everything ready to render
  53614. this._initialize();
  53615. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  53616. // Enable update effect
  53617. this._engine.enableEffect(this._updateEffect);
  53618. this._engine.setState(false);
  53619. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  53620. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  53621. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  53622. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  53623. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  53624. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  53625. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  53626. this._updateEffect.setDirectColor4("color1", this.color1);
  53627. this._updateEffect.setDirectColor4("color2", this.color2);
  53628. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  53629. this._updateEffect.setVector3("gravity", this.gravity);
  53630. if (this.particleEmitterType) {
  53631. this.particleEmitterType.applyToShader(this._updateEffect);
  53632. }
  53633. var emitterWM;
  53634. if (this.emitter.position) {
  53635. var emitterMesh = this.emitter;
  53636. emitterWM = emitterMesh.getWorldMatrix();
  53637. }
  53638. else {
  53639. var emitterPosition = this.emitter;
  53640. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  53641. }
  53642. this._updateEffect.setMatrix("emitterWM", emitterWM);
  53643. // Bind source VAO
  53644. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  53645. // Update
  53646. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  53647. this._engine.setRasterizerState(false);
  53648. this._engine.beginTransformFeedback();
  53649. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  53650. this._engine.endTransformFeedback();
  53651. this._engine.setRasterizerState(true);
  53652. this._engine.bindTransformFeedbackBuffer(null);
  53653. // Enable render effect
  53654. this._engine.enableEffect(this._renderEffect);
  53655. var viewMatrix = this._scene.getViewMatrix();
  53656. this._renderEffect.setMatrix("view", viewMatrix);
  53657. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  53658. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  53659. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  53660. if (this._scene.clipPlane) {
  53661. var clipPlane = this._scene.clipPlane;
  53662. var invView = viewMatrix.clone();
  53663. invView.invert();
  53664. this._renderEffect.setMatrix("invView", invView);
  53665. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  53666. }
  53667. // Draw order
  53668. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  53669. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  53670. }
  53671. else {
  53672. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53673. }
  53674. if (this.forceDepthWrite) {
  53675. this._engine.setDepthWrite(true);
  53676. }
  53677. // Bind source VAO
  53678. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  53679. // Render
  53680. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  53681. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53682. // Switch VAOs
  53683. this._targetIndex++;
  53684. if (this._targetIndex === 2) {
  53685. this._targetIndex = 0;
  53686. }
  53687. // Switch buffers
  53688. var tmpBuffer = this._sourceBuffer;
  53689. this._sourceBuffer = this._targetBuffer;
  53690. this._targetBuffer = tmpBuffer;
  53691. return this._currentActiveCount;
  53692. };
  53693. /**
  53694. * Rebuilds the particle system
  53695. */
  53696. GPUParticleSystem.prototype.rebuild = function () {
  53697. this._initialize(true);
  53698. };
  53699. GPUParticleSystem.prototype._releaseBuffers = function () {
  53700. if (this._buffer0) {
  53701. this._buffer0.dispose();
  53702. this._buffer0 = null;
  53703. }
  53704. if (this._buffer1) {
  53705. this._buffer1.dispose();
  53706. this._buffer1 = null;
  53707. }
  53708. if (this._spriteBuffer) {
  53709. this._spriteBuffer.dispose();
  53710. this._spriteBuffer = null;
  53711. }
  53712. };
  53713. GPUParticleSystem.prototype._releaseVAOs = function () {
  53714. if (!this._updateVAO) {
  53715. return;
  53716. }
  53717. for (var index = 0; index < this._updateVAO.length; index++) {
  53718. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  53719. }
  53720. this._updateVAO = [];
  53721. for (var index = 0; index < this._renderVAO.length; index++) {
  53722. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  53723. }
  53724. this._renderVAO = [];
  53725. };
  53726. /**
  53727. * Disposes the particle system and free the associated resources
  53728. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  53729. */
  53730. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  53731. if (disposeTexture === void 0) { disposeTexture = true; }
  53732. var index = this._scene.particleSystems.indexOf(this);
  53733. if (index > -1) {
  53734. this._scene.particleSystems.splice(index, 1);
  53735. }
  53736. this._releaseBuffers();
  53737. this._releaseVAOs();
  53738. if (this._randomTexture) {
  53739. this._randomTexture.dispose();
  53740. this._randomTexture = null;
  53741. }
  53742. if (disposeTexture && this.particleTexture) {
  53743. this.particleTexture.dispose();
  53744. this.particleTexture = null;
  53745. }
  53746. // Callback
  53747. this.onDisposeObservable.notifyObservers(this);
  53748. this.onDisposeObservable.clear();
  53749. };
  53750. /**
  53751. * Clones the particle system.
  53752. * @param name The name of the cloned object
  53753. * @param newEmitter The new emitter to use
  53754. * @returns the cloned particle system
  53755. */
  53756. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  53757. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  53758. BABYLON.Tools.DeepCopy(this, result);
  53759. if (newEmitter === undefined) {
  53760. newEmitter = this.emitter;
  53761. }
  53762. result.emitter = newEmitter;
  53763. if (this.particleTexture) {
  53764. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  53765. }
  53766. return result;
  53767. };
  53768. /**
  53769. * Serializes the particle system to a JSON object.
  53770. * @returns the JSON object
  53771. */
  53772. GPUParticleSystem.prototype.serialize = function () {
  53773. var serializationObject = {};
  53774. serializationObject.name = this.name;
  53775. serializationObject.id = this.id;
  53776. // Emitter
  53777. if (this.emitter.position) {
  53778. var emitterMesh = this.emitter;
  53779. serializationObject.emitterId = emitterMesh.id;
  53780. }
  53781. else {
  53782. var emitterPosition = this.emitter;
  53783. serializationObject.emitter = emitterPosition.asArray();
  53784. }
  53785. serializationObject.capacity = this.getCapacity();
  53786. if (this.particleTexture) {
  53787. serializationObject.textureName = this.particleTexture.name;
  53788. }
  53789. // Animations
  53790. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  53791. // Particle system
  53792. serializationObject.activeParticleCount = this.activeParticleCount;
  53793. serializationObject.randomTextureSize = this._randomTextureSize;
  53794. serializationObject.minSize = this.minSize;
  53795. serializationObject.maxSize = this.maxSize;
  53796. serializationObject.minEmitPower = this.minEmitPower;
  53797. serializationObject.maxEmitPower = this.maxEmitPower;
  53798. serializationObject.minLifeTime = this.minLifeTime;
  53799. serializationObject.maxLifeTime = this.maxLifeTime;
  53800. serializationObject.emitRate = this.emitRate;
  53801. serializationObject.gravity = this.gravity.asArray();
  53802. serializationObject.color1 = this.color1.asArray();
  53803. serializationObject.color2 = this.color2.asArray();
  53804. serializationObject.colorDead = this.colorDead.asArray();
  53805. serializationObject.updateSpeed = this.updateSpeed;
  53806. serializationObject.targetStopDuration = this.targetStopDuration;
  53807. serializationObject.blendMode = this.blendMode;
  53808. // Emitter
  53809. if (this.particleEmitterType) {
  53810. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  53811. }
  53812. return serializationObject;
  53813. };
  53814. /**
  53815. * Parses a JSON object to create a GPU particle system.
  53816. * @param parsedParticleSystem The JSON object to parse
  53817. * @param scene The scene to create the particle system in
  53818. * @param rootUrl The root url to use to load external dependencies like texture
  53819. * @returns the parsed GPU particle system
  53820. */
  53821. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  53822. var name = parsedParticleSystem.name;
  53823. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  53824. if (parsedParticleSystem.id) {
  53825. particleSystem.id = parsedParticleSystem.id;
  53826. }
  53827. // Texture
  53828. if (parsedParticleSystem.textureName) {
  53829. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53830. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53831. }
  53832. // Emitter
  53833. if (parsedParticleSystem.emitterId) {
  53834. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53835. }
  53836. else {
  53837. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53838. }
  53839. // Animations
  53840. if (parsedParticleSystem.animations) {
  53841. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53842. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53843. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53844. }
  53845. }
  53846. // Particle system
  53847. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  53848. particleSystem.minSize = parsedParticleSystem.minSize;
  53849. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53850. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53851. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53852. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53853. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53854. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53855. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53856. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53857. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53858. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53859. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53860. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53861. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53862. // Emitter
  53863. if (parsedParticleSystem.particleEmitterType) {
  53864. var emitterType = void 0;
  53865. switch (parsedParticleSystem.particleEmitterType.type) {
  53866. case "SphereEmitter":
  53867. emitterType = new BABYLON.SphereParticleEmitter();
  53868. break;
  53869. case "SphereDirectedParticleEmitter":
  53870. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  53871. break;
  53872. case "ConeEmitter":
  53873. emitterType = new BABYLON.ConeParticleEmitter();
  53874. break;
  53875. case "BoxEmitter":
  53876. default:
  53877. emitterType = new BABYLON.BoxParticleEmitter();
  53878. break;
  53879. }
  53880. emitterType.parse(parsedParticleSystem.particleEmitterType);
  53881. particleSystem.particleEmitterType = emitterType;
  53882. }
  53883. return particleSystem;
  53884. };
  53885. return GPUParticleSystem;
  53886. }());
  53887. BABYLON.GPUParticleSystem = GPUParticleSystem;
  53888. })(BABYLON || (BABYLON = {}));
  53889. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  53890. "use strict";
  53891. var BABYLON;
  53892. (function (BABYLON) {
  53893. /**
  53894. * Represents one particle of a solid particle system.
  53895. * @see SolidParticleSystem
  53896. */
  53897. var SolidParticle = /** @class */ (function () {
  53898. /**
  53899. * Creates a Solid Particle object.
  53900. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53901. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53902. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53903. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  53904. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  53905. * @param shapeId (integer) is the model shape identifier in the SPS.
  53906. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53907. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  53908. */
  53909. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53910. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  53911. /**
  53912. * particle global index
  53913. */
  53914. this.idx = 0;
  53915. /**
  53916. * The color of the particle
  53917. */
  53918. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53919. /**
  53920. * The world space position of the particle.
  53921. */
  53922. this.position = BABYLON.Vector3.Zero();
  53923. /**
  53924. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  53925. */
  53926. this.rotation = BABYLON.Vector3.Zero();
  53927. /**
  53928. * The scaling of the particle.
  53929. */
  53930. this.scaling = BABYLON.Vector3.One();
  53931. /**
  53932. * The uvs of the particle.
  53933. */
  53934. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  53935. /**
  53936. * The current speed of the particle.
  53937. */
  53938. this.velocity = BABYLON.Vector3.Zero();
  53939. /**
  53940. * The pivot point in the particle local space.
  53941. */
  53942. this.pivot = BABYLON.Vector3.Zero();
  53943. /**
  53944. * Must the particle be translated from its pivot point in its local space ?
  53945. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  53946. * Default : false
  53947. */
  53948. this.translateFromPivot = false;
  53949. /**
  53950. * Is the particle active or not ?
  53951. */
  53952. this.alive = true;
  53953. /**
  53954. * Is the particle visible or not ?
  53955. */
  53956. this.isVisible = true;
  53957. /**
  53958. * Index of this particle in the global "positions" array (Internal use)
  53959. */
  53960. this._pos = 0;
  53961. /**
  53962. * Index of this particle in the global "indices" array (Internal use)
  53963. */
  53964. this._ind = 0;
  53965. /**
  53966. * ModelShape id of this particle
  53967. */
  53968. this.shapeId = 0;
  53969. /**
  53970. * Index of the particle in its shape id (Internal use)
  53971. */
  53972. this.idxInShape = 0;
  53973. /**
  53974. * Still set as invisible in order to skip useless computations (Internal use)
  53975. */
  53976. this._stillInvisible = false;
  53977. /**
  53978. * Last computed particle rotation matrix
  53979. */
  53980. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53981. /**
  53982. * Parent particle Id, if any.
  53983. * Default null.
  53984. */
  53985. this.parentId = null;
  53986. /**
  53987. * Internal global position in the SPS.
  53988. */
  53989. this._globalPosition = BABYLON.Vector3.Zero();
  53990. this.idx = particleIndex;
  53991. this._pos = positionIndex;
  53992. this._ind = indiceIndex;
  53993. this._model = model;
  53994. this.shapeId = shapeId;
  53995. this.idxInShape = idxInShape;
  53996. this._sps = sps;
  53997. if (modelBoundingInfo) {
  53998. this._modelBoundingInfo = modelBoundingInfo;
  53999. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  54000. }
  54001. }
  54002. Object.defineProperty(SolidParticle.prototype, "scale", {
  54003. /**
  54004. * Legacy support, changed scale to scaling
  54005. */
  54006. get: function () {
  54007. return this.scaling;
  54008. },
  54009. /**
  54010. * Legacy support, changed scale to scaling
  54011. */
  54012. set: function (scale) {
  54013. this.scaling = scale;
  54014. },
  54015. enumerable: true,
  54016. configurable: true
  54017. });
  54018. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  54019. /**
  54020. * Legacy support, changed quaternion to rotationQuaternion
  54021. */
  54022. get: function () {
  54023. return this.rotationQuaternion;
  54024. },
  54025. /**
  54026. * Legacy support, changed quaternion to rotationQuaternion
  54027. */
  54028. set: function (q) {
  54029. this.rotationQuaternion = q;
  54030. },
  54031. enumerable: true,
  54032. configurable: true
  54033. });
  54034. /**
  54035. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  54036. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  54037. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  54038. * @returns true if it intersects
  54039. */
  54040. SolidParticle.prototype.intersectsMesh = function (target) {
  54041. if (!this._boundingInfo || !target._boundingInfo) {
  54042. return false;
  54043. }
  54044. if (this._sps._bSphereOnly) {
  54045. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  54046. }
  54047. return this._boundingInfo.intersects(target._boundingInfo, false);
  54048. };
  54049. return SolidParticle;
  54050. }());
  54051. BABYLON.SolidParticle = SolidParticle;
  54052. /**
  54053. * Represents the shape of the model used by one particle of a solid particle system.
  54054. * SPS internal tool, don't use it manually.
  54055. * @see SolidParticleSystem
  54056. */
  54057. var ModelShape = /** @class */ (function () {
  54058. /**
  54059. * 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.
  54060. * SPS internal tool, don't use it manually.
  54061. * @ignore
  54062. */
  54063. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  54064. /**
  54065. * length of the shape in the model indices array (internal use)
  54066. */
  54067. this._indicesLength = 0;
  54068. this.shapeID = id;
  54069. this._shape = shape;
  54070. this._indicesLength = indicesLength;
  54071. this._shapeUV = shapeUV;
  54072. this._positionFunction = posFunction;
  54073. this._vertexFunction = vtxFunction;
  54074. }
  54075. return ModelShape;
  54076. }());
  54077. BABYLON.ModelShape = ModelShape;
  54078. /**
  54079. * Represents a Depth Sorted Particle in the solid particle system.
  54080. * @see SolidParticleSystem
  54081. */
  54082. var DepthSortedParticle = /** @class */ (function () {
  54083. function DepthSortedParticle() {
  54084. /**
  54085. * Index of the particle in the "indices" array
  54086. */
  54087. this.ind = 0;
  54088. /**
  54089. * Length of the particle shape in the "indices" array
  54090. */
  54091. this.indicesLength = 0;
  54092. /**
  54093. * Squared distance from the particle to the camera
  54094. */
  54095. this.sqDistance = 0.0;
  54096. }
  54097. return DepthSortedParticle;
  54098. }());
  54099. BABYLON.DepthSortedParticle = DepthSortedParticle;
  54100. })(BABYLON || (BABYLON = {}));
  54101. //# sourceMappingURL=babylon.solidParticle.js.map
  54102. "use strict";
  54103. var BABYLON;
  54104. (function (BABYLON) {
  54105. /**
  54106. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  54107. *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.
  54108. * The SPS is also a particle system. It provides some methods to manage the particles.
  54109. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  54110. *
  54111. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  54112. */
  54113. var SolidParticleSystem = /** @class */ (function () {
  54114. /**
  54115. * Creates a SPS (Solid Particle System) object.
  54116. * @param name (String) is the SPS name, this will be the underlying mesh name.
  54117. * @param scene (Scene) is the scene in which the SPS is added.
  54118. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  54119. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  54120. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  54121. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  54122. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  54123. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  54124. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  54125. */
  54126. function SolidParticleSystem(name, scene, options) {
  54127. /**
  54128. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  54129. * Example : var p = SPS.particles[i];
  54130. */
  54131. this.particles = new Array();
  54132. /**
  54133. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  54134. */
  54135. this.nbParticles = 0;
  54136. /**
  54137. * If the particles must ever face the camera (default false). Useful for planar particles.
  54138. */
  54139. this.billboard = false;
  54140. /**
  54141. * Recompute normals when adding a shape
  54142. */
  54143. this.recomputeNormals = true;
  54144. /**
  54145. * This a counter ofr your own usage. It's not set by any SPS functions.
  54146. */
  54147. this.counter = 0;
  54148. /**
  54149. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  54150. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  54151. */
  54152. this.vars = {};
  54153. /**
  54154. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  54155. */
  54156. this._bSphereOnly = false;
  54157. /**
  54158. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  54159. */
  54160. this._bSphereRadiusFactor = 1.0;
  54161. this._positions = new Array();
  54162. this._indices = new Array();
  54163. this._normals = new Array();
  54164. this._colors = new Array();
  54165. this._uvs = new Array();
  54166. this._index = 0; // indices index
  54167. this._updatable = true;
  54168. this._pickable = false;
  54169. this._isVisibilityBoxLocked = false;
  54170. this._alwaysVisible = false;
  54171. this._depthSort = false;
  54172. this._shapeCounter = 0;
  54173. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  54174. this._color = new BABYLON.Color4(0, 0, 0, 0);
  54175. this._computeParticleColor = true;
  54176. this._computeParticleTexture = true;
  54177. this._computeParticleRotation = true;
  54178. this._computeParticleVertex = false;
  54179. this._computeBoundingBox = false;
  54180. this._depthSortParticles = true;
  54181. this._cam_axisZ = BABYLON.Vector3.Zero();
  54182. this._cam_axisY = BABYLON.Vector3.Zero();
  54183. this._cam_axisX = BABYLON.Vector3.Zero();
  54184. this._axisZ = BABYLON.Axis.Z;
  54185. this._camDir = BABYLON.Vector3.Zero();
  54186. this._camInvertedPosition = BABYLON.Vector3.Zero();
  54187. this._rotMatrix = new BABYLON.Matrix();
  54188. this._invertMatrix = new BABYLON.Matrix();
  54189. this._rotated = BABYLON.Vector3.Zero();
  54190. this._quaternion = new BABYLON.Quaternion();
  54191. this._vertex = BABYLON.Vector3.Zero();
  54192. this._normal = BABYLON.Vector3.Zero();
  54193. this._yaw = 0.0;
  54194. this._pitch = 0.0;
  54195. this._roll = 0.0;
  54196. this._halfroll = 0.0;
  54197. this._halfpitch = 0.0;
  54198. this._halfyaw = 0.0;
  54199. this._sinRoll = 0.0;
  54200. this._cosRoll = 0.0;
  54201. this._sinPitch = 0.0;
  54202. this._cosPitch = 0.0;
  54203. this._sinYaw = 0.0;
  54204. this._cosYaw = 0.0;
  54205. this._mustUnrotateFixedNormals = false;
  54206. this._minimum = BABYLON.Vector3.Zero();
  54207. this._maximum = BABYLON.Vector3.Zero();
  54208. this._minBbox = BABYLON.Vector3.Zero();
  54209. this._maxBbox = BABYLON.Vector3.Zero();
  54210. this._particlesIntersect = false;
  54211. this._depthSortFunction = function (p1, p2) {
  54212. return (p2.sqDistance - p1.sqDistance);
  54213. };
  54214. this._needs32Bits = false;
  54215. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  54216. this._scaledPivot = BABYLON.Vector3.Zero();
  54217. this._particleHasParent = false;
  54218. this.name = name;
  54219. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54220. this._camera = scene.activeCamera;
  54221. this._pickable = options ? options.isPickable : false;
  54222. this._depthSort = options ? options.enableDepthSort : false;
  54223. this._particlesIntersect = options ? options.particleIntersection : false;
  54224. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  54225. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  54226. if (options && options.updatable) {
  54227. this._updatable = options.updatable;
  54228. }
  54229. else {
  54230. this._updatable = true;
  54231. }
  54232. if (this._pickable) {
  54233. this.pickedParticles = [];
  54234. }
  54235. if (this._depthSort) {
  54236. this.depthSortedParticles = [];
  54237. }
  54238. }
  54239. /**
  54240. * Builds the SPS underlying mesh. Returns a standard Mesh.
  54241. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  54242. * @returns the created mesh
  54243. */
  54244. SolidParticleSystem.prototype.buildMesh = function () {
  54245. if (this.nbParticles === 0) {
  54246. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  54247. this.addShape(triangle, 1);
  54248. triangle.dispose();
  54249. }
  54250. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  54251. this._positions32 = new Float32Array(this._positions);
  54252. this._uvs32 = new Float32Array(this._uvs);
  54253. this._colors32 = new Float32Array(this._colors);
  54254. if (this.recomputeNormals) {
  54255. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  54256. }
  54257. this._normals32 = new Float32Array(this._normals);
  54258. this._fixedNormal32 = new Float32Array(this._normals);
  54259. if (this._mustUnrotateFixedNormals) {
  54260. this._unrotateFixedNormals();
  54261. }
  54262. var vertexData = new BABYLON.VertexData();
  54263. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  54264. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  54265. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  54266. if (this._uvs32) {
  54267. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  54268. ;
  54269. }
  54270. if (this._colors32) {
  54271. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  54272. }
  54273. var mesh = new BABYLON.Mesh(this.name, this._scene);
  54274. vertexData.applyToMesh(mesh, this._updatable);
  54275. this.mesh = mesh;
  54276. this.mesh.isPickable = this._pickable;
  54277. // free memory
  54278. if (!this._depthSort) {
  54279. this._indices = null;
  54280. }
  54281. this._positions = null;
  54282. this._normals = null;
  54283. this._uvs = null;
  54284. this._colors = null;
  54285. if (!this._updatable) {
  54286. this.particles.length = 0;
  54287. }
  54288. return mesh;
  54289. };
  54290. /**
  54291. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  54292. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  54293. * Thus the particles generated from `digest()` have their property `position` set yet.
  54294. * @param mesh ( Mesh ) is the mesh to be digested
  54295. * @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
  54296. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  54297. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  54298. * @returns the current SPS
  54299. */
  54300. SolidParticleSystem.prototype.digest = function (mesh, options) {
  54301. var size = (options && options.facetNb) || 1;
  54302. var number = (options && options.number) || 0;
  54303. var delta = (options && options.delta) || 0;
  54304. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54305. var meshInd = mesh.getIndices();
  54306. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54307. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54308. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54309. var f = 0; // facet counter
  54310. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  54311. // compute size from number
  54312. if (number) {
  54313. number = (number > totalFacets) ? totalFacets : number;
  54314. size = Math.round(totalFacets / number);
  54315. delta = 0;
  54316. }
  54317. else {
  54318. size = (size > totalFacets) ? totalFacets : size;
  54319. }
  54320. var facetPos = []; // submesh positions
  54321. var facetInd = []; // submesh indices
  54322. var facetUV = []; // submesh UV
  54323. var facetCol = []; // submesh colors
  54324. var barycenter = BABYLON.Vector3.Zero();
  54325. var sizeO = size;
  54326. while (f < totalFacets) {
  54327. size = sizeO + Math.floor((1 + delta) * Math.random());
  54328. if (f > totalFacets - size) {
  54329. size = totalFacets - f;
  54330. }
  54331. // reset temp arrays
  54332. facetPos.length = 0;
  54333. facetInd.length = 0;
  54334. facetUV.length = 0;
  54335. facetCol.length = 0;
  54336. // iterate over "size" facets
  54337. var fi = 0;
  54338. for (var j = f * 3; j < (f + size) * 3; j++) {
  54339. facetInd.push(fi);
  54340. var i = meshInd[j];
  54341. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  54342. if (meshUV) {
  54343. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  54344. }
  54345. if (meshCol) {
  54346. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  54347. }
  54348. fi++;
  54349. }
  54350. // create a model shape for each single particle
  54351. var idx = this.nbParticles;
  54352. var shape = this._posToShape(facetPos);
  54353. var shapeUV = this._uvsToShapeUV(facetUV);
  54354. // compute the barycenter of the shape
  54355. var v;
  54356. for (v = 0; v < shape.length; v++) {
  54357. barycenter.addInPlace(shape[v]);
  54358. }
  54359. barycenter.scaleInPlace(1 / shape.length);
  54360. // shift the shape from its barycenter to the origin
  54361. for (v = 0; v < shape.length; v++) {
  54362. shape[v].subtractInPlace(barycenter);
  54363. }
  54364. var bInfo;
  54365. if (this._particlesIntersect) {
  54366. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  54367. }
  54368. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  54369. // add the particle in the SPS
  54370. var currentPos = this._positions.length;
  54371. var currentInd = this._indices.length;
  54372. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  54373. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  54374. // initialize the particle position
  54375. this.particles[this.nbParticles].position.addInPlace(barycenter);
  54376. this._index += shape.length;
  54377. idx++;
  54378. this.nbParticles++;
  54379. this._shapeCounter++;
  54380. f += size;
  54381. }
  54382. return this;
  54383. };
  54384. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  54385. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  54386. var index = 0;
  54387. var idx = 0;
  54388. for (var p = 0; p < this.particles.length; p++) {
  54389. this._particle = this.particles[p];
  54390. this._shape = this._particle._model._shape;
  54391. if (this._particle.rotationQuaternion) {
  54392. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54393. }
  54394. else {
  54395. this._yaw = this._particle.rotation.y;
  54396. this._pitch = this._particle.rotation.x;
  54397. this._roll = this._particle.rotation.z;
  54398. this._quaternionRotationYPR();
  54399. }
  54400. this._quaternionToRotationMatrix();
  54401. this._rotMatrix.invertToRef(this._invertMatrix);
  54402. for (var pt = 0; pt < this._shape.length; pt++) {
  54403. idx = index + pt * 3;
  54404. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  54405. this._fixedNormal32[idx] = this._normal.x;
  54406. this._fixedNormal32[idx + 1] = this._normal.y;
  54407. this._fixedNormal32[idx + 2] = this._normal.z;
  54408. }
  54409. index = idx + 3;
  54410. }
  54411. };
  54412. //reset copy
  54413. SolidParticleSystem.prototype._resetCopy = function () {
  54414. this._copy.position.x = 0;
  54415. this._copy.position.y = 0;
  54416. this._copy.position.z = 0;
  54417. this._copy.rotation.x = 0;
  54418. this._copy.rotation.y = 0;
  54419. this._copy.rotation.z = 0;
  54420. this._copy.rotationQuaternion = null;
  54421. this._copy.scaling.x = 1.0;
  54422. this._copy.scaling.y = 1.0;
  54423. this._copy.scaling.z = 1.0;
  54424. this._copy.uvs.x = 0;
  54425. this._copy.uvs.y = 0;
  54426. this._copy.uvs.z = 1.0;
  54427. this._copy.uvs.w = 1.0;
  54428. this._copy.color = null;
  54429. this._copy.translateFromPivot = false;
  54430. };
  54431. // _meshBuilder : inserts the shape model in the global SPS mesh
  54432. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  54433. var i;
  54434. var u = 0;
  54435. var c = 0;
  54436. var n = 0;
  54437. this._resetCopy();
  54438. if (options && options.positionFunction) {
  54439. options.positionFunction(this._copy, idx, idxInShape);
  54440. this._mustUnrotateFixedNormals = true;
  54441. }
  54442. if (this._copy.rotationQuaternion) {
  54443. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54444. }
  54445. else {
  54446. this._yaw = this._copy.rotation.y;
  54447. this._pitch = this._copy.rotation.x;
  54448. this._roll = this._copy.rotation.z;
  54449. this._quaternionRotationYPR();
  54450. }
  54451. this._quaternionToRotationMatrix();
  54452. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  54453. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  54454. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  54455. if (this._copy.translateFromPivot) {
  54456. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54457. }
  54458. else {
  54459. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54460. }
  54461. for (i = 0; i < shape.length; i++) {
  54462. this._vertex.x = shape[i].x;
  54463. this._vertex.y = shape[i].y;
  54464. this._vertex.z = shape[i].z;
  54465. if (options && options.vertexFunction) {
  54466. options.vertexFunction(this._copy, this._vertex, i);
  54467. }
  54468. this._vertex.x *= this._copy.scaling.x;
  54469. this._vertex.y *= this._copy.scaling.y;
  54470. this._vertex.z *= this._copy.scaling.z;
  54471. this._vertex.x -= this._scaledPivot.x;
  54472. this._vertex.y -= this._scaledPivot.y;
  54473. this._vertex.z -= this._scaledPivot.z;
  54474. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54475. this._rotated.addInPlace(this._pivotBackTranslation);
  54476. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54477. if (meshUV) {
  54478. 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);
  54479. u += 2;
  54480. }
  54481. if (this._copy.color) {
  54482. this._color = this._copy.color;
  54483. }
  54484. else if (meshCol && meshCol[c] !== undefined) {
  54485. this._color.r = meshCol[c];
  54486. this._color.g = meshCol[c + 1];
  54487. this._color.b = meshCol[c + 2];
  54488. this._color.a = meshCol[c + 3];
  54489. }
  54490. else {
  54491. this._color.r = 1.0;
  54492. this._color.g = 1.0;
  54493. this._color.b = 1.0;
  54494. this._color.a = 1.0;
  54495. }
  54496. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54497. c += 4;
  54498. if (!this.recomputeNormals && meshNor) {
  54499. this._normal.x = meshNor[n];
  54500. this._normal.y = meshNor[n + 1];
  54501. this._normal.z = meshNor[n + 2];
  54502. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54503. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54504. n += 3;
  54505. }
  54506. }
  54507. for (i = 0; i < meshInd.length; i++) {
  54508. var current_ind = p + meshInd[i];
  54509. indices.push(current_ind);
  54510. if (current_ind > 65535) {
  54511. this._needs32Bits = true;
  54512. }
  54513. }
  54514. if (this._pickable) {
  54515. var nbfaces = meshInd.length / 3;
  54516. for (i = 0; i < nbfaces; i++) {
  54517. this.pickedParticles.push({ idx: idx, faceId: i });
  54518. }
  54519. }
  54520. if (this._depthSort) {
  54521. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  54522. }
  54523. return this._copy;
  54524. };
  54525. // returns a shape array from positions array
  54526. SolidParticleSystem.prototype._posToShape = function (positions) {
  54527. var shape = [];
  54528. for (var i = 0; i < positions.length; i += 3) {
  54529. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54530. }
  54531. return shape;
  54532. };
  54533. // returns a shapeUV array from a Vector4 uvs
  54534. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54535. var shapeUV = [];
  54536. if (uvs) {
  54537. for (var i = 0; i < uvs.length; i++)
  54538. shapeUV.push(uvs[i]);
  54539. }
  54540. return shapeUV;
  54541. };
  54542. // adds a new particle object in the particles array
  54543. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  54544. if (bInfo === void 0) { bInfo = null; }
  54545. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  54546. this.particles.push(sp);
  54547. return sp;
  54548. };
  54549. /**
  54550. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54551. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54552. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  54553. * @param nb (positive integer) the number of particles to be created from this model
  54554. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  54555. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  54556. * @returns the number of shapes in the system
  54557. */
  54558. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54559. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54560. var meshInd = mesh.getIndices();
  54561. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54562. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54563. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54564. var bbInfo;
  54565. if (this._particlesIntersect) {
  54566. bbInfo = mesh.getBoundingInfo();
  54567. }
  54568. var shape = this._posToShape(meshPos);
  54569. var shapeUV = this._uvsToShapeUV(meshUV);
  54570. var posfunc = options ? options.positionFunction : null;
  54571. var vtxfunc = options ? options.vertexFunction : null;
  54572. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  54573. // particles
  54574. var sp;
  54575. var currentCopy;
  54576. var idx = this.nbParticles;
  54577. for (var i = 0; i < nb; i++) {
  54578. var currentPos = this._positions.length;
  54579. var currentInd = this._indices.length;
  54580. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54581. if (this._updatable) {
  54582. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  54583. sp.position.copyFrom(currentCopy.position);
  54584. sp.rotation.copyFrom(currentCopy.rotation);
  54585. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  54586. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54587. }
  54588. if (currentCopy.color && sp.color) {
  54589. sp.color.copyFrom(currentCopy.color);
  54590. }
  54591. sp.scaling.copyFrom(currentCopy.scaling);
  54592. sp.uvs.copyFrom(currentCopy.uvs);
  54593. }
  54594. this._index += shape.length;
  54595. idx++;
  54596. }
  54597. this.nbParticles += nb;
  54598. this._shapeCounter++;
  54599. return this._shapeCounter - 1;
  54600. };
  54601. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54602. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54603. this._resetCopy();
  54604. if (particle._model._positionFunction) {
  54605. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54606. }
  54607. if (this._copy.rotationQuaternion) {
  54608. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54609. }
  54610. else {
  54611. this._yaw = this._copy.rotation.y;
  54612. this._pitch = this._copy.rotation.x;
  54613. this._roll = this._copy.rotation.z;
  54614. this._quaternionRotationYPR();
  54615. }
  54616. this._quaternionToRotationMatrix();
  54617. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54618. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54619. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54620. if (this._copy.translateFromPivot) {
  54621. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54622. }
  54623. else {
  54624. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54625. }
  54626. this._shape = particle._model._shape;
  54627. for (var pt = 0; pt < this._shape.length; pt++) {
  54628. this._vertex.x = this._shape[pt].x;
  54629. this._vertex.y = this._shape[pt].y;
  54630. this._vertex.z = this._shape[pt].z;
  54631. if (particle._model._vertexFunction) {
  54632. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54633. }
  54634. this._vertex.x *= this._copy.scaling.x;
  54635. this._vertex.y *= this._copy.scaling.y;
  54636. this._vertex.z *= this._copy.scaling.z;
  54637. this._vertex.x -= this._scaledPivot.x;
  54638. this._vertex.y -= this._scaledPivot.y;
  54639. this._vertex.z -= this._scaledPivot.z;
  54640. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54641. this._rotated.addInPlace(this._pivotBackTranslation);
  54642. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54643. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54644. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54645. }
  54646. particle.position.x = 0.0;
  54647. particle.position.y = 0.0;
  54648. particle.position.z = 0.0;
  54649. particle.rotation.x = 0.0;
  54650. particle.rotation.y = 0.0;
  54651. particle.rotation.z = 0.0;
  54652. particle.rotationQuaternion = null;
  54653. particle.scaling.x = 1.0;
  54654. particle.scaling.y = 1.0;
  54655. particle.scaling.z = 1.0;
  54656. particle.uvs.x = 0.0;
  54657. particle.uvs.y = 0.0;
  54658. particle.uvs.z = 1.0;
  54659. particle.uvs.w = 1.0;
  54660. particle.pivot.x = 0.0;
  54661. particle.pivot.y = 0.0;
  54662. particle.pivot.z = 0.0;
  54663. particle.translateFromPivot = false;
  54664. particle.parentId = null;
  54665. };
  54666. /**
  54667. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54668. * @returns the SPS.
  54669. */
  54670. SolidParticleSystem.prototype.rebuildMesh = function () {
  54671. for (var p = 0; p < this.particles.length; p++) {
  54672. this._rebuildParticle(this.particles[p]);
  54673. }
  54674. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54675. return this;
  54676. };
  54677. /**
  54678. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54679. * This method calls `updateParticle()` for each particle of the SPS.
  54680. * For an animated SPS, it is usually called within the render loop.
  54681. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54682. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54683. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54684. * @returns the SPS.
  54685. */
  54686. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54687. if (start === void 0) { start = 0; }
  54688. if (end === void 0) { end = this.nbParticles - 1; }
  54689. if (update === void 0) { update = true; }
  54690. if (!this._updatable) {
  54691. return this;
  54692. }
  54693. // custom beforeUpdate
  54694. this.beforeUpdateParticles(start, end, update);
  54695. this._cam_axisX.x = 1.0;
  54696. this._cam_axisX.y = 0.0;
  54697. this._cam_axisX.z = 0.0;
  54698. this._cam_axisY.x = 0.0;
  54699. this._cam_axisY.y = 1.0;
  54700. this._cam_axisY.z = 0.0;
  54701. this._cam_axisZ.x = 0.0;
  54702. this._cam_axisZ.y = 0.0;
  54703. this._cam_axisZ.z = 1.0;
  54704. // cases when the World Matrix is to be computed first
  54705. if (this.billboard || this._depthSort) {
  54706. this.mesh.computeWorldMatrix(true);
  54707. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  54708. }
  54709. // if the particles will always face the camera
  54710. if (this.billboard) {
  54711. // compute the camera position and un-rotate it by the current mesh rotation
  54712. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  54713. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54714. this._cam_axisZ.normalize();
  54715. // same for camera up vector extracted from the cam view matrix
  54716. var view = this._camera.getViewMatrix(true);
  54717. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54718. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54719. this._cam_axisY.normalize();
  54720. this._cam_axisX.normalize();
  54721. }
  54722. // if depthSort, compute the camera global position in the mesh local system
  54723. if (this._depthSort) {
  54724. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  54725. }
  54726. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54727. var idx = 0; // current position index in the global array positions32
  54728. var index = 0; // position start index in the global array positions32 of the current particle
  54729. var colidx = 0; // current color index in the global array colors32
  54730. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54731. var uvidx = 0; // current uv index in the global array uvs32
  54732. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54733. var pt = 0; // current index in the particle model shape
  54734. if (this.mesh.isFacetDataEnabled) {
  54735. this._computeBoundingBox = true;
  54736. }
  54737. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54738. if (this._computeBoundingBox) {
  54739. if (start == 0 && end == this.nbParticles - 1) {
  54740. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54741. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54742. }
  54743. else {
  54744. if (this.mesh._boundingInfo) {
  54745. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54746. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54747. }
  54748. }
  54749. }
  54750. // particle loop
  54751. index = this.particles[start]._pos;
  54752. var vpos = (index / 3) | 0;
  54753. colorIndex = vpos * 4;
  54754. uvIndex = vpos * 2;
  54755. for (var p = start; p <= end; p++) {
  54756. this._particle = this.particles[p];
  54757. this._shape = this._particle._model._shape;
  54758. this._shapeUV = this._particle._model._shapeUV;
  54759. // call to custom user function to update the particle properties
  54760. this.updateParticle(this._particle);
  54761. // camera-particle distance for depth sorting
  54762. if (this._depthSort && this._depthSortParticles) {
  54763. var dsp = this.depthSortedParticles[p];
  54764. dsp.ind = this._particle._ind;
  54765. dsp.indicesLength = this._particle._model._indicesLength;
  54766. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  54767. }
  54768. // skip the computations for inactive or already invisible particles
  54769. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  54770. // increment indexes for the next particle
  54771. pt = this._shape.length;
  54772. index += pt * 3;
  54773. colorIndex += pt * 4;
  54774. uvIndex += pt * 2;
  54775. continue;
  54776. }
  54777. if (this._particle.isVisible) {
  54778. this._particle._stillInvisible = false; // un-mark permanent invisibility
  54779. this._particleHasParent = (this._particle.parentId !== null);
  54780. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54781. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54782. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54783. // particle rotation matrix
  54784. if (this.billboard) {
  54785. this._particle.rotation.x = 0.0;
  54786. this._particle.rotation.y = 0.0;
  54787. }
  54788. if (this._computeParticleRotation || this.billboard) {
  54789. if (this._particle.rotationQuaternion) {
  54790. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54791. }
  54792. else {
  54793. this._yaw = this._particle.rotation.y;
  54794. this._pitch = this._particle.rotation.x;
  54795. this._roll = this._particle.rotation.z;
  54796. this._quaternionRotationYPR();
  54797. }
  54798. this._quaternionToRotationMatrix();
  54799. }
  54800. if (this._particleHasParent) {
  54801. this._parent = this.particles[this._particle.parentId];
  54802. 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];
  54803. 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];
  54804. 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];
  54805. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  54806. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  54807. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  54808. if (this._computeParticleRotation || this.billboard) {
  54809. 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];
  54810. 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];
  54811. 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];
  54812. 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];
  54813. 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];
  54814. 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];
  54815. 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];
  54816. 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];
  54817. 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];
  54818. }
  54819. }
  54820. else {
  54821. this._particle._globalPosition.x = this._particle.position.x;
  54822. this._particle._globalPosition.y = this._particle.position.y;
  54823. this._particle._globalPosition.z = this._particle.position.z;
  54824. if (this._computeParticleRotation || this.billboard) {
  54825. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  54826. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  54827. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  54828. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  54829. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  54830. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  54831. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  54832. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  54833. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  54834. }
  54835. }
  54836. if (this._particle.translateFromPivot) {
  54837. this._pivotBackTranslation.x = 0.0;
  54838. this._pivotBackTranslation.y = 0.0;
  54839. this._pivotBackTranslation.z = 0.0;
  54840. }
  54841. else {
  54842. this._pivotBackTranslation.x = this._scaledPivot.x;
  54843. this._pivotBackTranslation.y = this._scaledPivot.y;
  54844. this._pivotBackTranslation.z = this._scaledPivot.z;
  54845. }
  54846. // particle vertex loop
  54847. for (pt = 0; pt < this._shape.length; pt++) {
  54848. idx = index + pt * 3;
  54849. colidx = colorIndex + pt * 4;
  54850. uvidx = uvIndex + pt * 2;
  54851. this._vertex.x = this._shape[pt].x;
  54852. this._vertex.y = this._shape[pt].y;
  54853. this._vertex.z = this._shape[pt].z;
  54854. if (this._computeParticleVertex) {
  54855. this.updateParticleVertex(this._particle, this._vertex, pt);
  54856. }
  54857. // positions
  54858. this._vertex.x *= this._particle.scaling.x;
  54859. this._vertex.y *= this._particle.scaling.y;
  54860. this._vertex.z *= this._particle.scaling.z;
  54861. this._vertex.x -= this._scaledPivot.x;
  54862. this._vertex.y -= this._scaledPivot.y;
  54863. this._vertex.z -= this._scaledPivot.z;
  54864. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54865. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54866. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54867. this._rotated.x += this._pivotBackTranslation.x;
  54868. this._rotated.y += this._pivotBackTranslation.y;
  54869. this._rotated.z += this._pivotBackTranslation.z;
  54870. 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;
  54871. 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;
  54872. 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;
  54873. if (this._computeBoundingBox) {
  54874. if (this._positions32[idx] < this._minimum.x) {
  54875. this._minimum.x = this._positions32[idx];
  54876. }
  54877. if (this._positions32[idx] > this._maximum.x) {
  54878. this._maximum.x = this._positions32[idx];
  54879. }
  54880. if (this._positions32[idx + 1] < this._minimum.y) {
  54881. this._minimum.y = this._positions32[idx + 1];
  54882. }
  54883. if (this._positions32[idx + 1] > this._maximum.y) {
  54884. this._maximum.y = this._positions32[idx + 1];
  54885. }
  54886. if (this._positions32[idx + 2] < this._minimum.z) {
  54887. this._minimum.z = this._positions32[idx + 2];
  54888. }
  54889. if (this._positions32[idx + 2] > this._maximum.z) {
  54890. this._maximum.z = this._positions32[idx + 2];
  54891. }
  54892. }
  54893. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54894. if (!this._computeParticleVertex) {
  54895. this._normal.x = this._fixedNormal32[idx];
  54896. this._normal.y = this._fixedNormal32[idx + 1];
  54897. this._normal.z = this._fixedNormal32[idx + 2];
  54898. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  54899. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  54900. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  54901. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54902. 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;
  54903. 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;
  54904. }
  54905. if (this._computeParticleColor && this._particle.color) {
  54906. this._colors32[colidx] = this._particle.color.r;
  54907. this._colors32[colidx + 1] = this._particle.color.g;
  54908. this._colors32[colidx + 2] = this._particle.color.b;
  54909. this._colors32[colidx + 3] = this._particle.color.a;
  54910. }
  54911. if (this._computeParticleTexture) {
  54912. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54913. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54914. }
  54915. }
  54916. }
  54917. else {
  54918. this._particle._stillInvisible = true; // mark the particle as invisible
  54919. for (pt = 0; pt < this._shape.length; pt++) {
  54920. idx = index + pt * 3;
  54921. colidx = colorIndex + pt * 4;
  54922. uvidx = uvIndex + pt * 2;
  54923. this._positions32[idx] = 0.0;
  54924. this._positions32[idx + 1] = 0.0;
  54925. this._positions32[idx + 2] = 0.0;
  54926. this._normals32[idx] = 0.0;
  54927. this._normals32[idx + 1] = 0.0;
  54928. this._normals32[idx + 2] = 0.0;
  54929. if (this._computeParticleColor && this._particle.color) {
  54930. this._colors32[colidx] = this._particle.color.r;
  54931. this._colors32[colidx + 1] = this._particle.color.g;
  54932. this._colors32[colidx + 2] = this._particle.color.b;
  54933. this._colors32[colidx + 3] = this._particle.color.a;
  54934. }
  54935. if (this._computeParticleTexture) {
  54936. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54937. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54938. }
  54939. }
  54940. }
  54941. // if the particle intersections must be computed : update the bbInfo
  54942. if (this._particlesIntersect) {
  54943. var bInfo = this._particle._boundingInfo;
  54944. var bBox = bInfo.boundingBox;
  54945. var bSphere = bInfo.boundingSphere;
  54946. if (!this._bSphereOnly) {
  54947. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54948. for (var b = 0; b < bBox.vectors.length; b++) {
  54949. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54950. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54951. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54952. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54953. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54954. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54955. 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;
  54956. 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;
  54957. 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;
  54958. }
  54959. bBox._update(this.mesh._worldMatrix);
  54960. }
  54961. // place and scale the particle bouding sphere in the SPS local system, then update it
  54962. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54963. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54964. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54965. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54966. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54967. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54968. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54969. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54970. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54971. 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));
  54972. bSphere._update(this.mesh._worldMatrix);
  54973. }
  54974. // increment indexes for the next particle
  54975. index = idx + 3;
  54976. colorIndex = colidx + 4;
  54977. uvIndex = uvidx + 2;
  54978. }
  54979. // if the VBO must be updated
  54980. if (update) {
  54981. if (this._computeParticleColor) {
  54982. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54983. }
  54984. if (this._computeParticleTexture) {
  54985. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54986. }
  54987. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54988. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54989. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54990. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54991. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54992. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54993. for (var i = 0; i < this._normals32.length; i++) {
  54994. this._fixedNormal32[i] = this._normals32[i];
  54995. }
  54996. }
  54997. if (!this.mesh.areNormalsFrozen) {
  54998. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54999. }
  55000. }
  55001. if (this._depthSort && this._depthSortParticles) {
  55002. this.depthSortedParticles.sort(this._depthSortFunction);
  55003. var dspl = this.depthSortedParticles.length;
  55004. var sorted = 0;
  55005. var lind = 0;
  55006. var sind = 0;
  55007. var sid = 0;
  55008. for (sorted = 0; sorted < dspl; sorted++) {
  55009. lind = this.depthSortedParticles[sorted].indicesLength;
  55010. sind = this.depthSortedParticles[sorted].ind;
  55011. for (var i = 0; i < lind; i++) {
  55012. this._indices32[sid] = this._indices[sind + i];
  55013. sid++;
  55014. }
  55015. }
  55016. this.mesh.updateIndices(this._indices32);
  55017. }
  55018. }
  55019. if (this._computeBoundingBox) {
  55020. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  55021. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  55022. }
  55023. this.afterUpdateParticles(start, end, update);
  55024. return this;
  55025. };
  55026. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  55027. this._halfroll = this._roll * 0.5;
  55028. this._halfpitch = this._pitch * 0.5;
  55029. this._halfyaw = this._yaw * 0.5;
  55030. this._sinRoll = Math.sin(this._halfroll);
  55031. this._cosRoll = Math.cos(this._halfroll);
  55032. this._sinPitch = Math.sin(this._halfpitch);
  55033. this._cosPitch = Math.cos(this._halfpitch);
  55034. this._sinYaw = Math.sin(this._halfyaw);
  55035. this._cosYaw = Math.cos(this._halfyaw);
  55036. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  55037. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  55038. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  55039. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  55040. };
  55041. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  55042. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  55043. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  55044. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  55045. this._rotMatrix.m[3] = 0;
  55046. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  55047. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  55048. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  55049. this._rotMatrix.m[7] = 0;
  55050. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  55051. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  55052. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  55053. this._rotMatrix.m[11] = 0;
  55054. this._rotMatrix.m[12] = 0;
  55055. this._rotMatrix.m[13] = 0;
  55056. this._rotMatrix.m[14] = 0;
  55057. this._rotMatrix.m[15] = 1.0;
  55058. };
  55059. /**
  55060. * Disposes the SPS.
  55061. */
  55062. SolidParticleSystem.prototype.dispose = function () {
  55063. this.mesh.dispose();
  55064. this.vars = null;
  55065. // drop references to internal big arrays for the GC
  55066. this._positions = null;
  55067. this._indices = null;
  55068. this._normals = null;
  55069. this._uvs = null;
  55070. this._colors = null;
  55071. this._indices32 = null;
  55072. this._positions32 = null;
  55073. this._normals32 = null;
  55074. this._fixedNormal32 = null;
  55075. this._uvs32 = null;
  55076. this._colors32 = null;
  55077. this.pickedParticles = null;
  55078. };
  55079. /**
  55080. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  55081. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55082. * @returns the SPS.
  55083. */
  55084. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  55085. if (!this._isVisibilityBoxLocked) {
  55086. this.mesh.refreshBoundingInfo();
  55087. }
  55088. return this;
  55089. };
  55090. /**
  55091. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  55092. * @param size the size (float) of the visibility box
  55093. * note : this doesn't lock the SPS mesh bounding box.
  55094. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55095. */
  55096. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  55097. var vis = size / 2;
  55098. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  55099. };
  55100. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  55101. /**
  55102. * Gets whether the SPS as always visible or not
  55103. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55104. */
  55105. get: function () {
  55106. return this._alwaysVisible;
  55107. },
  55108. /**
  55109. * Sets the SPS as always visible or not
  55110. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55111. */
  55112. set: function (val) {
  55113. this._alwaysVisible = val;
  55114. this.mesh.alwaysSelectAsActiveMesh = val;
  55115. },
  55116. enumerable: true,
  55117. configurable: true
  55118. });
  55119. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  55120. /**
  55121. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55122. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55123. */
  55124. get: function () {
  55125. return this._isVisibilityBoxLocked;
  55126. },
  55127. /**
  55128. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55129. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55130. */
  55131. set: function (val) {
  55132. this._isVisibilityBoxLocked = val;
  55133. var boundingInfo = this.mesh.getBoundingInfo();
  55134. boundingInfo.isLocked = val;
  55135. },
  55136. enumerable: true,
  55137. configurable: true
  55138. });
  55139. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  55140. /**
  55141. * Gets if `setParticles()` computes the particle rotations or not.
  55142. * Default value : true. The SPS is faster when it's set to false.
  55143. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55144. */
  55145. get: function () {
  55146. return this._computeParticleRotation;
  55147. },
  55148. /**
  55149. * Tells to `setParticles()` to compute the particle rotations or not.
  55150. * Default value : true. The SPS is faster when it's set to false.
  55151. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55152. */
  55153. set: function (val) {
  55154. this._computeParticleRotation = val;
  55155. },
  55156. enumerable: true,
  55157. configurable: true
  55158. });
  55159. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  55160. /**
  55161. * Gets if `setParticles()` computes the particle colors or not.
  55162. * Default value : true. The SPS is faster when it's set to false.
  55163. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55164. */
  55165. get: function () {
  55166. return this._computeParticleColor;
  55167. },
  55168. /**
  55169. * Tells to `setParticles()` to compute the particle colors or not.
  55170. * Default value : true. The SPS is faster when it's set to false.
  55171. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55172. */
  55173. set: function (val) {
  55174. this._computeParticleColor = val;
  55175. },
  55176. enumerable: true,
  55177. configurable: true
  55178. });
  55179. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  55180. /**
  55181. * Gets if `setParticles()` computes the particle textures or not.
  55182. * Default value : true. The SPS is faster when it's set to false.
  55183. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  55184. */
  55185. get: function () {
  55186. return this._computeParticleTexture;
  55187. },
  55188. set: function (val) {
  55189. this._computeParticleTexture = val;
  55190. },
  55191. enumerable: true,
  55192. configurable: true
  55193. });
  55194. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  55195. /**
  55196. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  55197. * Default value : false. The SPS is faster when it's set to false.
  55198. * Note : the particle custom vertex positions aren't stored values.
  55199. */
  55200. get: function () {
  55201. return this._computeParticleVertex;
  55202. },
  55203. /**
  55204. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  55205. * Default value : false. The SPS is faster when it's set to false.
  55206. * Note : the particle custom vertex positions aren't stored values.
  55207. */
  55208. set: function (val) {
  55209. this._computeParticleVertex = val;
  55210. },
  55211. enumerable: true,
  55212. configurable: true
  55213. });
  55214. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  55215. /**
  55216. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  55217. */
  55218. get: function () {
  55219. return this._computeBoundingBox;
  55220. },
  55221. /**
  55222. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  55223. */
  55224. set: function (val) {
  55225. this._computeBoundingBox = val;
  55226. },
  55227. enumerable: true,
  55228. configurable: true
  55229. });
  55230. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  55231. /**
  55232. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  55233. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55234. * Default : `true`
  55235. */
  55236. get: function () {
  55237. return this._depthSortParticles;
  55238. },
  55239. /**
  55240. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  55241. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55242. * Default : `true`
  55243. */
  55244. set: function (val) {
  55245. this._depthSortParticles = val;
  55246. },
  55247. enumerable: true,
  55248. configurable: true
  55249. });
  55250. // =======================================================================
  55251. // Particle behavior logic
  55252. // these following methods may be overwritten by the user to fit his needs
  55253. /**
  55254. * This function does nothing. It may be overwritten to set all the particle first values.
  55255. * The SPS doesn't call this function, you may have to call it by your own.
  55256. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55257. */
  55258. SolidParticleSystem.prototype.initParticles = function () {
  55259. };
  55260. /**
  55261. * This function does nothing. It may be overwritten to recycle a particle.
  55262. * The SPS doesn't call this function, you may have to call it by your own.
  55263. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55264. * @param particle The particle to recycle
  55265. * @returns the recycled particle
  55266. */
  55267. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  55268. return particle;
  55269. };
  55270. /**
  55271. * Updates a particle : this function should be overwritten by the user.
  55272. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  55273. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55274. * @example : just set a particle position or velocity and recycle conditions
  55275. * @param particle The particle to update
  55276. * @returns the updated particle
  55277. */
  55278. SolidParticleSystem.prototype.updateParticle = function (particle) {
  55279. return particle;
  55280. };
  55281. /**
  55282. * Updates a vertex of a particle : it can be overwritten by the user.
  55283. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  55284. * @param particle the current particle
  55285. * @param vertex the current index of the current particle
  55286. * @param pt the index of the current vertex in the particle shape
  55287. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  55288. * @example : just set a vertex particle position
  55289. * @returns the updated vertex
  55290. */
  55291. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  55292. return vertex;
  55293. };
  55294. /**
  55295. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  55296. * This does nothing and may be overwritten by the user.
  55297. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55298. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55299. * @param update the boolean update value actually passed to setParticles()
  55300. */
  55301. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  55302. };
  55303. /**
  55304. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  55305. * This will be passed three parameters.
  55306. * This does nothing and may be overwritten by the user.
  55307. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55308. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55309. * @param update the boolean update value actually passed to setParticles()
  55310. */
  55311. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  55312. };
  55313. return SolidParticleSystem;
  55314. }());
  55315. BABYLON.SolidParticleSystem = SolidParticleSystem;
  55316. })(BABYLON || (BABYLON = {}));
  55317. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  55318. "use strict";
  55319. var BABYLON;
  55320. (function (BABYLON) {
  55321. var ShaderMaterial = /** @class */ (function (_super) {
  55322. __extends(ShaderMaterial, _super);
  55323. function ShaderMaterial(name, scene, shaderPath, options) {
  55324. var _this = _super.call(this, name, scene) || this;
  55325. _this._textures = {};
  55326. _this._textureArrays = {};
  55327. _this._floats = {};
  55328. _this._ints = {};
  55329. _this._floatsArrays = {};
  55330. _this._colors3 = {};
  55331. _this._colors3Arrays = {};
  55332. _this._colors4 = {};
  55333. _this._vectors2 = {};
  55334. _this._vectors3 = {};
  55335. _this._vectors4 = {};
  55336. _this._matrices = {};
  55337. _this._matrices3x3 = {};
  55338. _this._matrices2x2 = {};
  55339. _this._vectors2Arrays = {};
  55340. _this._vectors3Arrays = {};
  55341. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  55342. _this._shaderPath = shaderPath;
  55343. options.needAlphaBlending = options.needAlphaBlending || false;
  55344. options.needAlphaTesting = options.needAlphaTesting || false;
  55345. options.attributes = options.attributes || ["position", "normal", "uv"];
  55346. options.uniforms = options.uniforms || ["worldViewProjection"];
  55347. options.uniformBuffers = options.uniformBuffers || [];
  55348. options.samplers = options.samplers || [];
  55349. options.defines = options.defines || [];
  55350. _this._options = options;
  55351. return _this;
  55352. }
  55353. ShaderMaterial.prototype.getClassName = function () {
  55354. return "ShaderMaterial";
  55355. };
  55356. ShaderMaterial.prototype.needAlphaBlending = function () {
  55357. return this._options.needAlphaBlending;
  55358. };
  55359. ShaderMaterial.prototype.needAlphaTesting = function () {
  55360. return this._options.needAlphaTesting;
  55361. };
  55362. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  55363. if (this._options.uniforms.indexOf(uniformName) === -1) {
  55364. this._options.uniforms.push(uniformName);
  55365. }
  55366. };
  55367. ShaderMaterial.prototype.setTexture = function (name, texture) {
  55368. if (this._options.samplers.indexOf(name) === -1) {
  55369. this._options.samplers.push(name);
  55370. }
  55371. this._textures[name] = texture;
  55372. return this;
  55373. };
  55374. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  55375. if (this._options.samplers.indexOf(name) === -1) {
  55376. this._options.samplers.push(name);
  55377. }
  55378. this._checkUniform(name);
  55379. this._textureArrays[name] = textures;
  55380. return this;
  55381. };
  55382. ShaderMaterial.prototype.setFloat = function (name, value) {
  55383. this._checkUniform(name);
  55384. this._floats[name] = value;
  55385. return this;
  55386. };
  55387. ShaderMaterial.prototype.setInt = function (name, value) {
  55388. this._checkUniform(name);
  55389. this._ints[name] = value;
  55390. return this;
  55391. };
  55392. ShaderMaterial.prototype.setFloats = function (name, value) {
  55393. this._checkUniform(name);
  55394. this._floatsArrays[name] = value;
  55395. return this;
  55396. };
  55397. ShaderMaterial.prototype.setColor3 = function (name, value) {
  55398. this._checkUniform(name);
  55399. this._colors3[name] = value;
  55400. return this;
  55401. };
  55402. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  55403. this._checkUniform(name);
  55404. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  55405. color.toArray(arr, arr.length);
  55406. return arr;
  55407. }, []);
  55408. return this;
  55409. };
  55410. ShaderMaterial.prototype.setColor4 = function (name, value) {
  55411. this._checkUniform(name);
  55412. this._colors4[name] = value;
  55413. return this;
  55414. };
  55415. ShaderMaterial.prototype.setVector2 = function (name, value) {
  55416. this._checkUniform(name);
  55417. this._vectors2[name] = value;
  55418. return this;
  55419. };
  55420. ShaderMaterial.prototype.setVector3 = function (name, value) {
  55421. this._checkUniform(name);
  55422. this._vectors3[name] = value;
  55423. return this;
  55424. };
  55425. ShaderMaterial.prototype.setVector4 = function (name, value) {
  55426. this._checkUniform(name);
  55427. this._vectors4[name] = value;
  55428. return this;
  55429. };
  55430. ShaderMaterial.prototype.setMatrix = function (name, value) {
  55431. this._checkUniform(name);
  55432. this._matrices[name] = value;
  55433. return this;
  55434. };
  55435. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  55436. this._checkUniform(name);
  55437. this._matrices3x3[name] = value;
  55438. return this;
  55439. };
  55440. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  55441. this._checkUniform(name);
  55442. this._matrices2x2[name] = value;
  55443. return this;
  55444. };
  55445. ShaderMaterial.prototype.setArray2 = function (name, value) {
  55446. this._checkUniform(name);
  55447. this._vectors2Arrays[name] = value;
  55448. return this;
  55449. };
  55450. ShaderMaterial.prototype.setArray3 = function (name, value) {
  55451. this._checkUniform(name);
  55452. this._vectors3Arrays[name] = value;
  55453. return this;
  55454. };
  55455. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  55456. if (!mesh) {
  55457. return true;
  55458. }
  55459. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  55460. return false;
  55461. }
  55462. return false;
  55463. };
  55464. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  55465. var scene = this.getScene();
  55466. var engine = scene.getEngine();
  55467. if (!this.checkReadyOnEveryCall) {
  55468. if (this._renderId === scene.getRenderId()) {
  55469. if (this._checkCache(scene, mesh, useInstances)) {
  55470. return true;
  55471. }
  55472. }
  55473. }
  55474. // Instances
  55475. var defines = [];
  55476. var attribs = [];
  55477. var fallbacks = new BABYLON.EffectFallbacks();
  55478. if (useInstances) {
  55479. defines.push("#define INSTANCES");
  55480. }
  55481. for (var index = 0; index < this._options.defines.length; index++) {
  55482. defines.push(this._options.defines[index]);
  55483. }
  55484. for (var index = 0; index < this._options.attributes.length; index++) {
  55485. attribs.push(this._options.attributes[index]);
  55486. }
  55487. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  55488. attribs.push(BABYLON.VertexBuffer.ColorKind);
  55489. defines.push("#define VERTEXCOLOR");
  55490. }
  55491. // Bones
  55492. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  55493. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55494. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55495. if (mesh.numBoneInfluencers > 4) {
  55496. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55497. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55498. }
  55499. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55500. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55501. fallbacks.addCPUSkinningFallback(0, mesh);
  55502. if (this._options.uniforms.indexOf("mBones") === -1) {
  55503. this._options.uniforms.push("mBones");
  55504. }
  55505. }
  55506. else {
  55507. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55508. }
  55509. // Textures
  55510. for (var name in this._textures) {
  55511. if (!this._textures[name].isReady()) {
  55512. return false;
  55513. }
  55514. }
  55515. // Alpha test
  55516. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  55517. defines.push("#define ALPHATEST");
  55518. }
  55519. var previousEffect = this._effect;
  55520. var join = defines.join("\n");
  55521. this._effect = engine.createEffect(this._shaderPath, {
  55522. attributes: attribs,
  55523. uniformsNames: this._options.uniforms,
  55524. uniformBuffersNames: this._options.uniformBuffers,
  55525. samplers: this._options.samplers,
  55526. defines: join,
  55527. fallbacks: fallbacks,
  55528. onCompiled: this.onCompiled,
  55529. onError: this.onError
  55530. }, engine);
  55531. if (!this._effect.isReady()) {
  55532. return false;
  55533. }
  55534. if (previousEffect !== this._effect) {
  55535. scene.resetCachedMaterial();
  55536. }
  55537. this._renderId = scene.getRenderId();
  55538. return true;
  55539. };
  55540. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  55541. var scene = this.getScene();
  55542. if (!this._effect) {
  55543. return;
  55544. }
  55545. if (this._options.uniforms.indexOf("world") !== -1) {
  55546. this._effect.setMatrix("world", world);
  55547. }
  55548. if (this._options.uniforms.indexOf("worldView") !== -1) {
  55549. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  55550. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  55551. }
  55552. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  55553. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  55554. }
  55555. };
  55556. ShaderMaterial.prototype.bind = function (world, mesh) {
  55557. // Std values
  55558. this.bindOnlyWorldMatrix(world);
  55559. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  55560. if (this._options.uniforms.indexOf("view") !== -1) {
  55561. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  55562. }
  55563. if (this._options.uniforms.indexOf("projection") !== -1) {
  55564. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  55565. }
  55566. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  55567. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  55568. }
  55569. // Bones
  55570. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  55571. var name;
  55572. // Texture
  55573. for (name in this._textures) {
  55574. this._effect.setTexture(name, this._textures[name]);
  55575. }
  55576. // Texture arrays
  55577. for (name in this._textureArrays) {
  55578. this._effect.setTextureArray(name, this._textureArrays[name]);
  55579. }
  55580. // Int
  55581. for (name in this._ints) {
  55582. this._effect.setInt(name, this._ints[name]);
  55583. }
  55584. // Float
  55585. for (name in this._floats) {
  55586. this._effect.setFloat(name, this._floats[name]);
  55587. }
  55588. // Floats
  55589. for (name in this._floatsArrays) {
  55590. this._effect.setArray(name, this._floatsArrays[name]);
  55591. }
  55592. // Color3
  55593. for (name in this._colors3) {
  55594. this._effect.setColor3(name, this._colors3[name]);
  55595. }
  55596. for (name in this._colors3Arrays) {
  55597. this._effect.setArray3(name, this._colors3Arrays[name]);
  55598. }
  55599. // Color4
  55600. for (name in this._colors4) {
  55601. var color = this._colors4[name];
  55602. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55603. }
  55604. // Vector2
  55605. for (name in this._vectors2) {
  55606. this._effect.setVector2(name, this._vectors2[name]);
  55607. }
  55608. // Vector3
  55609. for (name in this._vectors3) {
  55610. this._effect.setVector3(name, this._vectors3[name]);
  55611. }
  55612. // Vector4
  55613. for (name in this._vectors4) {
  55614. this._effect.setVector4(name, this._vectors4[name]);
  55615. }
  55616. // Matrix
  55617. for (name in this._matrices) {
  55618. this._effect.setMatrix(name, this._matrices[name]);
  55619. }
  55620. // Matrix 3x3
  55621. for (name in this._matrices3x3) {
  55622. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  55623. }
  55624. // Matrix 2x2
  55625. for (name in this._matrices2x2) {
  55626. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  55627. }
  55628. // Vector2Array
  55629. for (name in this._vectors2Arrays) {
  55630. this._effect.setArray2(name, this._vectors2Arrays[name]);
  55631. }
  55632. // Vector3Array
  55633. for (name in this._vectors3Arrays) {
  55634. this._effect.setArray3(name, this._vectors3Arrays[name]);
  55635. }
  55636. }
  55637. this._afterBind(mesh);
  55638. };
  55639. ShaderMaterial.prototype.getActiveTextures = function () {
  55640. var activeTextures = _super.prototype.getActiveTextures.call(this);
  55641. for (var name in this._textures) {
  55642. activeTextures.push(this._textures[name]);
  55643. }
  55644. for (var name in this._textureArrays) {
  55645. var array = this._textureArrays[name];
  55646. for (var index = 0; index < array.length; index++) {
  55647. activeTextures.push(array[index]);
  55648. }
  55649. }
  55650. return activeTextures;
  55651. };
  55652. ShaderMaterial.prototype.hasTexture = function (texture) {
  55653. if (_super.prototype.hasTexture.call(this, texture)) {
  55654. return true;
  55655. }
  55656. for (var name in this._textures) {
  55657. if (this._textures[name] === texture) {
  55658. return true;
  55659. }
  55660. }
  55661. for (var name in this._textureArrays) {
  55662. var array = this._textureArrays[name];
  55663. for (var index = 0; index < array.length; index++) {
  55664. if (array[index] === texture) {
  55665. return true;
  55666. }
  55667. }
  55668. }
  55669. return false;
  55670. };
  55671. ShaderMaterial.prototype.clone = function (name) {
  55672. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  55673. return newShaderMaterial;
  55674. };
  55675. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55676. if (forceDisposeTextures) {
  55677. var name;
  55678. for (name in this._textures) {
  55679. this._textures[name].dispose();
  55680. }
  55681. for (name in this._textureArrays) {
  55682. var array = this._textureArrays[name];
  55683. for (var index = 0; index < array.length; index++) {
  55684. array[index].dispose();
  55685. }
  55686. }
  55687. }
  55688. this._textures = {};
  55689. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55690. };
  55691. ShaderMaterial.prototype.serialize = function () {
  55692. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55693. serializationObject.customType = "BABYLON.ShaderMaterial";
  55694. serializationObject.options = this._options;
  55695. serializationObject.shaderPath = this._shaderPath;
  55696. var name;
  55697. // Texture
  55698. serializationObject.textures = {};
  55699. for (name in this._textures) {
  55700. serializationObject.textures[name] = this._textures[name].serialize();
  55701. }
  55702. // Texture arrays
  55703. serializationObject.textureArrays = {};
  55704. for (name in this._textureArrays) {
  55705. serializationObject.textureArrays[name] = [];
  55706. var array = this._textureArrays[name];
  55707. for (var index = 0; index < array.length; index++) {
  55708. serializationObject.textureArrays[name].push(array[index].serialize());
  55709. }
  55710. }
  55711. // Float
  55712. serializationObject.floats = {};
  55713. for (name in this._floats) {
  55714. serializationObject.floats[name] = this._floats[name];
  55715. }
  55716. // Float s
  55717. serializationObject.FloatArrays = {};
  55718. for (name in this._floatsArrays) {
  55719. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  55720. }
  55721. // Color3
  55722. serializationObject.colors3 = {};
  55723. for (name in this._colors3) {
  55724. serializationObject.colors3[name] = this._colors3[name].asArray();
  55725. }
  55726. // Color3 array
  55727. serializationObject.colors3Arrays = {};
  55728. for (name in this._colors3Arrays) {
  55729. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  55730. }
  55731. // Color4
  55732. serializationObject.colors4 = {};
  55733. for (name in this._colors4) {
  55734. serializationObject.colors4[name] = this._colors4[name].asArray();
  55735. }
  55736. // Vector2
  55737. serializationObject.vectors2 = {};
  55738. for (name in this._vectors2) {
  55739. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  55740. }
  55741. // Vector3
  55742. serializationObject.vectors3 = {};
  55743. for (name in this._vectors3) {
  55744. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  55745. }
  55746. // Vector4
  55747. serializationObject.vectors4 = {};
  55748. for (name in this._vectors4) {
  55749. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  55750. }
  55751. // Matrix
  55752. serializationObject.matrices = {};
  55753. for (name in this._matrices) {
  55754. serializationObject.matrices[name] = this._matrices[name].asArray();
  55755. }
  55756. // Matrix 3x3
  55757. serializationObject.matrices3x3 = {};
  55758. for (name in this._matrices3x3) {
  55759. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  55760. }
  55761. // Matrix 2x2
  55762. serializationObject.matrices2x2 = {};
  55763. for (name in this._matrices2x2) {
  55764. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  55765. }
  55766. // Vector2Array
  55767. serializationObject.vectors2Arrays = {};
  55768. for (name in this._vectors2Arrays) {
  55769. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  55770. }
  55771. // Vector3Array
  55772. serializationObject.vectors3Arrays = {};
  55773. for (name in this._vectors3Arrays) {
  55774. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  55775. }
  55776. return serializationObject;
  55777. };
  55778. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  55779. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  55780. var name;
  55781. // Texture
  55782. for (name in source.textures) {
  55783. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  55784. }
  55785. // Texture arrays
  55786. for (name in source.textureArrays) {
  55787. var array = source.textureArrays[name];
  55788. var textureArray = new Array();
  55789. for (var index = 0; index < array.length; index++) {
  55790. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  55791. }
  55792. material.setTextureArray(name, textureArray);
  55793. }
  55794. // Float
  55795. for (name in source.floats) {
  55796. material.setFloat(name, source.floats[name]);
  55797. }
  55798. // Float s
  55799. for (name in source.floatsArrays) {
  55800. material.setFloats(name, source.floatsArrays[name]);
  55801. }
  55802. // Color3
  55803. for (name in source.colors3) {
  55804. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  55805. }
  55806. // Color3 arrays
  55807. for (name in source.colors3Arrays) {
  55808. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  55809. if (i % 3 === 0) {
  55810. arr.push([num]);
  55811. }
  55812. else {
  55813. arr[arr.length - 1].push(num);
  55814. }
  55815. return arr;
  55816. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  55817. material.setColor3Array(name, colors);
  55818. }
  55819. // Color4
  55820. for (name in source.colors4) {
  55821. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  55822. }
  55823. // Vector2
  55824. for (name in source.vectors2) {
  55825. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  55826. }
  55827. // Vector3
  55828. for (name in source.vectors3) {
  55829. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  55830. }
  55831. // Vector4
  55832. for (name in source.vectors4) {
  55833. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  55834. }
  55835. // Matrix
  55836. for (name in source.matrices) {
  55837. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  55838. }
  55839. // Matrix 3x3
  55840. for (name in source.matrices3x3) {
  55841. material.setMatrix3x3(name, source.matrices3x3[name]);
  55842. }
  55843. // Matrix 2x2
  55844. for (name in source.matrices2x2) {
  55845. material.setMatrix2x2(name, source.matrices2x2[name]);
  55846. }
  55847. // Vector2Array
  55848. for (name in source.vectors2Arrays) {
  55849. material.setArray2(name, source.vectors2Arrays[name]);
  55850. }
  55851. // Vector3Array
  55852. for (name in source.vectors3Arrays) {
  55853. material.setArray3(name, source.vectors3Arrays[name]);
  55854. }
  55855. return material;
  55856. };
  55857. return ShaderMaterial;
  55858. }(BABYLON.Material));
  55859. BABYLON.ShaderMaterial = ShaderMaterial;
  55860. })(BABYLON || (BABYLON = {}));
  55861. //# sourceMappingURL=babylon.shaderMaterial.js.map
  55862. "use strict";
  55863. var BABYLON;
  55864. (function (BABYLON) {
  55865. var GroundMesh = /** @class */ (function (_super) {
  55866. __extends(GroundMesh, _super);
  55867. function GroundMesh(name, scene) {
  55868. var _this = _super.call(this, name, scene) || this;
  55869. _this.generateOctree = false;
  55870. return _this;
  55871. }
  55872. GroundMesh.prototype.getClassName = function () {
  55873. return "GroundMesh";
  55874. };
  55875. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  55876. get: function () {
  55877. return Math.min(this._subdivisionsX, this._subdivisionsY);
  55878. },
  55879. enumerable: true,
  55880. configurable: true
  55881. });
  55882. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  55883. get: function () {
  55884. return this._subdivisionsX;
  55885. },
  55886. enumerable: true,
  55887. configurable: true
  55888. });
  55889. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  55890. get: function () {
  55891. return this._subdivisionsY;
  55892. },
  55893. enumerable: true,
  55894. configurable: true
  55895. });
  55896. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  55897. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  55898. this._subdivisionsX = chunksCount;
  55899. this._subdivisionsY = chunksCount;
  55900. this.subdivide(chunksCount);
  55901. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  55902. };
  55903. /**
  55904. * Returns a height (y) value in the Worl system :
  55905. * the ground altitude at the coordinates (x, z) expressed in the World system.
  55906. * Returns the ground y position if (x, z) are outside the ground surface.
  55907. */
  55908. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  55909. var world = this.getWorldMatrix();
  55910. var invMat = BABYLON.Tmp.Matrix[5];
  55911. world.invertToRef(invMat);
  55912. var tmpVect = BABYLON.Tmp.Vector3[8];
  55913. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  55914. x = tmpVect.x;
  55915. z = tmpVect.z;
  55916. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55917. return this.position.y;
  55918. }
  55919. if (!this._heightQuads || this._heightQuads.length == 0) {
  55920. this._initHeightQuads();
  55921. this._computeHeightQuads();
  55922. }
  55923. var facet = this._getFacetAt(x, z);
  55924. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  55925. // return y in the World system
  55926. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  55927. return tmpVect.y;
  55928. };
  55929. /**
  55930. * Returns a normalized vector (Vector3) orthogonal to the ground
  55931. * at the ground coordinates (x, z) expressed in the World system.
  55932. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  55933. */
  55934. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  55935. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  55936. this.getNormalAtCoordinatesToRef(x, z, normal);
  55937. return normal;
  55938. };
  55939. /**
  55940. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  55941. * at the ground coordinates (x, z) expressed in the World system.
  55942. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  55943. * Returns the GroundMesh.
  55944. */
  55945. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  55946. var world = this.getWorldMatrix();
  55947. var tmpMat = BABYLON.Tmp.Matrix[5];
  55948. world.invertToRef(tmpMat);
  55949. var tmpVect = BABYLON.Tmp.Vector3[8];
  55950. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  55951. x = tmpVect.x;
  55952. z = tmpVect.z;
  55953. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55954. return this;
  55955. }
  55956. if (!this._heightQuads || this._heightQuads.length == 0) {
  55957. this._initHeightQuads();
  55958. this._computeHeightQuads();
  55959. }
  55960. var facet = this._getFacetAt(x, z);
  55961. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55962. return this;
  55963. };
  55964. /**
  55965. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55966. * if the ground has been updated.
  55967. * This can be used in the render loop.
  55968. * Returns the GroundMesh.
  55969. */
  55970. GroundMesh.prototype.updateCoordinateHeights = function () {
  55971. if (!this._heightQuads || this._heightQuads.length == 0) {
  55972. this._initHeightQuads();
  55973. }
  55974. this._computeHeightQuads();
  55975. return this;
  55976. };
  55977. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55978. GroundMesh.prototype._getFacetAt = function (x, z) {
  55979. // retrieve col and row from x, z coordinates in the ground local system
  55980. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55981. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55982. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55983. var facet;
  55984. if (z < quad.slope.x * x + quad.slope.y) {
  55985. facet = quad.facet1;
  55986. }
  55987. else {
  55988. facet = quad.facet2;
  55989. }
  55990. return facet;
  55991. };
  55992. // Creates and populates the heightMap array with "facet" elements :
  55993. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55994. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55995. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55996. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55997. // Returns the GroundMesh.
  55998. GroundMesh.prototype._initHeightQuads = function () {
  55999. var subdivisionsX = this._subdivisionsX;
  56000. var subdivisionsY = this._subdivisionsY;
  56001. this._heightQuads = new Array();
  56002. for (var row = 0; row < subdivisionsY; row++) {
  56003. for (var col = 0; col < subdivisionsX; col++) {
  56004. 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) };
  56005. this._heightQuads[row * subdivisionsX + col] = quad;
  56006. }
  56007. }
  56008. return this;
  56009. };
  56010. // Compute each quad element values and update the the heightMap array :
  56011. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  56012. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  56013. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  56014. // Returns the GroundMesh.
  56015. GroundMesh.prototype._computeHeightQuads = function () {
  56016. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56017. if (!positions) {
  56018. return this;
  56019. }
  56020. var v1 = BABYLON.Tmp.Vector3[3];
  56021. var v2 = BABYLON.Tmp.Vector3[2];
  56022. var v3 = BABYLON.Tmp.Vector3[1];
  56023. var v4 = BABYLON.Tmp.Vector3[0];
  56024. var v1v2 = BABYLON.Tmp.Vector3[4];
  56025. var v1v3 = BABYLON.Tmp.Vector3[5];
  56026. var v1v4 = BABYLON.Tmp.Vector3[6];
  56027. var norm1 = BABYLON.Tmp.Vector3[7];
  56028. var norm2 = BABYLON.Tmp.Vector3[8];
  56029. var i = 0;
  56030. var j = 0;
  56031. var k = 0;
  56032. var cd = 0; // 2D slope coefficient : z = cd * x + h
  56033. var h = 0;
  56034. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  56035. var d2 = 0;
  56036. var subdivisionsX = this._subdivisionsX;
  56037. var subdivisionsY = this._subdivisionsY;
  56038. for (var row = 0; row < subdivisionsY; row++) {
  56039. for (var col = 0; col < subdivisionsX; col++) {
  56040. i = col * 3;
  56041. j = row * (subdivisionsX + 1) * 3;
  56042. k = (row + 1) * (subdivisionsX + 1) * 3;
  56043. v1.x = positions[j + i];
  56044. v1.y = positions[j + i + 1];
  56045. v1.z = positions[j + i + 2];
  56046. v2.x = positions[j + i + 3];
  56047. v2.y = positions[j + i + 4];
  56048. v2.z = positions[j + i + 5];
  56049. v3.x = positions[k + i];
  56050. v3.y = positions[k + i + 1];
  56051. v3.z = positions[k + i + 2];
  56052. v4.x = positions[k + i + 3];
  56053. v4.y = positions[k + i + 4];
  56054. v4.z = positions[k + i + 5];
  56055. // 2D slope V1V4
  56056. cd = (v4.z - v1.z) / (v4.x - v1.x);
  56057. h = v1.z - cd * v1.x; // v1 belongs to the slope
  56058. // facet equations :
  56059. // we compute each facet normal vector
  56060. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  56061. // we compute the value d by applying the equation to v1 which belongs to the plane
  56062. // then we store the facet equation in a Vector4
  56063. v2.subtractToRef(v1, v1v2);
  56064. v3.subtractToRef(v1, v1v3);
  56065. v4.subtractToRef(v1, v1v4);
  56066. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  56067. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  56068. norm1.normalize();
  56069. norm2.normalize();
  56070. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  56071. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  56072. var quad = this._heightQuads[row * subdivisionsX + col];
  56073. quad.slope.copyFromFloats(cd, h);
  56074. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  56075. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  56076. }
  56077. }
  56078. return this;
  56079. };
  56080. GroundMesh.prototype.serialize = function (serializationObject) {
  56081. _super.prototype.serialize.call(this, serializationObject);
  56082. serializationObject.subdivisionsX = this._subdivisionsX;
  56083. serializationObject.subdivisionsY = this._subdivisionsY;
  56084. serializationObject.minX = this._minX;
  56085. serializationObject.maxX = this._maxX;
  56086. serializationObject.minZ = this._minZ;
  56087. serializationObject.maxZ = this._maxZ;
  56088. serializationObject.width = this._width;
  56089. serializationObject.height = this._height;
  56090. };
  56091. GroundMesh.Parse = function (parsedMesh, scene) {
  56092. var result = new GroundMesh(parsedMesh.name, scene);
  56093. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  56094. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  56095. result._minX = parsedMesh.minX;
  56096. result._maxX = parsedMesh.maxX;
  56097. result._minZ = parsedMesh.minZ;
  56098. result._maxZ = parsedMesh.maxZ;
  56099. result._width = parsedMesh.width;
  56100. result._height = parsedMesh.height;
  56101. return result;
  56102. };
  56103. return GroundMesh;
  56104. }(BABYLON.Mesh));
  56105. BABYLON.GroundMesh = GroundMesh;
  56106. })(BABYLON || (BABYLON = {}));
  56107. //# sourceMappingURL=babylon.groundMesh.js.map
  56108. "use strict";
  56109. var BABYLON;
  56110. (function (BABYLON) {
  56111. /**
  56112. * Creates an instance based on a source mesh.
  56113. */
  56114. var InstancedMesh = /** @class */ (function (_super) {
  56115. __extends(InstancedMesh, _super);
  56116. function InstancedMesh(name, source) {
  56117. var _this = _super.call(this, name, source.getScene()) || this;
  56118. source.instances.push(_this);
  56119. _this._sourceMesh = source;
  56120. _this.position.copyFrom(source.position);
  56121. _this.rotation.copyFrom(source.rotation);
  56122. _this.scaling.copyFrom(source.scaling);
  56123. if (source.rotationQuaternion) {
  56124. _this.rotationQuaternion = source.rotationQuaternion.clone();
  56125. }
  56126. _this.infiniteDistance = source.infiniteDistance;
  56127. _this.setPivotMatrix(source.getPivotMatrix());
  56128. _this.refreshBoundingInfo();
  56129. _this._syncSubMeshes();
  56130. return _this;
  56131. }
  56132. /**
  56133. * Returns the string "InstancedMesh".
  56134. */
  56135. InstancedMesh.prototype.getClassName = function () {
  56136. return "InstancedMesh";
  56137. };
  56138. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  56139. // Methods
  56140. get: function () {
  56141. return this._sourceMesh.receiveShadows;
  56142. },
  56143. enumerable: true,
  56144. configurable: true
  56145. });
  56146. Object.defineProperty(InstancedMesh.prototype, "material", {
  56147. get: function () {
  56148. return this._sourceMesh.material;
  56149. },
  56150. enumerable: true,
  56151. configurable: true
  56152. });
  56153. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  56154. get: function () {
  56155. return this._sourceMesh.visibility;
  56156. },
  56157. enumerable: true,
  56158. configurable: true
  56159. });
  56160. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  56161. get: function () {
  56162. return this._sourceMesh.skeleton;
  56163. },
  56164. enumerable: true,
  56165. configurable: true
  56166. });
  56167. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  56168. get: function () {
  56169. return this._sourceMesh.renderingGroupId;
  56170. },
  56171. set: function (value) {
  56172. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  56173. return;
  56174. }
  56175. //no-op with warning
  56176. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  56177. },
  56178. enumerable: true,
  56179. configurable: true
  56180. });
  56181. /**
  56182. * Returns the total number of vertices (integer).
  56183. */
  56184. InstancedMesh.prototype.getTotalVertices = function () {
  56185. return this._sourceMesh.getTotalVertices();
  56186. };
  56187. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  56188. get: function () {
  56189. return this._sourceMesh;
  56190. },
  56191. enumerable: true,
  56192. configurable: true
  56193. });
  56194. /**
  56195. * Is this node ready to be used/rendered
  56196. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  56197. * @return {boolean} is it ready
  56198. */
  56199. InstancedMesh.prototype.isReady = function (completeCheck) {
  56200. if (completeCheck === void 0) { completeCheck = false; }
  56201. return this._sourceMesh.isReady(completeCheck, true);
  56202. };
  56203. /**
  56204. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  56205. */
  56206. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  56207. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  56208. };
  56209. /**
  56210. * Sets the vertex data of the mesh geometry for the requested `kind`.
  56211. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  56212. * The `data` are either a numeric array either a Float32Array.
  56213. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  56214. * 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).
  56215. * Note that a new underlying VertexBuffer object is created each call.
  56216. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  56217. *
  56218. * Possible `kind` values :
  56219. * - BABYLON.VertexBuffer.PositionKind
  56220. * - BABYLON.VertexBuffer.UVKind
  56221. * - BABYLON.VertexBuffer.UV2Kind
  56222. * - BABYLON.VertexBuffer.UV3Kind
  56223. * - BABYLON.VertexBuffer.UV4Kind
  56224. * - BABYLON.VertexBuffer.UV5Kind
  56225. * - BABYLON.VertexBuffer.UV6Kind
  56226. * - BABYLON.VertexBuffer.ColorKind
  56227. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56228. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56229. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56230. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56231. *
  56232. * Returns the Mesh.
  56233. */
  56234. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  56235. if (this.sourceMesh) {
  56236. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  56237. }
  56238. return this.sourceMesh;
  56239. };
  56240. /**
  56241. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  56242. * If the mesh has no geometry, it is simply returned as it is.
  56243. * The `data` are either a numeric array either a Float32Array.
  56244. * No new underlying VertexBuffer object is created.
  56245. * 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.
  56246. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  56247. *
  56248. * Possible `kind` values :
  56249. * - BABYLON.VertexBuffer.PositionKind
  56250. * - BABYLON.VertexBuffer.UVKind
  56251. * - BABYLON.VertexBuffer.UV2Kind
  56252. * - BABYLON.VertexBuffer.UV3Kind
  56253. * - BABYLON.VertexBuffer.UV4Kind
  56254. * - BABYLON.VertexBuffer.UV5Kind
  56255. * - BABYLON.VertexBuffer.UV6Kind
  56256. * - BABYLON.VertexBuffer.ColorKind
  56257. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56258. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56259. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56260. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56261. *
  56262. * Returns the Mesh.
  56263. */
  56264. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  56265. if (this.sourceMesh) {
  56266. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  56267. }
  56268. return this.sourceMesh;
  56269. };
  56270. /**
  56271. * Sets the mesh indices.
  56272. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  56273. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  56274. * This method creates a new index buffer each call.
  56275. * Returns the Mesh.
  56276. */
  56277. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  56278. if (totalVertices === void 0) { totalVertices = null; }
  56279. if (this.sourceMesh) {
  56280. this.sourceMesh.setIndices(indices, totalVertices);
  56281. }
  56282. return this.sourceMesh;
  56283. };
  56284. /**
  56285. * Boolean : True if the mesh owns the requested kind of data.
  56286. */
  56287. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  56288. return this._sourceMesh.isVerticesDataPresent(kind);
  56289. };
  56290. /**
  56291. * Returns an array of indices (IndicesArray).
  56292. */
  56293. InstancedMesh.prototype.getIndices = function () {
  56294. return this._sourceMesh.getIndices();
  56295. };
  56296. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  56297. get: function () {
  56298. return this._sourceMesh._positions;
  56299. },
  56300. enumerable: true,
  56301. configurable: true
  56302. });
  56303. /**
  56304. * Sets a new updated BoundingInfo to the mesh.
  56305. * Returns the mesh.
  56306. */
  56307. InstancedMesh.prototype.refreshBoundingInfo = function () {
  56308. var meshBB = this._sourceMesh.getBoundingInfo();
  56309. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  56310. this._updateBoundingInfo();
  56311. return this;
  56312. };
  56313. InstancedMesh.prototype._preActivate = function () {
  56314. if (this._currentLOD) {
  56315. this._currentLOD._preActivate();
  56316. }
  56317. return this;
  56318. };
  56319. InstancedMesh.prototype._activate = function (renderId) {
  56320. if (this._currentLOD) {
  56321. this._currentLOD._registerInstanceForRenderId(this, renderId);
  56322. }
  56323. return this;
  56324. };
  56325. /**
  56326. * Returns the current associated LOD AbstractMesh.
  56327. */
  56328. InstancedMesh.prototype.getLOD = function (camera) {
  56329. if (!camera) {
  56330. return this;
  56331. }
  56332. var boundingInfo = this.getBoundingInfo();
  56333. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  56334. if (this._currentLOD === this.sourceMesh) {
  56335. return this;
  56336. }
  56337. return this._currentLOD;
  56338. };
  56339. InstancedMesh.prototype._syncSubMeshes = function () {
  56340. this.releaseSubMeshes();
  56341. if (this._sourceMesh.subMeshes) {
  56342. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  56343. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  56344. }
  56345. }
  56346. return this;
  56347. };
  56348. InstancedMesh.prototype._generatePointsArray = function () {
  56349. return this._sourceMesh._generatePointsArray();
  56350. };
  56351. /**
  56352. * Creates a new InstancedMesh from the current mesh.
  56353. * - name (string) : the cloned mesh name
  56354. * - newParent (optional Node) : the optional Node to parent the clone to.
  56355. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  56356. *
  56357. * Returns the clone.
  56358. */
  56359. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56360. var result = this._sourceMesh.createInstance(name);
  56361. // Deep copy
  56362. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  56363. // Bounding info
  56364. this.refreshBoundingInfo();
  56365. // Parent
  56366. if (newParent) {
  56367. result.parent = newParent;
  56368. }
  56369. if (!doNotCloneChildren) {
  56370. // Children
  56371. for (var index = 0; index < this.getScene().meshes.length; index++) {
  56372. var mesh = this.getScene().meshes[index];
  56373. if (mesh.parent === this) {
  56374. mesh.clone(mesh.name, result);
  56375. }
  56376. }
  56377. }
  56378. result.computeWorldMatrix(true);
  56379. return result;
  56380. };
  56381. /**
  56382. * Disposes the InstancedMesh.
  56383. * Returns nothing.
  56384. */
  56385. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  56386. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  56387. // Remove from mesh
  56388. var index = this._sourceMesh.instances.indexOf(this);
  56389. this._sourceMesh.instances.splice(index, 1);
  56390. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  56391. };
  56392. return InstancedMesh;
  56393. }(BABYLON.AbstractMesh));
  56394. BABYLON.InstancedMesh = InstancedMesh;
  56395. })(BABYLON || (BABYLON = {}));
  56396. //# sourceMappingURL=babylon.instancedMesh.js.map
  56397. "use strict";
  56398. var BABYLON;
  56399. (function (BABYLON) {
  56400. var LinesMesh = /** @class */ (function (_super) {
  56401. __extends(LinesMesh, _super);
  56402. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  56403. if (scene === void 0) { scene = null; }
  56404. if (parent === void 0) { parent = null; }
  56405. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  56406. _this.useVertexColor = useVertexColor;
  56407. _this.useVertexAlpha = useVertexAlpha;
  56408. _this.color = new BABYLON.Color3(1, 1, 1);
  56409. _this.alpha = 1;
  56410. if (source) {
  56411. _this.color = source.color.clone();
  56412. _this.alpha = source.alpha;
  56413. _this.useVertexColor = source.useVertexColor;
  56414. _this.useVertexAlpha = source.useVertexAlpha;
  56415. }
  56416. _this._intersectionThreshold = 0.1;
  56417. var defines = [];
  56418. var options = {
  56419. attributes: [BABYLON.VertexBuffer.PositionKind],
  56420. uniforms: ["world", "viewProjection"],
  56421. needAlphaBlending: true,
  56422. defines: defines
  56423. };
  56424. if (useVertexAlpha === false) {
  56425. options.needAlphaBlending = false;
  56426. }
  56427. if (!useVertexColor) {
  56428. options.uniforms.push("color");
  56429. }
  56430. else {
  56431. options.defines.push("#define VERTEXCOLOR");
  56432. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  56433. }
  56434. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  56435. return _this;
  56436. }
  56437. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  56438. /**
  56439. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56440. * This margin is expressed in world space coordinates, so its value may vary.
  56441. * Default value is 0.1
  56442. * @returns the intersection Threshold value.
  56443. */
  56444. get: function () {
  56445. return this._intersectionThreshold;
  56446. },
  56447. /**
  56448. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56449. * This margin is expressed in world space coordinates, so its value may vary.
  56450. * @param value the new threshold to apply
  56451. */
  56452. set: function (value) {
  56453. if (this._intersectionThreshold === value) {
  56454. return;
  56455. }
  56456. this._intersectionThreshold = value;
  56457. if (this.geometry) {
  56458. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  56459. }
  56460. },
  56461. enumerable: true,
  56462. configurable: true
  56463. });
  56464. /**
  56465. * Returns the string "LineMesh"
  56466. */
  56467. LinesMesh.prototype.getClassName = function () {
  56468. return "LinesMesh";
  56469. };
  56470. Object.defineProperty(LinesMesh.prototype, "material", {
  56471. get: function () {
  56472. return this._colorShader;
  56473. },
  56474. set: function (value) {
  56475. // Do nothing
  56476. },
  56477. enumerable: true,
  56478. configurable: true
  56479. });
  56480. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  56481. get: function () {
  56482. return false;
  56483. },
  56484. enumerable: true,
  56485. configurable: true
  56486. });
  56487. LinesMesh.prototype.createInstance = function (name) {
  56488. throw new Error("LinesMeshes do not support createInstance.");
  56489. };
  56490. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  56491. if (!this._geometry) {
  56492. return this;
  56493. }
  56494. // VBOs
  56495. this._geometry._bind(this._colorShader.getEffect());
  56496. // Color
  56497. if (!this.useVertexColor) {
  56498. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  56499. }
  56500. return this;
  56501. };
  56502. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  56503. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  56504. return this;
  56505. }
  56506. var engine = this.getScene().getEngine();
  56507. // Draw order
  56508. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  56509. return this;
  56510. };
  56511. LinesMesh.prototype.dispose = function (doNotRecurse) {
  56512. this._colorShader.dispose();
  56513. _super.prototype.dispose.call(this, doNotRecurse);
  56514. };
  56515. /**
  56516. * Returns a new LineMesh object cloned from the current one.
  56517. */
  56518. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56519. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  56520. };
  56521. return LinesMesh;
  56522. }(BABYLON.Mesh));
  56523. BABYLON.LinesMesh = LinesMesh;
  56524. })(BABYLON || (BABYLON = {}));
  56525. //# sourceMappingURL=babylon.linesMesh.js.map
  56526. "use strict";
  56527. var BABYLON;
  56528. (function (BABYLON) {
  56529. var MeshBuilder = /** @class */ (function () {
  56530. function MeshBuilder() {
  56531. }
  56532. MeshBuilder.updateSideOrientation = function (orientation) {
  56533. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  56534. return BABYLON.Mesh.DOUBLESIDE;
  56535. }
  56536. if (orientation === undefined || orientation === null) {
  56537. return BABYLON.Mesh.FRONTSIDE;
  56538. }
  56539. return orientation;
  56540. };
  56541. /**
  56542. * Creates a box mesh.
  56543. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  56544. * The parameter `size` sets the size (float) of each box side (default 1).
  56545. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  56546. * 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).
  56547. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56548. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56549. * 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).
  56550. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56551. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56552. */
  56553. MeshBuilder.CreateBox = function (name, options, scene) {
  56554. if (scene === void 0) { scene = null; }
  56555. var box = new BABYLON.Mesh(name, scene);
  56556. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56557. box._originalBuilderSideOrientation = options.sideOrientation;
  56558. var vertexData = BABYLON.VertexData.CreateBox(options);
  56559. vertexData.applyToMesh(box, options.updatable);
  56560. return box;
  56561. };
  56562. /**
  56563. * Creates a sphere mesh.
  56564. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  56565. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  56566. * 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`).
  56567. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  56568. * 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
  56569. * 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).
  56570. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56571. * 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).
  56572. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56573. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56574. */
  56575. MeshBuilder.CreateSphere = function (name, options, scene) {
  56576. var sphere = new BABYLON.Mesh(name, scene);
  56577. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56578. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56579. var vertexData = BABYLON.VertexData.CreateSphere(options);
  56580. vertexData.applyToMesh(sphere, options.updatable);
  56581. return sphere;
  56582. };
  56583. /**
  56584. * Creates a plane polygonal mesh. By default, this is a disc.
  56585. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  56586. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  56587. * 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.
  56588. * 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
  56589. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56590. * 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).
  56591. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56592. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56593. */
  56594. MeshBuilder.CreateDisc = function (name, options, scene) {
  56595. if (scene === void 0) { scene = null; }
  56596. var disc = new BABYLON.Mesh(name, scene);
  56597. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56598. disc._originalBuilderSideOrientation = options.sideOrientation;
  56599. var vertexData = BABYLON.VertexData.CreateDisc(options);
  56600. vertexData.applyToMesh(disc, options.updatable);
  56601. return disc;
  56602. };
  56603. /**
  56604. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  56605. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  56606. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  56607. * 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`).
  56608. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  56609. * 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.
  56610. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56611. * 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).
  56612. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56613. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56614. */
  56615. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  56616. var sphere = new BABYLON.Mesh(name, scene);
  56617. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56618. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56619. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  56620. vertexData.applyToMesh(sphere, options.updatable);
  56621. return sphere;
  56622. };
  56623. ;
  56624. /**
  56625. * Creates a ribbon mesh.
  56626. * 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.
  56627. *
  56628. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  56629. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  56630. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  56631. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  56632. * 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.
  56633. * 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.
  56634. * 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
  56635. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56636. * 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).
  56637. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56638. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56639. * 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.
  56640. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  56641. * 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
  56642. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  56643. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  56644. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56645. */
  56646. MeshBuilder.CreateRibbon = function (name, options, scene) {
  56647. if (scene === void 0) { scene = null; }
  56648. var pathArray = options.pathArray;
  56649. var closeArray = options.closeArray;
  56650. var closePath = options.closePath;
  56651. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56652. var instance = options.instance;
  56653. var updatable = options.updatable;
  56654. if (instance) {
  56655. // positionFunction : ribbon case
  56656. // only pathArray and sideOrientation parameters are taken into account for positions update
  56657. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  56658. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  56659. var positionFunction = function (positions) {
  56660. var minlg = pathArray[0].length;
  56661. var i = 0;
  56662. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  56663. for (var si = 1; si <= ns; si++) {
  56664. for (var p = 0; p < pathArray.length; p++) {
  56665. var path = pathArray[p];
  56666. var l = path.length;
  56667. minlg = (minlg < l) ? minlg : l;
  56668. var j = 0;
  56669. while (j < minlg) {
  56670. positions[i] = path[j].x;
  56671. positions[i + 1] = path[j].y;
  56672. positions[i + 2] = path[j].z;
  56673. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  56674. BABYLON.Tmp.Vector3[0].x = path[j].x;
  56675. }
  56676. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  56677. BABYLON.Tmp.Vector3[1].x = path[j].x;
  56678. }
  56679. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  56680. BABYLON.Tmp.Vector3[0].y = path[j].y;
  56681. }
  56682. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  56683. BABYLON.Tmp.Vector3[1].y = path[j].y;
  56684. }
  56685. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  56686. BABYLON.Tmp.Vector3[0].z = path[j].z;
  56687. }
  56688. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  56689. BABYLON.Tmp.Vector3[1].z = path[j].z;
  56690. }
  56691. j++;
  56692. i += 3;
  56693. }
  56694. if (instance._closePath) {
  56695. positions[i] = path[0].x;
  56696. positions[i + 1] = path[0].y;
  56697. positions[i + 2] = path[0].z;
  56698. i += 3;
  56699. }
  56700. }
  56701. }
  56702. };
  56703. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56704. positionFunction(positions);
  56705. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  56706. instance._boundingInfo.update(instance._worldMatrix);
  56707. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56708. if (options.colors) {
  56709. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56710. for (var c = 0; c < options.colors.length; c++) {
  56711. colors[c * 4] = options.colors[c].r;
  56712. colors[c * 4 + 1] = options.colors[c].g;
  56713. colors[c * 4 + 2] = options.colors[c].b;
  56714. colors[c * 4 + 3] = options.colors[c].a;
  56715. }
  56716. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  56717. }
  56718. if (options.uvs) {
  56719. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56720. for (var i = 0; i < options.uvs.length; i++) {
  56721. uvs[i * 2] = options.uvs[i].x;
  56722. uvs[i * 2 + 1] = options.uvs[i].y;
  56723. }
  56724. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  56725. }
  56726. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  56727. var indices = instance.getIndices();
  56728. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56729. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  56730. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  56731. if (instance._closePath) {
  56732. var indexFirst = 0;
  56733. var indexLast = 0;
  56734. for (var p = 0; p < pathArray.length; p++) {
  56735. indexFirst = instance._idx[p] * 3;
  56736. if (p + 1 < pathArray.length) {
  56737. indexLast = (instance._idx[p + 1] - 1) * 3;
  56738. }
  56739. else {
  56740. indexLast = normals.length - 3;
  56741. }
  56742. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  56743. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  56744. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  56745. normals[indexLast] = normals[indexFirst];
  56746. normals[indexLast + 1] = normals[indexFirst + 1];
  56747. normals[indexLast + 2] = normals[indexFirst + 2];
  56748. }
  56749. }
  56750. if (!(instance.areNormalsFrozen)) {
  56751. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  56752. }
  56753. }
  56754. return instance;
  56755. }
  56756. else {
  56757. var ribbon = new BABYLON.Mesh(name, scene);
  56758. ribbon._originalBuilderSideOrientation = sideOrientation;
  56759. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  56760. if (closePath) {
  56761. ribbon._idx = vertexData._idx;
  56762. }
  56763. ribbon._closePath = closePath;
  56764. ribbon._closeArray = closeArray;
  56765. vertexData.applyToMesh(ribbon, updatable);
  56766. return ribbon;
  56767. }
  56768. };
  56769. /**
  56770. * Creates a cylinder or a cone mesh.
  56771. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  56772. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  56773. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  56774. * 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.
  56775. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  56776. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  56777. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  56778. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  56779. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  56780. * 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).
  56781. * 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
  56782. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  56783. * 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
  56784. * 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.
  56785. * If `enclose` is false, a ring surface is one element.
  56786. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  56787. * 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
  56788. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56789. * 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).
  56790. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56791. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56792. */
  56793. MeshBuilder.CreateCylinder = function (name, options, scene) {
  56794. var cylinder = new BABYLON.Mesh(name, scene);
  56795. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56796. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  56797. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  56798. vertexData.applyToMesh(cylinder, options.updatable);
  56799. return cylinder;
  56800. };
  56801. /**
  56802. * Creates a torus mesh.
  56803. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  56804. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  56805. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  56806. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  56807. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56808. * 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).
  56809. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56810. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56811. */
  56812. MeshBuilder.CreateTorus = function (name, options, scene) {
  56813. var torus = new BABYLON.Mesh(name, scene);
  56814. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56815. torus._originalBuilderSideOrientation = options.sideOrientation;
  56816. var vertexData = BABYLON.VertexData.CreateTorus(options);
  56817. vertexData.applyToMesh(torus, options.updatable);
  56818. return torus;
  56819. };
  56820. /**
  56821. * Creates a torus knot mesh.
  56822. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  56823. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  56824. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  56825. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  56826. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  56827. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56828. * 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).
  56829. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56830. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56831. */
  56832. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  56833. var torusKnot = new BABYLON.Mesh(name, scene);
  56834. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56835. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  56836. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  56837. vertexData.applyToMesh(torusKnot, options.updatable);
  56838. return torusKnot;
  56839. };
  56840. /**
  56841. * Creates a line system mesh.
  56842. * A line system is a pool of many lines gathered in a single mesh.
  56843. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  56844. * 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.
  56845. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  56846. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  56847. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  56848. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  56849. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  56850. * 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
  56851. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  56852. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56853. */
  56854. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  56855. var instance = options.instance;
  56856. var lines = options.lines;
  56857. var colors = options.colors;
  56858. if (instance) {
  56859. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56860. var vertexColor;
  56861. var lineColors;
  56862. if (colors) {
  56863. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56864. }
  56865. var i = 0;
  56866. var c = 0;
  56867. for (var l = 0; l < lines.length; l++) {
  56868. var points = lines[l];
  56869. for (var p = 0; p < points.length; p++) {
  56870. positions[i] = points[p].x;
  56871. positions[i + 1] = points[p].y;
  56872. positions[i + 2] = points[p].z;
  56873. if (colors && vertexColor) {
  56874. lineColors = colors[l];
  56875. vertexColor[c] = lineColors[p].r;
  56876. vertexColor[c + 1] = lineColors[p].g;
  56877. vertexColor[c + 2] = lineColors[p].b;
  56878. vertexColor[c + 3] = lineColors[p].a;
  56879. c += 4;
  56880. }
  56881. i += 3;
  56882. }
  56883. }
  56884. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56885. if (colors && vertexColor) {
  56886. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  56887. }
  56888. return instance;
  56889. }
  56890. // line system creation
  56891. var useVertexColor = (colors) ? true : false;
  56892. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  56893. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  56894. vertexData.applyToMesh(lineSystem, options.updatable);
  56895. return lineSystem;
  56896. };
  56897. /**
  56898. * Creates a line mesh.
  56899. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  56900. * 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.
  56901. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56902. * The parameter `points` is an array successive Vector3.
  56903. * 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
  56904. * The optional parameter `colors` is an array of successive Color4, one per line point.
  56905. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  56906. * When updating an instance, remember that only point positions can change, not the number of points.
  56907. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56908. */
  56909. MeshBuilder.CreateLines = function (name, options, scene) {
  56910. if (scene === void 0) { scene = null; }
  56911. var colors = (options.colors) ? [options.colors] : null;
  56912. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  56913. return lines;
  56914. };
  56915. /**
  56916. * Creates a dashed line mesh.
  56917. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  56918. * 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.
  56919. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56920. * The parameter `points` is an array successive Vector3.
  56921. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  56922. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  56923. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  56924. * 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
  56925. * When updating an instance, remember that only point positions can change, not the number of points.
  56926. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56927. */
  56928. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  56929. if (scene === void 0) { scene = null; }
  56930. var points = options.points;
  56931. var instance = options.instance;
  56932. var gapSize = options.gapSize || 1;
  56933. var dashSize = options.dashSize || 3;
  56934. if (instance) {
  56935. var positionFunction = function (positions) {
  56936. var curvect = BABYLON.Vector3.Zero();
  56937. var nbSeg = positions.length / 6;
  56938. var lg = 0;
  56939. var nb = 0;
  56940. var shft = 0;
  56941. var dashshft = 0;
  56942. var curshft = 0;
  56943. var p = 0;
  56944. var i = 0;
  56945. var j = 0;
  56946. for (i = 0; i < points.length - 1; i++) {
  56947. points[i + 1].subtractToRef(points[i], curvect);
  56948. lg += curvect.length();
  56949. }
  56950. shft = lg / nbSeg;
  56951. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  56952. for (i = 0; i < points.length - 1; i++) {
  56953. points[i + 1].subtractToRef(points[i], curvect);
  56954. nb = Math.floor(curvect.length() / shft);
  56955. curvect.normalize();
  56956. j = 0;
  56957. while (j < nb && p < positions.length) {
  56958. curshft = shft * j;
  56959. positions[p] = points[i].x + curshft * curvect.x;
  56960. positions[p + 1] = points[i].y + curshft * curvect.y;
  56961. positions[p + 2] = points[i].z + curshft * curvect.z;
  56962. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56963. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56964. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56965. p += 6;
  56966. j++;
  56967. }
  56968. }
  56969. while (p < positions.length) {
  56970. positions[p] = points[i].x;
  56971. positions[p + 1] = points[i].y;
  56972. positions[p + 2] = points[i].z;
  56973. p += 3;
  56974. }
  56975. };
  56976. instance.updateMeshPositions(positionFunction, false);
  56977. return instance;
  56978. }
  56979. // dashed lines creation
  56980. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56981. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56982. vertexData.applyToMesh(dashedLines, options.updatable);
  56983. dashedLines.dashSize = dashSize;
  56984. dashedLines.gapSize = gapSize;
  56985. return dashedLines;
  56986. };
  56987. /**
  56988. * Creates an extruded shape mesh.
  56989. * 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.
  56990. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56991. *
  56992. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56993. * 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
  56994. * extruded along the Z axis.
  56995. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56996. * 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.
  56997. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56998. * 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
  56999. * 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
  57000. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  57001. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57002. * 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).
  57003. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57004. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57005. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57006. */
  57007. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  57008. if (scene === void 0) { scene = null; }
  57009. var path = options.path;
  57010. var shape = options.shape;
  57011. var scale = options.scale || 1;
  57012. var rotation = options.rotation || 0;
  57013. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  57014. var updatable = options.updatable;
  57015. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57016. var instance = options.instance || null;
  57017. var invertUV = options.invertUV || false;
  57018. 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);
  57019. };
  57020. /**
  57021. * Creates an custom extruded shape mesh.
  57022. * 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.
  57023. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  57024. *
  57025. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  57026. * 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
  57027. * extruded along the Z axis.
  57028. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  57029. * 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
  57030. * and the distance of this point from the begining of the path :
  57031. * ```javascript
  57032. * var rotationFunction = function(i, distance) {
  57033. * // do things
  57034. * return rotationValue; }
  57035. * ```
  57036. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  57037. * 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
  57038. * and the distance of this point from the begining of the path :
  57039. * ```javascript
  57040. * var scaleFunction = function(i, distance) {
  57041. * // do things
  57042. * return scaleValue;}
  57043. * ```
  57044. * It must returns a float value that will be the scale value applied to the shape on each path point.
  57045. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  57046. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  57047. * 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
  57048. * 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
  57049. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  57050. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57051. * 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).
  57052. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57053. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57054. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57055. */
  57056. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  57057. var path = options.path;
  57058. var shape = options.shape;
  57059. var scaleFunction = options.scaleFunction || (function () { return 1; });
  57060. var rotationFunction = options.rotationFunction || (function () { return 0; });
  57061. var ribbonCloseArray = options.ribbonCloseArray || false;
  57062. var ribbonClosePath = options.ribbonClosePath || false;
  57063. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  57064. var updatable = options.updatable;
  57065. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57066. var instance = options.instance;
  57067. var invertUV = options.invertUV || false;
  57068. 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);
  57069. };
  57070. /**
  57071. * Creates lathe mesh.
  57072. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  57073. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  57074. *
  57075. * 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
  57076. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  57077. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  57078. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  57079. * 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.
  57080. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  57081. * 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
  57082. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57083. * 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).
  57084. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57085. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57086. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57087. */
  57088. MeshBuilder.CreateLathe = function (name, options, scene) {
  57089. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  57090. var closed = (options.closed === undefined) ? true : options.closed;
  57091. var shape = options.shape;
  57092. var radius = options.radius || 1;
  57093. var tessellation = options.tessellation || 64;
  57094. var updatable = options.updatable;
  57095. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57096. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57097. var pi2 = Math.PI * 2;
  57098. var paths = new Array();
  57099. var invertUV = options.invertUV || false;
  57100. var i = 0;
  57101. var p = 0;
  57102. var step = pi2 / tessellation * arc;
  57103. var rotated;
  57104. var path = new Array();
  57105. ;
  57106. for (i = 0; i <= tessellation; i++) {
  57107. var path = [];
  57108. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  57109. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  57110. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  57111. }
  57112. for (p = 0; p < shape.length; p++) {
  57113. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  57114. path.push(rotated);
  57115. }
  57116. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  57117. 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));
  57118. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  57119. }
  57120. paths.push(path);
  57121. }
  57122. // lathe ribbon
  57123. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57124. return lathe;
  57125. };
  57126. /**
  57127. * Creates a plane mesh.
  57128. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  57129. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  57130. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  57131. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  57132. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57133. * 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).
  57134. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57135. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57136. */
  57137. MeshBuilder.CreatePlane = function (name, options, scene) {
  57138. var plane = new BABYLON.Mesh(name, scene);
  57139. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57140. plane._originalBuilderSideOrientation = options.sideOrientation;
  57141. var vertexData = BABYLON.VertexData.CreatePlane(options);
  57142. vertexData.applyToMesh(plane, options.updatable);
  57143. if (options.sourcePlane) {
  57144. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  57145. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  57146. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  57147. plane.rotate(vectorProduct, product);
  57148. }
  57149. return plane;
  57150. };
  57151. /**
  57152. * Creates a ground mesh.
  57153. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  57154. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  57155. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  57156. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57157. */
  57158. MeshBuilder.CreateGround = function (name, options, scene) {
  57159. var ground = new BABYLON.GroundMesh(name, scene);
  57160. ground._setReady(false);
  57161. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  57162. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  57163. ground._width = options.width || 1;
  57164. ground._height = options.height || 1;
  57165. ground._maxX = ground._width / 2;
  57166. ground._maxZ = ground._height / 2;
  57167. ground._minX = -ground._maxX;
  57168. ground._minZ = -ground._maxZ;
  57169. var vertexData = BABYLON.VertexData.CreateGround(options);
  57170. vertexData.applyToMesh(ground, options.updatable);
  57171. ground._setReady(true);
  57172. return ground;
  57173. };
  57174. /**
  57175. * Creates a tiled ground mesh.
  57176. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  57177. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  57178. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  57179. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  57180. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  57181. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  57182. * numbers of subdivisions on the ground width and height of each tile.
  57183. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57184. */
  57185. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  57186. var tiledGround = new BABYLON.Mesh(name, scene);
  57187. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  57188. vertexData.applyToMesh(tiledGround, options.updatable);
  57189. return tiledGround;
  57190. };
  57191. /**
  57192. * Creates a ground mesh from a height map.
  57193. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  57194. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  57195. * The parameter `url` sets the URL of the height map image resource.
  57196. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  57197. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  57198. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  57199. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  57200. * 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.
  57201. * 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).
  57202. * This function is passed the newly built mesh :
  57203. * ```javascript
  57204. * function(mesh) { // do things
  57205. * return; }
  57206. * ```
  57207. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57208. */
  57209. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  57210. var width = options.width || 10.0;
  57211. var height = options.height || 10.0;
  57212. var subdivisions = options.subdivisions || 1 | 0;
  57213. var minHeight = options.minHeight || 0.0;
  57214. var maxHeight = options.maxHeight || 1.0;
  57215. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  57216. var updatable = options.updatable;
  57217. var onReady = options.onReady;
  57218. var ground = new BABYLON.GroundMesh(name, scene);
  57219. ground._subdivisionsX = subdivisions;
  57220. ground._subdivisionsY = subdivisions;
  57221. ground._width = width;
  57222. ground._height = height;
  57223. ground._maxX = ground._width / 2.0;
  57224. ground._maxZ = ground._height / 2.0;
  57225. ground._minX = -ground._maxX;
  57226. ground._minZ = -ground._maxZ;
  57227. ground._setReady(false);
  57228. var onload = function (img) {
  57229. // Getting height map data
  57230. var canvas = document.createElement("canvas");
  57231. var context = canvas.getContext("2d");
  57232. if (!context) {
  57233. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  57234. }
  57235. if (scene.isDisposed) {
  57236. return;
  57237. }
  57238. var bufferWidth = img.width;
  57239. var bufferHeight = img.height;
  57240. canvas.width = bufferWidth;
  57241. canvas.height = bufferHeight;
  57242. context.drawImage(img, 0, 0);
  57243. // Create VertexData from map data
  57244. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  57245. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  57246. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  57247. width: width, height: height,
  57248. subdivisions: subdivisions,
  57249. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  57250. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  57251. });
  57252. vertexData.applyToMesh(ground, updatable);
  57253. //execute ready callback, if set
  57254. if (onReady) {
  57255. onReady(ground);
  57256. }
  57257. ground._setReady(true);
  57258. };
  57259. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  57260. return ground;
  57261. };
  57262. /**
  57263. * Creates a polygon mesh.
  57264. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  57265. * 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.
  57266. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57267. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57268. * 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).
  57269. * Remember you can only change the shape positions, not their number when updating a polygon.
  57270. */
  57271. MeshBuilder.CreatePolygon = function (name, options, scene) {
  57272. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57273. var shape = options.shape;
  57274. var holes = options.holes || [];
  57275. var depth = options.depth || 0;
  57276. var contours = [];
  57277. var hole = [];
  57278. for (var i = 0; i < shape.length; i++) {
  57279. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  57280. }
  57281. var epsilon = 0.00000001;
  57282. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  57283. contours.pop();
  57284. }
  57285. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  57286. for (var hNb = 0; hNb < holes.length; hNb++) {
  57287. hole = [];
  57288. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  57289. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  57290. }
  57291. polygonTriangulation.addHole(hole);
  57292. }
  57293. var polygon = polygonTriangulation.build(options.updatable, depth);
  57294. polygon._originalBuilderSideOrientation = options.sideOrientation;
  57295. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  57296. vertexData.applyToMesh(polygon, options.updatable);
  57297. return polygon;
  57298. };
  57299. ;
  57300. /**
  57301. * Creates an extruded polygon mesh, with depth in the Y direction.
  57302. * 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).
  57303. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  57304. */
  57305. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  57306. return MeshBuilder.CreatePolygon(name, options, scene);
  57307. };
  57308. ;
  57309. /**
  57310. * Creates a tube mesh.
  57311. * 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.
  57312. *
  57313. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  57314. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  57315. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  57316. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  57317. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  57318. * 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.
  57319. * It must return a radius value (positive float) :
  57320. * ```javascript
  57321. * var radiusFunction = function(i, distance) {
  57322. * // do things
  57323. * return radius; }
  57324. * ```
  57325. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  57326. * 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
  57327. * 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
  57328. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57329. * 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).
  57330. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57331. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57332. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57333. */
  57334. MeshBuilder.CreateTube = function (name, options, scene) {
  57335. var path = options.path;
  57336. var instance = options.instance;
  57337. var radius = 1.0;
  57338. if (instance) {
  57339. radius = instance.radius;
  57340. }
  57341. if (options.radius !== undefined) {
  57342. radius = options.radius;
  57343. }
  57344. ;
  57345. var tessellation = options.tessellation || 64 | 0;
  57346. var radiusFunction = options.radiusFunction || null;
  57347. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57348. var invertUV = options.invertUV || false;
  57349. var updatable = options.updatable;
  57350. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57351. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  57352. // tube geometry
  57353. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  57354. var tangents = path3D.getTangents();
  57355. var normals = path3D.getNormals();
  57356. var distances = path3D.getDistances();
  57357. var pi2 = Math.PI * 2;
  57358. var step = pi2 / tessellation * arc;
  57359. var returnRadius = function () { return radius; };
  57360. var radiusFunctionFinal = radiusFunction || returnRadius;
  57361. var circlePath;
  57362. var rad;
  57363. var normal;
  57364. var rotated;
  57365. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57366. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57367. for (var i = 0; i < path.length; i++) {
  57368. rad = radiusFunctionFinal(i, distances[i]); // current radius
  57369. circlePath = Array(); // current circle array
  57370. normal = normals[i]; // current normal
  57371. for (var t = 0; t < tessellation; t++) {
  57372. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  57373. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  57374. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  57375. rotated.scaleInPlace(rad).addInPlace(path[i]);
  57376. circlePath[t] = rotated;
  57377. }
  57378. circlePaths[index] = circlePath;
  57379. index++;
  57380. }
  57381. // cap
  57382. var capPath = function (nbPoints, pathIndex) {
  57383. var pointCap = Array();
  57384. for (var i = 0; i < nbPoints; i++) {
  57385. pointCap.push(path[pathIndex]);
  57386. }
  57387. return pointCap;
  57388. };
  57389. switch (cap) {
  57390. case BABYLON.Mesh.NO_CAP:
  57391. break;
  57392. case BABYLON.Mesh.CAP_START:
  57393. circlePaths[0] = capPath(tessellation, 0);
  57394. circlePaths[1] = circlePaths[2].slice(0);
  57395. break;
  57396. case BABYLON.Mesh.CAP_END:
  57397. circlePaths[index] = circlePaths[index - 1].slice(0);
  57398. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57399. break;
  57400. case BABYLON.Mesh.CAP_ALL:
  57401. circlePaths[0] = capPath(tessellation, 0);
  57402. circlePaths[1] = circlePaths[2].slice(0);
  57403. circlePaths[index] = circlePaths[index - 1].slice(0);
  57404. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57405. break;
  57406. default:
  57407. break;
  57408. }
  57409. return circlePaths;
  57410. };
  57411. var path3D;
  57412. var pathArray;
  57413. if (instance) {
  57414. var arc = options.arc || instance.arc;
  57415. path3D = (instance.path3D).update(path);
  57416. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  57417. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  57418. instance.path3D = path3D;
  57419. instance.pathArray = pathArray;
  57420. instance.arc = arc;
  57421. instance.radius = radius;
  57422. return instance;
  57423. }
  57424. // tube creation
  57425. path3D = new BABYLON.Path3D(path);
  57426. var newPathArray = new Array();
  57427. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57428. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  57429. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57430. tube.pathArray = pathArray;
  57431. tube.path3D = path3D;
  57432. tube.tessellation = tessellation;
  57433. tube.cap = cap;
  57434. tube.arc = options.arc;
  57435. tube.radius = radius;
  57436. return tube;
  57437. };
  57438. /**
  57439. * Creates a polyhedron mesh.
  57440. *
  57441. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  57442. * 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
  57443. * to choose the wanted type.
  57444. * The parameter `size` (positive float, default 1) sets the polygon size.
  57445. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  57446. * 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`.
  57447. * 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
  57448. * 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)`).
  57449. * 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
  57450. * 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.
  57451. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57452. * 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).
  57453. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57454. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57455. */
  57456. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  57457. var polyhedron = new BABYLON.Mesh(name, scene);
  57458. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57459. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  57460. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  57461. vertexData.applyToMesh(polyhedron, options.updatable);
  57462. return polyhedron;
  57463. };
  57464. /**
  57465. * Creates a decal mesh.
  57466. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  57467. * 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.
  57468. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  57469. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  57470. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  57471. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  57472. */
  57473. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  57474. var indices = sourceMesh.getIndices();
  57475. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57476. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57477. var position = options.position || BABYLON.Vector3.Zero();
  57478. var normal = options.normal || BABYLON.Vector3.Up();
  57479. var size = options.size || BABYLON.Vector3.One();
  57480. var angle = options.angle || 0;
  57481. // Getting correct rotation
  57482. if (!normal) {
  57483. var target = new BABYLON.Vector3(0, 0, 1);
  57484. var camera = sourceMesh.getScene().activeCamera;
  57485. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  57486. normal = camera.globalPosition.subtract(cameraWorldTarget);
  57487. }
  57488. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  57489. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  57490. var pitch = Math.atan2(normal.y, len);
  57491. // Matrix
  57492. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  57493. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  57494. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  57495. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  57496. var vertexData = new BABYLON.VertexData();
  57497. vertexData.indices = [];
  57498. vertexData.positions = [];
  57499. vertexData.normals = [];
  57500. vertexData.uvs = [];
  57501. var currentVertexDataIndex = 0;
  57502. var extractDecalVector3 = function (indexId) {
  57503. var result = new BABYLON.PositionNormalVertex();
  57504. if (!indices || !positions || !normals) {
  57505. return result;
  57506. }
  57507. var vertexId = indices[indexId];
  57508. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  57509. // Send vector to decal local world
  57510. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  57511. // Get normal
  57512. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  57513. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  57514. return result;
  57515. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  57516. var clip = function (vertices, axis) {
  57517. if (vertices.length === 0) {
  57518. return vertices;
  57519. }
  57520. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  57521. var clipVertices = function (v0, v1) {
  57522. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  57523. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  57524. };
  57525. var result = new Array();
  57526. for (var index = 0; index < vertices.length; index += 3) {
  57527. var v1Out;
  57528. var v2Out;
  57529. var v3Out;
  57530. var total = 0;
  57531. var nV1 = null;
  57532. var nV2 = null;
  57533. var nV3 = null;
  57534. var nV4 = null;
  57535. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  57536. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  57537. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  57538. v1Out = d1 > 0;
  57539. v2Out = d2 > 0;
  57540. v3Out = d3 > 0;
  57541. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  57542. switch (total) {
  57543. case 0:
  57544. result.push(vertices[index]);
  57545. result.push(vertices[index + 1]);
  57546. result.push(vertices[index + 2]);
  57547. break;
  57548. case 1:
  57549. if (v1Out) {
  57550. nV1 = vertices[index + 1];
  57551. nV2 = vertices[index + 2];
  57552. nV3 = clipVertices(vertices[index], nV1);
  57553. nV4 = clipVertices(vertices[index], nV2);
  57554. }
  57555. if (v2Out) {
  57556. nV1 = vertices[index];
  57557. nV2 = vertices[index + 2];
  57558. nV3 = clipVertices(vertices[index + 1], nV1);
  57559. nV4 = clipVertices(vertices[index + 1], nV2);
  57560. result.push(nV3);
  57561. result.push(nV2.clone());
  57562. result.push(nV1.clone());
  57563. result.push(nV2.clone());
  57564. result.push(nV3.clone());
  57565. result.push(nV4);
  57566. break;
  57567. }
  57568. if (v3Out) {
  57569. nV1 = vertices[index];
  57570. nV2 = vertices[index + 1];
  57571. nV3 = clipVertices(vertices[index + 2], nV1);
  57572. nV4 = clipVertices(vertices[index + 2], nV2);
  57573. }
  57574. if (nV1 && nV2 && nV3 && nV4) {
  57575. result.push(nV1.clone());
  57576. result.push(nV2.clone());
  57577. result.push(nV3);
  57578. result.push(nV4);
  57579. result.push(nV3.clone());
  57580. result.push(nV2.clone());
  57581. }
  57582. break;
  57583. case 2:
  57584. if (!v1Out) {
  57585. nV1 = vertices[index].clone();
  57586. nV2 = clipVertices(nV1, vertices[index + 1]);
  57587. nV3 = clipVertices(nV1, vertices[index + 2]);
  57588. result.push(nV1);
  57589. result.push(nV2);
  57590. result.push(nV3);
  57591. }
  57592. if (!v2Out) {
  57593. nV1 = vertices[index + 1].clone();
  57594. nV2 = clipVertices(nV1, vertices[index + 2]);
  57595. nV3 = clipVertices(nV1, vertices[index]);
  57596. result.push(nV1);
  57597. result.push(nV2);
  57598. result.push(nV3);
  57599. }
  57600. if (!v3Out) {
  57601. nV1 = vertices[index + 2].clone();
  57602. nV2 = clipVertices(nV1, vertices[index]);
  57603. nV3 = clipVertices(nV1, vertices[index + 1]);
  57604. result.push(nV1);
  57605. result.push(nV2);
  57606. result.push(nV3);
  57607. }
  57608. break;
  57609. case 3:
  57610. break;
  57611. }
  57612. }
  57613. return result;
  57614. };
  57615. for (var index = 0; index < indices.length; index += 3) {
  57616. var faceVertices = new Array();
  57617. faceVertices.push(extractDecalVector3(index));
  57618. faceVertices.push(extractDecalVector3(index + 1));
  57619. faceVertices.push(extractDecalVector3(index + 2));
  57620. // Clip
  57621. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  57622. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  57623. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  57624. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  57625. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  57626. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  57627. if (faceVertices.length === 0) {
  57628. continue;
  57629. }
  57630. // Add UVs and get back to world
  57631. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  57632. var vertex = faceVertices[vIndex];
  57633. //TODO check for Int32Array | Uint32Array | Uint16Array
  57634. vertexData.indices.push(currentVertexDataIndex);
  57635. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  57636. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  57637. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  57638. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  57639. currentVertexDataIndex++;
  57640. }
  57641. }
  57642. // Return mesh
  57643. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  57644. vertexData.applyToMesh(decal);
  57645. decal.position = position.clone();
  57646. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  57647. return decal;
  57648. };
  57649. // Privates
  57650. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  57651. // extrusion geometry
  57652. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  57653. var tangents = path3D.getTangents();
  57654. var normals = path3D.getNormals();
  57655. var binormals = path3D.getBinormals();
  57656. var distances = path3D.getDistances();
  57657. var angle = 0;
  57658. var returnScale = function () { return scale !== null ? scale : 1; };
  57659. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  57660. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  57661. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  57662. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57663. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57664. for (var i = 0; i < curve.length; i++) {
  57665. var shapePath = new Array();
  57666. var angleStep = rotate(i, distances[i]);
  57667. var scaleRatio = scl(i, distances[i]);
  57668. for (var p = 0; p < shape.length; p++) {
  57669. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  57670. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  57671. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  57672. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  57673. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  57674. shapePath[p] = rotated;
  57675. }
  57676. shapePaths[index] = shapePath;
  57677. angle += angleStep;
  57678. index++;
  57679. }
  57680. // cap
  57681. var capPath = function (shapePath) {
  57682. var pointCap = Array();
  57683. var barycenter = BABYLON.Vector3.Zero();
  57684. var i;
  57685. for (i = 0; i < shapePath.length; i++) {
  57686. barycenter.addInPlace(shapePath[i]);
  57687. }
  57688. barycenter.scaleInPlace(1.0 / shapePath.length);
  57689. for (i = 0; i < shapePath.length; i++) {
  57690. pointCap.push(barycenter);
  57691. }
  57692. return pointCap;
  57693. };
  57694. switch (cap) {
  57695. case BABYLON.Mesh.NO_CAP:
  57696. break;
  57697. case BABYLON.Mesh.CAP_START:
  57698. shapePaths[0] = capPath(shapePaths[2]);
  57699. shapePaths[1] = shapePaths[2];
  57700. break;
  57701. case BABYLON.Mesh.CAP_END:
  57702. shapePaths[index] = shapePaths[index - 1];
  57703. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57704. break;
  57705. case BABYLON.Mesh.CAP_ALL:
  57706. shapePaths[0] = capPath(shapePaths[2]);
  57707. shapePaths[1] = shapePaths[2];
  57708. shapePaths[index] = shapePaths[index - 1];
  57709. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57710. break;
  57711. default:
  57712. break;
  57713. }
  57714. return shapePaths;
  57715. };
  57716. var path3D;
  57717. var pathArray;
  57718. if (instance) {
  57719. path3D = (instance.path3D).update(curve);
  57720. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  57721. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  57722. return instance;
  57723. }
  57724. // extruded shape creation
  57725. path3D = new BABYLON.Path3D(curve);
  57726. var newShapePaths = new Array();
  57727. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57728. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  57729. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  57730. extrudedGeneric.pathArray = pathArray;
  57731. extrudedGeneric.path3D = path3D;
  57732. extrudedGeneric.cap = cap;
  57733. return extrudedGeneric;
  57734. };
  57735. return MeshBuilder;
  57736. }());
  57737. BABYLON.MeshBuilder = MeshBuilder;
  57738. })(BABYLON || (BABYLON = {}));
  57739. //# sourceMappingURL=babylon.meshBuilder.js.map
  57740. "use strict";
  57741. var BABYLON;
  57742. (function (BABYLON) {
  57743. /**
  57744. * Draco compression (https://google.github.io/draco/)
  57745. */
  57746. var DracoCompression = /** @class */ (function () {
  57747. /**
  57748. * Constructor
  57749. * @param numWorkers The number of workers for async operations
  57750. */
  57751. function DracoCompression(numWorkers) {
  57752. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  57753. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  57754. if (!workerBlobUrl || !Worker) {
  57755. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  57756. return;
  57757. }
  57758. var workers = new Array(numWorkers);
  57759. for (var i = 0; i < workers.length; i++) {
  57760. var worker = new Worker(workerBlobUrl);
  57761. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  57762. workers[i] = worker;
  57763. }
  57764. this._workerPool = new BABYLON.WorkerPool(workers);
  57765. }
  57766. /**
  57767. * Stop all async operations and release resources.
  57768. */
  57769. DracoCompression.prototype.dispose = function () {
  57770. this._workerPool.dispose();
  57771. delete this._workerPool;
  57772. };
  57773. /**
  57774. * Decode Draco compressed mesh data to vertex data.
  57775. * @param data The array buffer view for the Draco compression data
  57776. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  57777. * @returns A promise that resolves with the decoded vertex data
  57778. */
  57779. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  57780. var _this = this;
  57781. return new Promise(function (resolve, reject) {
  57782. _this._workerPool.push(function (worker, onComplete) {
  57783. var vertexData = new BABYLON.VertexData();
  57784. var onError = function (error) {
  57785. worker.removeEventListener("error", onError);
  57786. worker.removeEventListener("message", onMessage);
  57787. reject(error);
  57788. onComplete();
  57789. };
  57790. var onMessage = function (message) {
  57791. if (message.data === "done") {
  57792. worker.removeEventListener("error", onError);
  57793. worker.removeEventListener("message", onMessage);
  57794. resolve(vertexData);
  57795. onComplete();
  57796. }
  57797. else if (message.data.id === "indices") {
  57798. vertexData.indices = message.data.value;
  57799. }
  57800. else {
  57801. vertexData.set(message.data.value, message.data.id);
  57802. }
  57803. };
  57804. worker.addEventListener("error", onError);
  57805. worker.addEventListener("message", onMessage);
  57806. var dataCopy = new Uint8Array(data.byteLength);
  57807. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  57808. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  57809. });
  57810. });
  57811. };
  57812. /**
  57813. * The worker function that gets converted to a blob url to pass into a worker.
  57814. */
  57815. DracoCompression._Worker = function () {
  57816. // self is actually a DedicatedWorkerGlobalScope
  57817. var _self = self;
  57818. var decodeMesh = function (data, attributes) {
  57819. var dracoModule = new DracoDecoderModule();
  57820. var buffer = new dracoModule.DecoderBuffer();
  57821. buffer.Init(data, data.byteLength);
  57822. var decoder = new dracoModule.Decoder();
  57823. var geometry;
  57824. var status;
  57825. try {
  57826. var type = decoder.GetEncodedGeometryType(buffer);
  57827. switch (type) {
  57828. case dracoModule.TRIANGULAR_MESH:
  57829. geometry = new dracoModule.Mesh();
  57830. status = decoder.DecodeBufferToMesh(buffer, geometry);
  57831. break;
  57832. case dracoModule.POINT_CLOUD:
  57833. geometry = new dracoModule.PointCloud();
  57834. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  57835. break;
  57836. default:
  57837. throw new Error("Invalid geometry type " + type);
  57838. }
  57839. if (!status.ok() || !geometry.ptr) {
  57840. throw new Error(status.error_msg());
  57841. }
  57842. var numPoints = geometry.num_points();
  57843. if (type === dracoModule.TRIANGULAR_MESH) {
  57844. var numFaces = geometry.num_faces();
  57845. var faceIndices = new dracoModule.DracoInt32Array();
  57846. try {
  57847. var indices = new Uint32Array(numFaces * 3);
  57848. for (var i = 0; i < numFaces; i++) {
  57849. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  57850. var offset = i * 3;
  57851. indices[offset + 0] = faceIndices.GetValue(0);
  57852. indices[offset + 1] = faceIndices.GetValue(1);
  57853. indices[offset + 2] = faceIndices.GetValue(2);
  57854. }
  57855. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  57856. }
  57857. finally {
  57858. dracoModule.destroy(faceIndices);
  57859. }
  57860. }
  57861. for (var kind in attributes) {
  57862. var uniqueId = attributes[kind];
  57863. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  57864. var dracoData = new dracoModule.DracoFloat32Array();
  57865. try {
  57866. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  57867. var babylonData = new Float32Array(numPoints * attribute.num_components());
  57868. for (var i = 0; i < babylonData.length; i++) {
  57869. babylonData[i] = dracoData.GetValue(i);
  57870. }
  57871. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  57872. }
  57873. finally {
  57874. dracoModule.destroy(dracoData);
  57875. }
  57876. }
  57877. }
  57878. finally {
  57879. if (geometry) {
  57880. dracoModule.destroy(geometry);
  57881. }
  57882. dracoModule.destroy(decoder);
  57883. dracoModule.destroy(buffer);
  57884. }
  57885. _self.postMessage("done");
  57886. };
  57887. _self.onmessage = function (event) {
  57888. switch (event.data.id) {
  57889. case "initDecoder": {
  57890. importScripts(event.data.url);
  57891. break;
  57892. }
  57893. case "decodeMesh": {
  57894. decodeMesh(event.data.data, event.data.attributes);
  57895. break;
  57896. }
  57897. }
  57898. };
  57899. };
  57900. DracoCompression._GetDefaultDecoderUrl = function () {
  57901. if (!BABYLON.Tools.IsWindowObjectExist()) {
  57902. return null;
  57903. }
  57904. for (var i = 0; i < document.scripts.length; i++) {
  57905. if (document.scripts[i].type === "text/x-draco-decoder") {
  57906. return document.scripts[i].src;
  57907. }
  57908. }
  57909. return null;
  57910. };
  57911. /**
  57912. * Gets the url to the draco decoder if available.
  57913. */
  57914. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  57915. return DracoCompression;
  57916. }());
  57917. BABYLON.DracoCompression = DracoCompression;
  57918. })(BABYLON || (BABYLON = {}));
  57919. //# sourceMappingURL=babylon.dracoCompression.js.map
  57920. "use strict";
  57921. var BABYLON;
  57922. (function (BABYLON) {
  57923. var AudioEngine = /** @class */ (function () {
  57924. function AudioEngine() {
  57925. this._audioContext = null;
  57926. this._audioContextInitialized = false;
  57927. this.canUseWebAudio = false;
  57928. this.WarnedWebAudioUnsupported = false;
  57929. this.unlocked = false;
  57930. this.isMP3supported = false;
  57931. this.isOGGsupported = false;
  57932. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  57933. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  57934. this.canUseWebAudio = true;
  57935. }
  57936. var audioElem = document.createElement('audio');
  57937. try {
  57938. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  57939. this.isMP3supported = true;
  57940. }
  57941. }
  57942. catch (e) {
  57943. // protect error during capability check.
  57944. }
  57945. try {
  57946. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  57947. this.isOGGsupported = true;
  57948. }
  57949. }
  57950. catch (e) {
  57951. // protect error during capability check.
  57952. }
  57953. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  57954. this._unlockiOSaudio();
  57955. }
  57956. else {
  57957. this.unlocked = true;
  57958. }
  57959. }
  57960. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  57961. get: function () {
  57962. if (!this._audioContextInitialized) {
  57963. this._initializeAudioContext();
  57964. }
  57965. return this._audioContext;
  57966. },
  57967. enumerable: true,
  57968. configurable: true
  57969. });
  57970. AudioEngine.prototype._unlockiOSaudio = function () {
  57971. var _this = this;
  57972. var unlockaudio = function () {
  57973. if (!_this.audioContext) {
  57974. return;
  57975. }
  57976. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57977. var source = _this.audioContext.createBufferSource();
  57978. source.buffer = buffer;
  57979. source.connect(_this.audioContext.destination);
  57980. source.start(0);
  57981. setTimeout(function () {
  57982. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57983. _this.unlocked = true;
  57984. window.removeEventListener('touchend', unlockaudio, false);
  57985. if (_this.onAudioUnlocked) {
  57986. _this.onAudioUnlocked();
  57987. }
  57988. }
  57989. }, 0);
  57990. };
  57991. window.addEventListener('touchend', unlockaudio, false);
  57992. };
  57993. AudioEngine.prototype._initializeAudioContext = function () {
  57994. try {
  57995. if (this.canUseWebAudio) {
  57996. this._audioContext = new AudioContext();
  57997. // create a global volume gain node
  57998. this.masterGain = this._audioContext.createGain();
  57999. this.masterGain.gain.value = 1;
  58000. this.masterGain.connect(this._audioContext.destination);
  58001. this._audioContextInitialized = true;
  58002. }
  58003. }
  58004. catch (e) {
  58005. this.canUseWebAudio = false;
  58006. BABYLON.Tools.Error("Web Audio: " + e.message);
  58007. }
  58008. };
  58009. AudioEngine.prototype.dispose = function () {
  58010. if (this.canUseWebAudio && this._audioContextInitialized) {
  58011. if (this._connectedAnalyser && this._audioContext) {
  58012. this._connectedAnalyser.stopDebugCanvas();
  58013. this._connectedAnalyser.dispose();
  58014. this.masterGain.disconnect();
  58015. this.masterGain.connect(this._audioContext.destination);
  58016. this._connectedAnalyser = null;
  58017. }
  58018. this.masterGain.gain.value = 1;
  58019. }
  58020. this.WarnedWebAudioUnsupported = false;
  58021. };
  58022. AudioEngine.prototype.getGlobalVolume = function () {
  58023. if (this.canUseWebAudio && this._audioContextInitialized) {
  58024. return this.masterGain.gain.value;
  58025. }
  58026. else {
  58027. return -1;
  58028. }
  58029. };
  58030. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  58031. if (this.canUseWebAudio && this._audioContextInitialized) {
  58032. this.masterGain.gain.value = newVolume;
  58033. }
  58034. };
  58035. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  58036. if (this._connectedAnalyser) {
  58037. this._connectedAnalyser.stopDebugCanvas();
  58038. }
  58039. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  58040. this._connectedAnalyser = analyser;
  58041. this.masterGain.disconnect();
  58042. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  58043. }
  58044. };
  58045. return AudioEngine;
  58046. }());
  58047. BABYLON.AudioEngine = AudioEngine;
  58048. })(BABYLON || (BABYLON = {}));
  58049. //# sourceMappingURL=babylon.audioEngine.js.map
  58050. "use strict";
  58051. var BABYLON;
  58052. (function (BABYLON) {
  58053. var Sound = /** @class */ (function () {
  58054. /**
  58055. * Create a sound and attach it to a scene
  58056. * @param name Name of your sound
  58057. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  58058. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  58059. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  58060. */
  58061. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  58062. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  58063. var _this = this;
  58064. this.autoplay = false;
  58065. this.loop = false;
  58066. this.useCustomAttenuation = false;
  58067. this.spatialSound = false;
  58068. this.refDistance = 1;
  58069. this.rolloffFactor = 1;
  58070. this.maxDistance = 100;
  58071. this.distanceModel = "linear";
  58072. this._panningModel = "equalpower";
  58073. this._playbackRate = 1;
  58074. this._streaming = false;
  58075. this._startTime = 0;
  58076. this._startOffset = 0;
  58077. this._position = BABYLON.Vector3.Zero();
  58078. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  58079. this._volume = 1;
  58080. this._isReadyToPlay = false;
  58081. this.isPlaying = false;
  58082. this.isPaused = false;
  58083. this._isDirectional = false;
  58084. // Used if you'd like to create a directional sound.
  58085. // If not set, the sound will be omnidirectional
  58086. this._coneInnerAngle = 360;
  58087. this._coneOuterAngle = 360;
  58088. this._coneOuterGain = 0;
  58089. this._isOutputConnected = false;
  58090. this._urlType = "Unknown";
  58091. this.name = name;
  58092. this._scene = scene;
  58093. this._readyToPlayCallback = readyToPlayCallback;
  58094. // Default custom attenuation function is a linear attenuation
  58095. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  58096. if (currentDistance < maxDistance) {
  58097. return currentVolume * (1 - currentDistance / maxDistance);
  58098. }
  58099. else {
  58100. return 0;
  58101. }
  58102. };
  58103. if (options) {
  58104. this.autoplay = options.autoplay || false;
  58105. this.loop = options.loop || false;
  58106. // if volume === 0, we need another way to check this option
  58107. if (options.volume !== undefined) {
  58108. this._volume = options.volume;
  58109. }
  58110. this.spatialSound = options.spatialSound || false;
  58111. this.maxDistance = options.maxDistance || 100;
  58112. this.useCustomAttenuation = options.useCustomAttenuation || false;
  58113. this.rolloffFactor = options.rolloffFactor || 1;
  58114. this.refDistance = options.refDistance || 1;
  58115. this.distanceModel = options.distanceModel || "linear";
  58116. this._playbackRate = options.playbackRate || 1;
  58117. this._streaming = options.streaming || false;
  58118. }
  58119. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58120. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  58121. this._soundGain.gain.value = this._volume;
  58122. this._inputAudioNode = this._soundGain;
  58123. this._ouputAudioNode = this._soundGain;
  58124. if (this.spatialSound) {
  58125. this._createSpatialParameters();
  58126. }
  58127. this._scene.mainSoundTrack.AddSound(this);
  58128. var validParameter = true;
  58129. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  58130. if (urlOrArrayBuffer) {
  58131. try {
  58132. if (typeof (urlOrArrayBuffer) === "string")
  58133. this._urlType = "String";
  58134. if (Array.isArray(urlOrArrayBuffer))
  58135. this._urlType = "Array";
  58136. if (urlOrArrayBuffer instanceof ArrayBuffer)
  58137. this._urlType = "ArrayBuffer";
  58138. var urls = [];
  58139. var codecSupportedFound = false;
  58140. switch (this._urlType) {
  58141. case "ArrayBuffer":
  58142. if (urlOrArrayBuffer.byteLength > 0) {
  58143. codecSupportedFound = true;
  58144. this._soundLoaded(urlOrArrayBuffer);
  58145. }
  58146. break;
  58147. case "String":
  58148. urls.push(urlOrArrayBuffer);
  58149. case "Array":
  58150. if (urls.length === 0)
  58151. urls = urlOrArrayBuffer;
  58152. // If we found a supported format, we load it immediately and stop the loop
  58153. for (var i = 0; i < urls.length; i++) {
  58154. var url = urls[i];
  58155. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  58156. codecSupportedFound = true;
  58157. }
  58158. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  58159. codecSupportedFound = true;
  58160. }
  58161. if (url.indexOf(".wav", url.length - 4) !== -1) {
  58162. codecSupportedFound = true;
  58163. }
  58164. if (url.indexOf("blob:") !== -1) {
  58165. codecSupportedFound = true;
  58166. }
  58167. if (codecSupportedFound) {
  58168. // Loading sound using XHR2
  58169. if (!this._streaming) {
  58170. this._scene._loadFile(url, function (data) {
  58171. _this._soundLoaded(data);
  58172. }, undefined, true, true, function (exception) {
  58173. if (exception) {
  58174. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  58175. }
  58176. BABYLON.Tools.Error("Sound creation aborted.");
  58177. _this._scene.mainSoundTrack.RemoveSound(_this);
  58178. });
  58179. }
  58180. else {
  58181. this._htmlAudioElement = new Audio(url);
  58182. this._htmlAudioElement.controls = false;
  58183. this._htmlAudioElement.loop = this.loop;
  58184. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  58185. this._htmlAudioElement.preload = "auto";
  58186. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  58187. _this._isReadyToPlay = true;
  58188. if (_this.autoplay) {
  58189. _this.play();
  58190. }
  58191. if (_this._readyToPlayCallback) {
  58192. _this._readyToPlayCallback();
  58193. }
  58194. });
  58195. document.body.appendChild(this._htmlAudioElement);
  58196. }
  58197. break;
  58198. }
  58199. }
  58200. break;
  58201. default:
  58202. validParameter = false;
  58203. break;
  58204. }
  58205. if (!validParameter) {
  58206. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  58207. }
  58208. else {
  58209. if (!codecSupportedFound) {
  58210. this._isReadyToPlay = true;
  58211. // Simulating a ready to play event to avoid breaking code path
  58212. if (this._readyToPlayCallback) {
  58213. window.setTimeout(function () {
  58214. if (_this._readyToPlayCallback) {
  58215. _this._readyToPlayCallback();
  58216. }
  58217. }, 1000);
  58218. }
  58219. }
  58220. }
  58221. }
  58222. catch (ex) {
  58223. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  58224. this._scene.mainSoundTrack.RemoveSound(this);
  58225. }
  58226. }
  58227. }
  58228. else {
  58229. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  58230. this._scene.mainSoundTrack.AddSound(this);
  58231. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  58232. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  58233. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  58234. }
  58235. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  58236. if (this._readyToPlayCallback) {
  58237. window.setTimeout(function () {
  58238. if (_this._readyToPlayCallback) {
  58239. _this._readyToPlayCallback();
  58240. }
  58241. }, 1000);
  58242. }
  58243. }
  58244. }
  58245. Sound.prototype.dispose = function () {
  58246. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58247. if (this.isPlaying) {
  58248. this.stop();
  58249. }
  58250. this._isReadyToPlay = false;
  58251. if (this.soundTrackId === -1) {
  58252. this._scene.mainSoundTrack.RemoveSound(this);
  58253. }
  58254. else {
  58255. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  58256. }
  58257. if (this._soundGain) {
  58258. this._soundGain.disconnect();
  58259. this._soundGain = null;
  58260. }
  58261. if (this._soundPanner) {
  58262. this._soundPanner.disconnect();
  58263. this._soundPanner = null;
  58264. }
  58265. if (this._soundSource) {
  58266. this._soundSource.disconnect();
  58267. this._soundSource = null;
  58268. }
  58269. this._audioBuffer = null;
  58270. if (this._htmlAudioElement) {
  58271. this._htmlAudioElement.pause();
  58272. this._htmlAudioElement.src = "";
  58273. document.body.removeChild(this._htmlAudioElement);
  58274. }
  58275. if (this._connectedMesh && this._registerFunc) {
  58276. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58277. this._connectedMesh = null;
  58278. }
  58279. }
  58280. };
  58281. Sound.prototype.isReady = function () {
  58282. return this._isReadyToPlay;
  58283. };
  58284. Sound.prototype._soundLoaded = function (audioData) {
  58285. var _this = this;
  58286. if (!BABYLON.Engine.audioEngine.audioContext) {
  58287. return;
  58288. }
  58289. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  58290. _this._audioBuffer = buffer;
  58291. _this._isReadyToPlay = true;
  58292. if (_this.autoplay) {
  58293. _this.play();
  58294. }
  58295. if (_this._readyToPlayCallback) {
  58296. _this._readyToPlayCallback();
  58297. }
  58298. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  58299. };
  58300. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  58301. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58302. this._audioBuffer = audioBuffer;
  58303. this._isReadyToPlay = true;
  58304. }
  58305. };
  58306. Sound.prototype.updateOptions = function (options) {
  58307. if (options) {
  58308. this.loop = options.loop || this.loop;
  58309. this.maxDistance = options.maxDistance || this.maxDistance;
  58310. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  58311. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  58312. this.refDistance = options.refDistance || this.refDistance;
  58313. this.distanceModel = options.distanceModel || this.distanceModel;
  58314. this._playbackRate = options.playbackRate || this._playbackRate;
  58315. this._updateSpatialParameters();
  58316. if (this.isPlaying) {
  58317. if (this._streaming) {
  58318. this._htmlAudioElement.playbackRate = this._playbackRate;
  58319. }
  58320. else {
  58321. if (this._soundSource) {
  58322. this._soundSource.playbackRate.value = this._playbackRate;
  58323. }
  58324. }
  58325. }
  58326. }
  58327. };
  58328. Sound.prototype._createSpatialParameters = function () {
  58329. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58330. if (this._scene.headphone) {
  58331. this._panningModel = "HRTF";
  58332. }
  58333. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  58334. this._updateSpatialParameters();
  58335. this._soundPanner.connect(this._ouputAudioNode);
  58336. this._inputAudioNode = this._soundPanner;
  58337. }
  58338. };
  58339. Sound.prototype._updateSpatialParameters = function () {
  58340. if (this.spatialSound && this._soundPanner) {
  58341. if (this.useCustomAttenuation) {
  58342. // Tricks to disable in a way embedded Web Audio attenuation
  58343. this._soundPanner.distanceModel = "linear";
  58344. this._soundPanner.maxDistance = Number.MAX_VALUE;
  58345. this._soundPanner.refDistance = 1;
  58346. this._soundPanner.rolloffFactor = 1;
  58347. this._soundPanner.panningModel = this._panningModel;
  58348. }
  58349. else {
  58350. this._soundPanner.distanceModel = this.distanceModel;
  58351. this._soundPanner.maxDistance = this.maxDistance;
  58352. this._soundPanner.refDistance = this.refDistance;
  58353. this._soundPanner.rolloffFactor = this.rolloffFactor;
  58354. this._soundPanner.panningModel = this._panningModel;
  58355. }
  58356. }
  58357. };
  58358. Sound.prototype.switchPanningModelToHRTF = function () {
  58359. this._panningModel = "HRTF";
  58360. this._switchPanningModel();
  58361. };
  58362. Sound.prototype.switchPanningModelToEqualPower = function () {
  58363. this._panningModel = "equalpower";
  58364. this._switchPanningModel();
  58365. };
  58366. Sound.prototype._switchPanningModel = function () {
  58367. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58368. this._soundPanner.panningModel = this._panningModel;
  58369. }
  58370. };
  58371. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  58372. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58373. if (this._isOutputConnected) {
  58374. this._ouputAudioNode.disconnect();
  58375. }
  58376. this._ouputAudioNode.connect(soundTrackAudioNode);
  58377. this._isOutputConnected = true;
  58378. }
  58379. };
  58380. /**
  58381. * Transform this sound into a directional source
  58382. * @param coneInnerAngle Size of the inner cone in degree
  58383. * @param coneOuterAngle Size of the outer cone in degree
  58384. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  58385. */
  58386. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  58387. if (coneOuterAngle < coneInnerAngle) {
  58388. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  58389. return;
  58390. }
  58391. this._coneInnerAngle = coneInnerAngle;
  58392. this._coneOuterAngle = coneOuterAngle;
  58393. this._coneOuterGain = coneOuterGain;
  58394. this._isDirectional = true;
  58395. if (this.isPlaying && this.loop) {
  58396. this.stop();
  58397. this.play();
  58398. }
  58399. };
  58400. Sound.prototype.setPosition = function (newPosition) {
  58401. this._position = newPosition;
  58402. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58403. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58404. }
  58405. };
  58406. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  58407. this._localDirection = newLocalDirection;
  58408. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  58409. this._updateDirection();
  58410. }
  58411. };
  58412. Sound.prototype._updateDirection = function () {
  58413. if (!this._connectedMesh || !this._soundPanner) {
  58414. return;
  58415. }
  58416. var mat = this._connectedMesh.getWorldMatrix();
  58417. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  58418. direction.normalize();
  58419. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  58420. };
  58421. Sound.prototype.updateDistanceFromListener = function () {
  58422. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  58423. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  58424. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  58425. }
  58426. };
  58427. Sound.prototype.setAttenuationFunction = function (callback) {
  58428. this._customAttenuationFunction = callback;
  58429. };
  58430. /**
  58431. * Play the sound
  58432. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  58433. * @param offset (optional) Start the sound setting it at a specific time
  58434. */
  58435. Sound.prototype.play = function (time, offset) {
  58436. var _this = this;
  58437. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  58438. try {
  58439. if (this._startOffset < 0) {
  58440. time = -this._startOffset;
  58441. this._startOffset = 0;
  58442. }
  58443. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58444. if (!this._soundSource || !this._streamingSource) {
  58445. if (this.spatialSound && this._soundPanner) {
  58446. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58447. if (this._isDirectional) {
  58448. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  58449. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  58450. this._soundPanner.coneOuterGain = this._coneOuterGain;
  58451. if (this._connectedMesh) {
  58452. this._updateDirection();
  58453. }
  58454. else {
  58455. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  58456. }
  58457. }
  58458. }
  58459. }
  58460. if (this._streaming) {
  58461. if (!this._streamingSource) {
  58462. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  58463. this._htmlAudioElement.onended = function () { _this._onended(); };
  58464. this._htmlAudioElement.playbackRate = this._playbackRate;
  58465. }
  58466. this._streamingSource.disconnect();
  58467. this._streamingSource.connect(this._inputAudioNode);
  58468. this._htmlAudioElement.play();
  58469. }
  58470. else {
  58471. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  58472. this._soundSource.buffer = this._audioBuffer;
  58473. this._soundSource.connect(this._inputAudioNode);
  58474. this._soundSource.loop = this.loop;
  58475. this._soundSource.playbackRate.value = this._playbackRate;
  58476. this._soundSource.onended = function () { _this._onended(); };
  58477. if (this._soundSource.buffer) {
  58478. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  58479. }
  58480. }
  58481. this._startTime = startTime;
  58482. this.isPlaying = true;
  58483. this.isPaused = false;
  58484. }
  58485. catch (ex) {
  58486. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  58487. }
  58488. }
  58489. };
  58490. Sound.prototype._onended = function () {
  58491. this.isPlaying = false;
  58492. if (this.onended) {
  58493. this.onended();
  58494. }
  58495. };
  58496. /**
  58497. * Stop the sound
  58498. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  58499. */
  58500. Sound.prototype.stop = function (time) {
  58501. if (this.isPlaying) {
  58502. if (this._streaming) {
  58503. this._htmlAudioElement.pause();
  58504. // Test needed for Firefox or it will generate an Invalid State Error
  58505. if (this._htmlAudioElement.currentTime > 0) {
  58506. this._htmlAudioElement.currentTime = 0;
  58507. }
  58508. }
  58509. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  58510. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58511. this._soundSource.stop(stopTime);
  58512. this._soundSource.onended = function () { };
  58513. if (!this.isPaused) {
  58514. this._startOffset = 0;
  58515. }
  58516. }
  58517. this.isPlaying = false;
  58518. }
  58519. };
  58520. Sound.prototype.pause = function () {
  58521. if (this.isPlaying) {
  58522. this.isPaused = true;
  58523. if (this._streaming) {
  58524. this._htmlAudioElement.pause();
  58525. }
  58526. else if (BABYLON.Engine.audioEngine.audioContext) {
  58527. this.stop(0);
  58528. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  58529. }
  58530. }
  58531. };
  58532. Sound.prototype.setVolume = function (newVolume, time) {
  58533. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  58534. if (time && BABYLON.Engine.audioEngine.audioContext) {
  58535. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  58536. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  58537. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  58538. }
  58539. else {
  58540. this._soundGain.gain.value = newVolume;
  58541. }
  58542. }
  58543. this._volume = newVolume;
  58544. };
  58545. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  58546. this._playbackRate = newPlaybackRate;
  58547. if (this.isPlaying) {
  58548. if (this._streaming) {
  58549. this._htmlAudioElement.playbackRate = this._playbackRate;
  58550. }
  58551. else if (this._soundSource) {
  58552. this._soundSource.playbackRate.value = this._playbackRate;
  58553. }
  58554. }
  58555. };
  58556. Sound.prototype.getVolume = function () {
  58557. return this._volume;
  58558. };
  58559. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  58560. var _this = this;
  58561. if (this._connectedMesh && this._registerFunc) {
  58562. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58563. this._registerFunc = null;
  58564. }
  58565. this._connectedMesh = meshToConnectTo;
  58566. if (!this.spatialSound) {
  58567. this.spatialSound = true;
  58568. this._createSpatialParameters();
  58569. if (this.isPlaying && this.loop) {
  58570. this.stop();
  58571. this.play();
  58572. }
  58573. }
  58574. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  58575. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  58576. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  58577. };
  58578. Sound.prototype.detachFromMesh = function () {
  58579. if (this._connectedMesh && this._registerFunc) {
  58580. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58581. this._registerFunc = null;
  58582. this._connectedMesh = null;
  58583. }
  58584. };
  58585. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  58586. if (!node.getBoundingInfo) {
  58587. return;
  58588. }
  58589. var mesh = node;
  58590. var boundingInfo = mesh.getBoundingInfo();
  58591. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  58592. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  58593. this._updateDirection();
  58594. }
  58595. };
  58596. Sound.prototype.clone = function () {
  58597. var _this = this;
  58598. if (!this._streaming) {
  58599. var setBufferAndRun = function () {
  58600. if (_this._isReadyToPlay) {
  58601. clonedSound._audioBuffer = _this.getAudioBuffer();
  58602. clonedSound._isReadyToPlay = true;
  58603. if (clonedSound.autoplay) {
  58604. clonedSound.play();
  58605. }
  58606. }
  58607. else {
  58608. window.setTimeout(setBufferAndRun, 300);
  58609. }
  58610. };
  58611. var currentOptions = {
  58612. autoplay: this.autoplay, loop: this.loop,
  58613. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  58614. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  58615. refDistance: this.refDistance, distanceModel: this.distanceModel
  58616. };
  58617. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  58618. if (this.useCustomAttenuation) {
  58619. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  58620. }
  58621. clonedSound.setPosition(this._position);
  58622. clonedSound.setPlaybackRate(this._playbackRate);
  58623. setBufferAndRun();
  58624. return clonedSound;
  58625. }
  58626. else {
  58627. return null;
  58628. }
  58629. };
  58630. Sound.prototype.getAudioBuffer = function () {
  58631. return this._audioBuffer;
  58632. };
  58633. Sound.prototype.serialize = function () {
  58634. var serializationObject = {
  58635. name: this.name,
  58636. url: this.name,
  58637. autoplay: this.autoplay,
  58638. loop: this.loop,
  58639. volume: this._volume,
  58640. spatialSound: this.spatialSound,
  58641. maxDistance: this.maxDistance,
  58642. rolloffFactor: this.rolloffFactor,
  58643. refDistance: this.refDistance,
  58644. distanceModel: this.distanceModel,
  58645. playbackRate: this._playbackRate,
  58646. panningModel: this._panningModel,
  58647. soundTrackId: this.soundTrackId
  58648. };
  58649. if (this.spatialSound) {
  58650. if (this._connectedMesh)
  58651. serializationObject.connectedMeshId = this._connectedMesh.id;
  58652. serializationObject.position = this._position.asArray();
  58653. serializationObject.refDistance = this.refDistance;
  58654. serializationObject.distanceModel = this.distanceModel;
  58655. serializationObject.isDirectional = this._isDirectional;
  58656. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  58657. serializationObject.coneInnerAngle = this._coneInnerAngle;
  58658. serializationObject.coneOuterAngle = this._coneOuterAngle;
  58659. serializationObject.coneOuterGain = this._coneOuterGain;
  58660. }
  58661. return serializationObject;
  58662. };
  58663. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  58664. var soundName = parsedSound.name;
  58665. var soundUrl;
  58666. if (parsedSound.url) {
  58667. soundUrl = rootUrl + parsedSound.url;
  58668. }
  58669. else {
  58670. soundUrl = rootUrl + soundName;
  58671. }
  58672. var options = {
  58673. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  58674. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  58675. rolloffFactor: parsedSound.rolloffFactor,
  58676. refDistance: parsedSound.refDistance,
  58677. distanceModel: parsedSound.distanceModel,
  58678. playbackRate: parsedSound.playbackRate
  58679. };
  58680. var newSound;
  58681. if (!sourceSound) {
  58682. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  58683. scene._addPendingData(newSound);
  58684. }
  58685. else {
  58686. var setBufferAndRun = function () {
  58687. if (sourceSound._isReadyToPlay) {
  58688. newSound._audioBuffer = sourceSound.getAudioBuffer();
  58689. newSound._isReadyToPlay = true;
  58690. if (newSound.autoplay) {
  58691. newSound.play();
  58692. }
  58693. }
  58694. else {
  58695. window.setTimeout(setBufferAndRun, 300);
  58696. }
  58697. };
  58698. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  58699. setBufferAndRun();
  58700. }
  58701. if (parsedSound.position) {
  58702. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  58703. newSound.setPosition(soundPosition);
  58704. }
  58705. if (parsedSound.isDirectional) {
  58706. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  58707. if (parsedSound.localDirectionToMesh) {
  58708. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  58709. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  58710. }
  58711. }
  58712. if (parsedSound.connectedMeshId) {
  58713. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  58714. if (connectedMesh) {
  58715. newSound.attachToMesh(connectedMesh);
  58716. }
  58717. }
  58718. return newSound;
  58719. };
  58720. return Sound;
  58721. }());
  58722. BABYLON.Sound = Sound;
  58723. })(BABYLON || (BABYLON = {}));
  58724. //# sourceMappingURL=babylon.sound.js.map
  58725. "use strict";
  58726. var BABYLON;
  58727. (function (BABYLON) {
  58728. var SoundTrack = /** @class */ (function () {
  58729. function SoundTrack(scene, options) {
  58730. this.id = -1;
  58731. this._isMainTrack = false;
  58732. this._isInitialized = false;
  58733. this._scene = scene;
  58734. this.soundCollection = new Array();
  58735. this._options = options;
  58736. if (!this._isMainTrack) {
  58737. this._scene.soundTracks.push(this);
  58738. this.id = this._scene.soundTracks.length - 1;
  58739. }
  58740. }
  58741. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  58742. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58743. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  58744. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  58745. if (this._options) {
  58746. if (this._options.volume) {
  58747. this._outputAudioNode.gain.value = this._options.volume;
  58748. }
  58749. if (this._options.mainTrack) {
  58750. this._isMainTrack = this._options.mainTrack;
  58751. }
  58752. }
  58753. this._isInitialized = true;
  58754. }
  58755. };
  58756. SoundTrack.prototype.dispose = function () {
  58757. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  58758. if (this._connectedAnalyser) {
  58759. this._connectedAnalyser.stopDebugCanvas();
  58760. }
  58761. while (this.soundCollection.length) {
  58762. this.soundCollection[0].dispose();
  58763. }
  58764. if (this._outputAudioNode) {
  58765. this._outputAudioNode.disconnect();
  58766. }
  58767. this._outputAudioNode = null;
  58768. }
  58769. };
  58770. SoundTrack.prototype.AddSound = function (sound) {
  58771. if (!this._isInitialized) {
  58772. this._initializeSoundTrackAudioGraph();
  58773. }
  58774. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58775. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  58776. }
  58777. if (sound.soundTrackId) {
  58778. if (sound.soundTrackId === -1) {
  58779. this._scene.mainSoundTrack.RemoveSound(sound);
  58780. }
  58781. else {
  58782. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  58783. }
  58784. }
  58785. this.soundCollection.push(sound);
  58786. sound.soundTrackId = this.id;
  58787. };
  58788. SoundTrack.prototype.RemoveSound = function (sound) {
  58789. var index = this.soundCollection.indexOf(sound);
  58790. if (index !== -1) {
  58791. this.soundCollection.splice(index, 1);
  58792. }
  58793. };
  58794. SoundTrack.prototype.setVolume = function (newVolume) {
  58795. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58796. this._outputAudioNode.gain.value = newVolume;
  58797. }
  58798. };
  58799. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  58800. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58801. for (var i = 0; i < this.soundCollection.length; i++) {
  58802. this.soundCollection[i].switchPanningModelToHRTF();
  58803. }
  58804. }
  58805. };
  58806. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  58807. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58808. for (var i = 0; i < this.soundCollection.length; i++) {
  58809. this.soundCollection[i].switchPanningModelToEqualPower();
  58810. }
  58811. }
  58812. };
  58813. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  58814. if (this._connectedAnalyser) {
  58815. this._connectedAnalyser.stopDebugCanvas();
  58816. }
  58817. this._connectedAnalyser = analyser;
  58818. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58819. this._outputAudioNode.disconnect();
  58820. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  58821. }
  58822. };
  58823. return SoundTrack;
  58824. }());
  58825. BABYLON.SoundTrack = SoundTrack;
  58826. })(BABYLON || (BABYLON = {}));
  58827. //# sourceMappingURL=babylon.soundtrack.js.map
  58828. "use strict";
  58829. var BABYLON;
  58830. (function (BABYLON) {
  58831. var Analyser = /** @class */ (function () {
  58832. function Analyser(scene) {
  58833. this.SMOOTHING = 0.75;
  58834. this.FFT_SIZE = 512;
  58835. this.BARGRAPHAMPLITUDE = 256;
  58836. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  58837. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  58838. this._scene = scene;
  58839. this._audioEngine = BABYLON.Engine.audioEngine;
  58840. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  58841. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  58842. this._webAudioAnalyser.minDecibels = -140;
  58843. this._webAudioAnalyser.maxDecibels = 0;
  58844. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58845. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58846. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  58847. }
  58848. }
  58849. Analyser.prototype.getFrequencyBinCount = function () {
  58850. if (this._audioEngine.canUseWebAudio) {
  58851. return this._webAudioAnalyser.frequencyBinCount;
  58852. }
  58853. else {
  58854. return 0;
  58855. }
  58856. };
  58857. Analyser.prototype.getByteFrequencyData = function () {
  58858. if (this._audioEngine.canUseWebAudio) {
  58859. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58860. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58861. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  58862. }
  58863. return this._byteFreqs;
  58864. };
  58865. Analyser.prototype.getByteTimeDomainData = function () {
  58866. if (this._audioEngine.canUseWebAudio) {
  58867. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58868. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58869. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  58870. }
  58871. return this._byteTime;
  58872. };
  58873. Analyser.prototype.getFloatFrequencyData = function () {
  58874. if (this._audioEngine.canUseWebAudio) {
  58875. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58876. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58877. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  58878. }
  58879. return this._floatFreqs;
  58880. };
  58881. Analyser.prototype.drawDebugCanvas = function () {
  58882. var _this = this;
  58883. if (this._audioEngine.canUseWebAudio) {
  58884. if (!this._debugCanvas) {
  58885. this._debugCanvas = document.createElement("canvas");
  58886. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  58887. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  58888. this._debugCanvas.style.position = "absolute";
  58889. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  58890. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  58891. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  58892. document.body.appendChild(this._debugCanvas);
  58893. this._registerFunc = function () {
  58894. _this.drawDebugCanvas();
  58895. };
  58896. this._scene.registerBeforeRender(this._registerFunc);
  58897. }
  58898. if (this._registerFunc && this._debugCanvasContext) {
  58899. var workingArray = this.getByteFrequencyData();
  58900. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  58901. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  58902. // Draw the frequency domain chart.
  58903. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  58904. var value = workingArray[i];
  58905. var percent = value / this.BARGRAPHAMPLITUDE;
  58906. var height = this.DEBUGCANVASSIZE.height * percent;
  58907. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  58908. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  58909. var hue = i / this.getFrequencyBinCount() * 360;
  58910. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  58911. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  58912. }
  58913. }
  58914. }
  58915. };
  58916. Analyser.prototype.stopDebugCanvas = function () {
  58917. if (this._debugCanvas) {
  58918. if (this._registerFunc) {
  58919. this._scene.unregisterBeforeRender(this._registerFunc);
  58920. this._registerFunc = null;
  58921. }
  58922. document.body.removeChild(this._debugCanvas);
  58923. this._debugCanvas = null;
  58924. this._debugCanvasContext = null;
  58925. }
  58926. };
  58927. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  58928. if (this._audioEngine.canUseWebAudio) {
  58929. inputAudioNode.connect(this._webAudioAnalyser);
  58930. this._webAudioAnalyser.connect(outputAudioNode);
  58931. }
  58932. };
  58933. Analyser.prototype.dispose = function () {
  58934. if (this._audioEngine.canUseWebAudio) {
  58935. this._webAudioAnalyser.disconnect();
  58936. }
  58937. };
  58938. return Analyser;
  58939. }());
  58940. BABYLON.Analyser = Analyser;
  58941. })(BABYLON || (BABYLON = {}));
  58942. //# sourceMappingURL=babylon.analyser.js.map
  58943. "use strict";
  58944. var BABYLON;
  58945. (function (BABYLON) {
  58946. var CubeTexture = /** @class */ (function (_super) {
  58947. __extends(CubeTexture, _super);
  58948. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  58949. if (extensions === void 0) { extensions = null; }
  58950. if (noMipmap === void 0) { noMipmap = false; }
  58951. if (files === void 0) { files = null; }
  58952. if (onLoad === void 0) { onLoad = null; }
  58953. if (onError === void 0) { onError = null; }
  58954. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58955. if (prefiltered === void 0) { prefiltered = false; }
  58956. if (forcedExtension === void 0) { forcedExtension = null; }
  58957. var _this = _super.call(this, scene) || this;
  58958. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58959. /**
  58960. * Gets or sets the center of the bounding box associated with the cube texture
  58961. * It must define where the camera used to render the texture was set
  58962. */
  58963. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58964. _this.name = rootUrl;
  58965. _this.url = rootUrl;
  58966. _this._noMipmap = noMipmap;
  58967. _this.hasAlpha = false;
  58968. _this._format = format;
  58969. _this._prefiltered = prefiltered;
  58970. _this.isCube = true;
  58971. _this._textureMatrix = BABYLON.Matrix.Identity();
  58972. if (prefiltered) {
  58973. _this.gammaSpace = false;
  58974. }
  58975. if (!rootUrl && !files) {
  58976. return _this;
  58977. }
  58978. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  58979. var lastDot = rootUrl.lastIndexOf(".");
  58980. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  58981. var isDDS = (extension === ".dds");
  58982. if (!files) {
  58983. if (!isDDS && !extensions) {
  58984. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58985. }
  58986. files = [];
  58987. if (extensions) {
  58988. for (var index = 0; index < extensions.length; index++) {
  58989. files.push(rootUrl + extensions[index]);
  58990. }
  58991. }
  58992. }
  58993. _this._files = files;
  58994. if (!_this._texture) {
  58995. if (!scene.useDelayedTextureLoading) {
  58996. if (prefiltered) {
  58997. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58998. }
  58999. else {
  59000. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  59001. }
  59002. }
  59003. else {
  59004. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  59005. }
  59006. }
  59007. else if (onLoad) {
  59008. if (_this._texture.isReady) {
  59009. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  59010. }
  59011. else {
  59012. _this._texture.onLoadedObservable.add(onLoad);
  59013. }
  59014. }
  59015. return _this;
  59016. }
  59017. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  59018. get: function () {
  59019. return this._boundingBoxSize;
  59020. },
  59021. /**
  59022. * Gets or sets the size of the bounding box associated with the cube texture
  59023. * When defined, the cubemap will switch to local mode
  59024. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  59025. * @example https://www.babylonjs-playground.com/#RNASML
  59026. */
  59027. set: function (value) {
  59028. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  59029. return;
  59030. }
  59031. this._boundingBoxSize = value;
  59032. var scene = this.getScene();
  59033. if (scene) {
  59034. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59035. }
  59036. },
  59037. enumerable: true,
  59038. configurable: true
  59039. });
  59040. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  59041. var rootUrlKey = "";
  59042. files.forEach(function (url) { return rootUrlKey += url; });
  59043. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  59044. };
  59045. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  59046. if (forcedExtension === void 0) { forcedExtension = null; }
  59047. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  59048. };
  59049. // Methods
  59050. CubeTexture.prototype.delayLoad = function () {
  59051. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59052. return;
  59053. }
  59054. var scene = this.getScene();
  59055. if (!scene) {
  59056. return;
  59057. }
  59058. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59059. this._texture = this._getFromCache(this.url, this._noMipmap);
  59060. if (!this._texture) {
  59061. if (this._prefiltered) {
  59062. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  59063. }
  59064. else {
  59065. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  59066. }
  59067. }
  59068. };
  59069. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  59070. return this._textureMatrix;
  59071. };
  59072. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  59073. this._textureMatrix = value;
  59074. };
  59075. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  59076. var texture = BABYLON.SerializationHelper.Parse(function () {
  59077. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  59078. }, parsedTexture, scene);
  59079. // Local Cubemaps
  59080. if (parsedTexture.boundingBoxPosition) {
  59081. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  59082. }
  59083. if (parsedTexture.boundingBoxSize) {
  59084. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  59085. }
  59086. // Animations
  59087. if (parsedTexture.animations) {
  59088. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  59089. var parsedAnimation = parsedTexture.animations[animationIndex];
  59090. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  59091. }
  59092. }
  59093. return texture;
  59094. };
  59095. CubeTexture.prototype.clone = function () {
  59096. var _this = this;
  59097. return BABYLON.SerializationHelper.Clone(function () {
  59098. var scene = _this.getScene();
  59099. if (!scene) {
  59100. return _this;
  59101. }
  59102. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  59103. }, this);
  59104. };
  59105. return CubeTexture;
  59106. }(BABYLON.BaseTexture));
  59107. BABYLON.CubeTexture = CubeTexture;
  59108. })(BABYLON || (BABYLON = {}));
  59109. //# sourceMappingURL=babylon.cubeTexture.js.map
  59110. "use strict";
  59111. var BABYLON;
  59112. (function (BABYLON) {
  59113. var RenderTargetTexture = /** @class */ (function (_super) {
  59114. __extends(RenderTargetTexture, _super);
  59115. /**
  59116. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  59117. * or used a shadow, depth texture...
  59118. * @param name The friendly name of the texture
  59119. * @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)
  59120. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  59121. * @param generateMipMaps True if mip maps need to be generated after render.
  59122. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  59123. * @param type The type of the buffer in the RTT (int, half float, float...)
  59124. * @param isCube True if a cube texture needs to be created
  59125. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  59126. * @param generateDepthBuffer True to generate a depth buffer
  59127. * @param generateStencilBuffer True to generate a stencil buffer
  59128. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  59129. */
  59130. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  59131. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  59132. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59133. if (isCube === void 0) { isCube = false; }
  59134. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59135. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59136. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  59137. if (isMulti === void 0) { isMulti = false; }
  59138. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  59139. _this.isCube = isCube;
  59140. /**
  59141. * Use this list to define the list of mesh you want to render.
  59142. */
  59143. _this.renderList = new Array();
  59144. _this.renderParticles = true;
  59145. _this.renderSprites = false;
  59146. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  59147. _this.ignoreCameraViewport = false;
  59148. // Events
  59149. /**
  59150. * An event triggered when the texture is unbind.
  59151. * @type {BABYLON.Observable}
  59152. */
  59153. _this.onBeforeBindObservable = new BABYLON.Observable();
  59154. /**
  59155. * An event triggered when the texture is unbind.
  59156. * @type {BABYLON.Observable}
  59157. */
  59158. _this.onAfterUnbindObservable = new BABYLON.Observable();
  59159. /**
  59160. * An event triggered before rendering the texture
  59161. * @type {BABYLON.Observable}
  59162. */
  59163. _this.onBeforeRenderObservable = new BABYLON.Observable();
  59164. /**
  59165. * An event triggered after rendering the texture
  59166. * @type {BABYLON.Observable}
  59167. */
  59168. _this.onAfterRenderObservable = new BABYLON.Observable();
  59169. /**
  59170. * An event triggered after the texture clear
  59171. * @type {BABYLON.Observable}
  59172. */
  59173. _this.onClearObservable = new BABYLON.Observable();
  59174. _this._currentRefreshId = -1;
  59175. _this._refreshRate = 1;
  59176. _this._samples = 1;
  59177. /**
  59178. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  59179. * It must define where the camera used to render the texture is set
  59180. */
  59181. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  59182. scene = _this.getScene();
  59183. if (!scene) {
  59184. return _this;
  59185. }
  59186. _this._engine = scene.getEngine();
  59187. _this.name = name;
  59188. _this.isRenderTarget = true;
  59189. _this._initialSizeParameter = size;
  59190. _this._processSizeParameter(size);
  59191. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  59192. });
  59193. _this._generateMipMaps = generateMipMaps ? true : false;
  59194. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  59195. // Rendering groups
  59196. _this._renderingManager = new BABYLON.RenderingManager(scene);
  59197. if (isMulti) {
  59198. return _this;
  59199. }
  59200. _this._renderTargetOptions = {
  59201. generateMipMaps: generateMipMaps,
  59202. type: type,
  59203. samplingMode: samplingMode,
  59204. generateDepthBuffer: generateDepthBuffer,
  59205. generateStencilBuffer: generateStencilBuffer
  59206. };
  59207. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  59208. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59209. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59210. }
  59211. if (isCube) {
  59212. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  59213. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  59214. _this._textureMatrix = BABYLON.Matrix.Identity();
  59215. }
  59216. else {
  59217. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  59218. }
  59219. return _this;
  59220. }
  59221. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  59222. get: function () {
  59223. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  59224. },
  59225. enumerable: true,
  59226. configurable: true
  59227. });
  59228. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  59229. get: function () {
  59230. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  59231. },
  59232. enumerable: true,
  59233. configurable: true
  59234. });
  59235. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  59236. get: function () {
  59237. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  59238. },
  59239. enumerable: true,
  59240. configurable: true
  59241. });
  59242. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  59243. set: function (callback) {
  59244. if (this._onAfterUnbindObserver) {
  59245. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  59246. }
  59247. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  59248. },
  59249. enumerable: true,
  59250. configurable: true
  59251. });
  59252. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  59253. set: function (callback) {
  59254. if (this._onBeforeRenderObserver) {
  59255. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59256. }
  59257. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59258. },
  59259. enumerable: true,
  59260. configurable: true
  59261. });
  59262. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  59263. set: function (callback) {
  59264. if (this._onAfterRenderObserver) {
  59265. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59266. }
  59267. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59268. },
  59269. enumerable: true,
  59270. configurable: true
  59271. });
  59272. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  59273. set: function (callback) {
  59274. if (this._onClearObserver) {
  59275. this.onClearObservable.remove(this._onClearObserver);
  59276. }
  59277. this._onClearObserver = this.onClearObservable.add(callback);
  59278. },
  59279. enumerable: true,
  59280. configurable: true
  59281. });
  59282. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  59283. get: function () {
  59284. return this._renderTargetOptions;
  59285. },
  59286. enumerable: true,
  59287. configurable: true
  59288. });
  59289. RenderTargetTexture.prototype._onRatioRescale = function () {
  59290. if (this._sizeRatio) {
  59291. this.resize(this._initialSizeParameter);
  59292. }
  59293. };
  59294. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  59295. get: function () {
  59296. return this._boundingBoxSize;
  59297. },
  59298. /**
  59299. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  59300. * When defined, the cubemap will switch to local mode
  59301. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  59302. * @example https://www.babylonjs-playground.com/#RNASML
  59303. */
  59304. set: function (value) {
  59305. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  59306. return;
  59307. }
  59308. this._boundingBoxSize = value;
  59309. var scene = this.getScene();
  59310. if (scene) {
  59311. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59312. }
  59313. },
  59314. enumerable: true,
  59315. configurable: true
  59316. });
  59317. /**
  59318. * Creates a depth stencil texture.
  59319. * This is only available in WebGL 2 or with the depth texture extension available.
  59320. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  59321. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  59322. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  59323. */
  59324. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  59325. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  59326. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  59327. if (generateStencil === void 0) { generateStencil = false; }
  59328. if (!this.getScene()) {
  59329. return;
  59330. }
  59331. var engine = this.getScene().getEngine();
  59332. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  59333. bilinearFiltering: bilinearFiltering,
  59334. comparisonFunction: comparisonFunction,
  59335. generateStencil: generateStencil,
  59336. isCube: this.isCube
  59337. });
  59338. engine.setFrameBufferDepthStencilTexture(this);
  59339. };
  59340. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  59341. if (size.ratio) {
  59342. this._sizeRatio = size.ratio;
  59343. this._size = {
  59344. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  59345. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  59346. };
  59347. }
  59348. else {
  59349. this._size = size;
  59350. }
  59351. };
  59352. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  59353. get: function () {
  59354. return this._samples;
  59355. },
  59356. set: function (value) {
  59357. if (this._samples === value) {
  59358. return;
  59359. }
  59360. var scene = this.getScene();
  59361. if (!scene) {
  59362. return;
  59363. }
  59364. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  59365. },
  59366. enumerable: true,
  59367. configurable: true
  59368. });
  59369. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  59370. this._currentRefreshId = -1;
  59371. };
  59372. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  59373. get: function () {
  59374. return this._refreshRate;
  59375. },
  59376. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59377. set: function (value) {
  59378. this._refreshRate = value;
  59379. this.resetRefreshCounter();
  59380. },
  59381. enumerable: true,
  59382. configurable: true
  59383. });
  59384. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  59385. if (!this._postProcessManager) {
  59386. var scene = this.getScene();
  59387. if (!scene) {
  59388. return;
  59389. }
  59390. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  59391. this._postProcesses = new Array();
  59392. }
  59393. this._postProcesses.push(postProcess);
  59394. this._postProcesses[0].autoClear = false;
  59395. };
  59396. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  59397. if (!this._postProcesses) {
  59398. return;
  59399. }
  59400. if (dispose) {
  59401. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  59402. var postProcess = _a[_i];
  59403. postProcess.dispose();
  59404. }
  59405. }
  59406. this._postProcesses = [];
  59407. };
  59408. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  59409. if (!this._postProcesses) {
  59410. return;
  59411. }
  59412. var index = this._postProcesses.indexOf(postProcess);
  59413. if (index === -1) {
  59414. return;
  59415. }
  59416. this._postProcesses.splice(index, 1);
  59417. if (this._postProcesses.length > 0) {
  59418. this._postProcesses[0].autoClear = false;
  59419. }
  59420. };
  59421. RenderTargetTexture.prototype._shouldRender = function () {
  59422. if (this._currentRefreshId === -1) {
  59423. this._currentRefreshId = 1;
  59424. return true;
  59425. }
  59426. if (this.refreshRate === this._currentRefreshId) {
  59427. this._currentRefreshId = 1;
  59428. return true;
  59429. }
  59430. this._currentRefreshId++;
  59431. return false;
  59432. };
  59433. RenderTargetTexture.prototype.getRenderSize = function () {
  59434. if (this._size.width) {
  59435. return this._size.width;
  59436. }
  59437. return this._size;
  59438. };
  59439. RenderTargetTexture.prototype.getRenderWidth = function () {
  59440. if (this._size.width) {
  59441. return this._size.width;
  59442. }
  59443. return this._size;
  59444. };
  59445. RenderTargetTexture.prototype.getRenderHeight = function () {
  59446. if (this._size.width) {
  59447. return this._size.height;
  59448. }
  59449. return this._size;
  59450. };
  59451. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  59452. get: function () {
  59453. return true;
  59454. },
  59455. enumerable: true,
  59456. configurable: true
  59457. });
  59458. RenderTargetTexture.prototype.scale = function (ratio) {
  59459. var newSize = this.getRenderSize() * ratio;
  59460. this.resize(newSize);
  59461. };
  59462. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  59463. if (this.isCube) {
  59464. return this._textureMatrix;
  59465. }
  59466. return _super.prototype.getReflectionTextureMatrix.call(this);
  59467. };
  59468. RenderTargetTexture.prototype.resize = function (size) {
  59469. this.releaseInternalTexture();
  59470. var scene = this.getScene();
  59471. if (!scene) {
  59472. return;
  59473. }
  59474. this._processSizeParameter(size);
  59475. if (this.isCube) {
  59476. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  59477. }
  59478. else {
  59479. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  59480. }
  59481. };
  59482. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  59483. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  59484. if (dumpForDebug === void 0) { dumpForDebug = false; }
  59485. var scene = this.getScene();
  59486. if (!scene) {
  59487. return;
  59488. }
  59489. var engine = scene.getEngine();
  59490. if (this.useCameraPostProcesses !== undefined) {
  59491. useCameraPostProcess = this.useCameraPostProcesses;
  59492. }
  59493. if (this._waitingRenderList) {
  59494. this.renderList = [];
  59495. for (var index = 0; index < this._waitingRenderList.length; index++) {
  59496. var id = this._waitingRenderList[index];
  59497. var mesh_1 = scene.getMeshByID(id);
  59498. if (mesh_1) {
  59499. this.renderList.push(mesh_1);
  59500. }
  59501. }
  59502. delete this._waitingRenderList;
  59503. }
  59504. // Is predicate defined?
  59505. if (this.renderListPredicate) {
  59506. if (this.renderList) {
  59507. this.renderList.splice(0); // Clear previous renderList
  59508. }
  59509. else {
  59510. this.renderList = [];
  59511. }
  59512. var scene = this.getScene();
  59513. if (!scene) {
  59514. return;
  59515. }
  59516. var sceneMeshes = scene.meshes;
  59517. for (var index = 0; index < sceneMeshes.length; index++) {
  59518. var mesh = sceneMeshes[index];
  59519. if (this.renderListPredicate(mesh)) {
  59520. this.renderList.push(mesh);
  59521. }
  59522. }
  59523. }
  59524. this.onBeforeBindObservable.notifyObservers(this);
  59525. // Set custom projection.
  59526. // Needs to be before binding to prevent changing the aspect ratio.
  59527. var camera;
  59528. if (this.activeCamera) {
  59529. camera = this.activeCamera;
  59530. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59531. if (this.activeCamera !== scene.activeCamera) {
  59532. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  59533. }
  59534. }
  59535. else {
  59536. camera = scene.activeCamera;
  59537. if (camera) {
  59538. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59539. }
  59540. }
  59541. // Prepare renderingManager
  59542. this._renderingManager.reset();
  59543. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  59544. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  59545. var sceneRenderId = scene.getRenderId();
  59546. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  59547. var mesh = currentRenderList[meshIndex];
  59548. if (mesh) {
  59549. if (!mesh.isReady(this.refreshRate === 0)) {
  59550. this.resetRefreshCounter();
  59551. continue;
  59552. }
  59553. mesh._preActivateForIntermediateRendering(sceneRenderId);
  59554. var isMasked = void 0;
  59555. if (!this.renderList && camera) {
  59556. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  59557. }
  59558. else {
  59559. isMasked = false;
  59560. }
  59561. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  59562. mesh._activate(sceneRenderId);
  59563. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  59564. var subMesh = mesh.subMeshes[subIndex];
  59565. scene._activeIndices.addCount(subMesh.indexCount, false);
  59566. this._renderingManager.dispatch(subMesh, mesh);
  59567. }
  59568. }
  59569. }
  59570. }
  59571. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  59572. var particleSystem = scene.particleSystems[particleIndex];
  59573. var emitter = particleSystem.emitter;
  59574. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  59575. continue;
  59576. }
  59577. if (currentRenderList.indexOf(emitter) >= 0) {
  59578. this._renderingManager.dispatchParticles(particleSystem);
  59579. }
  59580. }
  59581. if (this.isCube) {
  59582. for (var face = 0; face < 6; face++) {
  59583. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59584. scene.incrementRenderId();
  59585. scene.resetCachedMaterial();
  59586. }
  59587. }
  59588. else {
  59589. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59590. }
  59591. this.onAfterUnbindObservable.notifyObservers(this);
  59592. if (scene.activeCamera) {
  59593. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  59594. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  59595. }
  59596. engine.setViewport(scene.activeCamera.viewport);
  59597. }
  59598. scene.resetCachedMaterial();
  59599. };
  59600. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  59601. var minimum = 128;
  59602. var x = renderDimension * scale;
  59603. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  59604. // Ensure we don't exceed the render dimension (while staying POT)
  59605. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  59606. };
  59607. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59608. var _this = this;
  59609. if (!this._texture) {
  59610. return;
  59611. }
  59612. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  59613. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59614. });
  59615. };
  59616. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  59617. var scene = this.getScene();
  59618. if (!scene) {
  59619. return;
  59620. }
  59621. var engine = scene.getEngine();
  59622. if (!this._texture) {
  59623. return;
  59624. }
  59625. // Bind
  59626. if (this._postProcessManager) {
  59627. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  59628. }
  59629. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  59630. if (this._texture) {
  59631. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  59632. }
  59633. }
  59634. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  59635. // Clear
  59636. if (this.onClearObservable.hasObservers()) {
  59637. this.onClearObservable.notifyObservers(engine);
  59638. }
  59639. else {
  59640. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  59641. }
  59642. if (!this._doNotChangeAspectRatio) {
  59643. scene.updateTransformMatrix(true);
  59644. }
  59645. // Render
  59646. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  59647. if (this._postProcessManager) {
  59648. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  59649. }
  59650. else if (useCameraPostProcess) {
  59651. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  59652. }
  59653. if (!this._doNotChangeAspectRatio) {
  59654. scene.updateTransformMatrix(true);
  59655. }
  59656. // Dump ?
  59657. if (dumpForDebug) {
  59658. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  59659. }
  59660. // Unbind
  59661. if (!this.isCube || faceIndex === 5) {
  59662. if (this.isCube) {
  59663. if (faceIndex === 5) {
  59664. engine.generateMipMapsForCubemap(this._texture);
  59665. }
  59666. }
  59667. this.unbindFrameBuffer(engine, faceIndex);
  59668. }
  59669. else {
  59670. this.onAfterRenderObservable.notifyObservers(faceIndex);
  59671. }
  59672. };
  59673. /**
  59674. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  59675. * This allowed control for front to back rendering or reversly depending of the special needs.
  59676. *
  59677. * @param renderingGroupId The rendering group id corresponding to its index
  59678. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  59679. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  59680. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  59681. */
  59682. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  59683. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  59684. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  59685. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  59686. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  59687. };
  59688. /**
  59689. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  59690. *
  59691. * @param renderingGroupId The rendering group id corresponding to its index
  59692. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  59693. */
  59694. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  59695. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  59696. };
  59697. RenderTargetTexture.prototype.clone = function () {
  59698. var textureSize = this.getSize();
  59699. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  59700. // Base texture
  59701. newTexture.hasAlpha = this.hasAlpha;
  59702. newTexture.level = this.level;
  59703. // RenderTarget Texture
  59704. newTexture.coordinatesMode = this.coordinatesMode;
  59705. if (this.renderList) {
  59706. newTexture.renderList = this.renderList.slice(0);
  59707. }
  59708. return newTexture;
  59709. };
  59710. RenderTargetTexture.prototype.serialize = function () {
  59711. if (!this.name) {
  59712. return null;
  59713. }
  59714. var serializationObject = _super.prototype.serialize.call(this);
  59715. serializationObject.renderTargetSize = this.getRenderSize();
  59716. serializationObject.renderList = [];
  59717. if (this.renderList) {
  59718. for (var index = 0; index < this.renderList.length; index++) {
  59719. serializationObject.renderList.push(this.renderList[index].id);
  59720. }
  59721. }
  59722. return serializationObject;
  59723. };
  59724. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  59725. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  59726. var objBuffer = this.getInternalTexture();
  59727. var scene = this.getScene();
  59728. if (objBuffer && scene) {
  59729. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  59730. }
  59731. };
  59732. RenderTargetTexture.prototype.dispose = function () {
  59733. if (this._postProcessManager) {
  59734. this._postProcessManager.dispose();
  59735. this._postProcessManager = null;
  59736. }
  59737. this.clearPostProcesses(true);
  59738. if (this._resizeObserver) {
  59739. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  59740. this._resizeObserver = null;
  59741. }
  59742. this.renderList = null;
  59743. // Remove from custom render targets
  59744. var scene = this.getScene();
  59745. if (!scene) {
  59746. return;
  59747. }
  59748. var index = scene.customRenderTargets.indexOf(this);
  59749. if (index >= 0) {
  59750. scene.customRenderTargets.splice(index, 1);
  59751. }
  59752. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  59753. var camera = _a[_i];
  59754. index = camera.customRenderTargets.indexOf(this);
  59755. if (index >= 0) {
  59756. camera.customRenderTargets.splice(index, 1);
  59757. }
  59758. }
  59759. _super.prototype.dispose.call(this);
  59760. };
  59761. RenderTargetTexture.prototype._rebuild = function () {
  59762. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59763. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59764. }
  59765. if (this._postProcessManager) {
  59766. this._postProcessManager._rebuild();
  59767. }
  59768. };
  59769. /**
  59770. * Clear the info related to rendering groups preventing retention point in material dispose.
  59771. */
  59772. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  59773. if (this._renderingManager) {
  59774. this._renderingManager.freeRenderingGroups();
  59775. }
  59776. };
  59777. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  59778. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  59779. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  59780. return RenderTargetTexture;
  59781. }(BABYLON.Texture));
  59782. BABYLON.RenderTargetTexture = RenderTargetTexture;
  59783. })(BABYLON || (BABYLON = {}));
  59784. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  59785. "use strict";
  59786. var BABYLON;
  59787. (function (BABYLON) {
  59788. ;
  59789. var MultiRenderTarget = /** @class */ (function (_super) {
  59790. __extends(MultiRenderTarget, _super);
  59791. function MultiRenderTarget(name, size, count, scene, options) {
  59792. var _this = this;
  59793. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  59794. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  59795. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  59796. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  59797. _this._engine = scene.getEngine();
  59798. if (!_this.isSupported) {
  59799. _this.dispose();
  59800. return;
  59801. }
  59802. var types = [];
  59803. var samplingModes = [];
  59804. for (var i = 0; i < count; i++) {
  59805. if (options && options.types && options.types[i] !== undefined) {
  59806. types.push(options.types[i]);
  59807. }
  59808. else {
  59809. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59810. }
  59811. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  59812. samplingModes.push(options.samplingModes[i]);
  59813. }
  59814. else {
  59815. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59816. }
  59817. }
  59818. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  59819. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  59820. _this._size = size;
  59821. _this._multiRenderTargetOptions = {
  59822. samplingModes: samplingModes,
  59823. generateMipMaps: generateMipMaps,
  59824. generateDepthBuffer: generateDepthBuffer,
  59825. generateStencilBuffer: generateStencilBuffer,
  59826. generateDepthTexture: generateDepthTexture,
  59827. types: types,
  59828. textureCount: count
  59829. };
  59830. _this._createInternalTextures();
  59831. _this._createTextures();
  59832. return _this;
  59833. }
  59834. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  59835. get: function () {
  59836. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  59837. },
  59838. enumerable: true,
  59839. configurable: true
  59840. });
  59841. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  59842. get: function () {
  59843. return this._textures;
  59844. },
  59845. enumerable: true,
  59846. configurable: true
  59847. });
  59848. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  59849. get: function () {
  59850. return this._textures[this._textures.length - 1];
  59851. },
  59852. enumerable: true,
  59853. configurable: true
  59854. });
  59855. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  59856. set: function (wrap) {
  59857. if (this._textures) {
  59858. for (var i = 0; i < this._textures.length; i++) {
  59859. this._textures[i].wrapU = wrap;
  59860. }
  59861. }
  59862. },
  59863. enumerable: true,
  59864. configurable: true
  59865. });
  59866. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  59867. set: function (wrap) {
  59868. if (this._textures) {
  59869. for (var i = 0; i < this._textures.length; i++) {
  59870. this._textures[i].wrapV = wrap;
  59871. }
  59872. }
  59873. },
  59874. enumerable: true,
  59875. configurable: true
  59876. });
  59877. MultiRenderTarget.prototype._rebuild = function () {
  59878. this.releaseInternalTextures();
  59879. this._createInternalTextures();
  59880. for (var i = 0; i < this._internalTextures.length; i++) {
  59881. var texture = this._textures[i];
  59882. texture._texture = this._internalTextures[i];
  59883. }
  59884. // Keeps references to frame buffer and stencil/depth buffer
  59885. this._texture = this._internalTextures[0];
  59886. };
  59887. MultiRenderTarget.prototype._createInternalTextures = function () {
  59888. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  59889. };
  59890. MultiRenderTarget.prototype._createTextures = function () {
  59891. this._textures = [];
  59892. for (var i = 0; i < this._internalTextures.length; i++) {
  59893. var texture = new BABYLON.Texture(null, this.getScene());
  59894. texture._texture = this._internalTextures[i];
  59895. this._textures.push(texture);
  59896. }
  59897. // Keeps references to frame buffer and stencil/depth buffer
  59898. this._texture = this._internalTextures[0];
  59899. };
  59900. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  59901. get: function () {
  59902. return this._samples;
  59903. },
  59904. set: function (value) {
  59905. if (this._samples === value) {
  59906. return;
  59907. }
  59908. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  59909. },
  59910. enumerable: true,
  59911. configurable: true
  59912. });
  59913. MultiRenderTarget.prototype.resize = function (size) {
  59914. this.releaseInternalTextures();
  59915. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  59916. this._createInternalTextures();
  59917. };
  59918. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59919. var _this = this;
  59920. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  59921. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59922. });
  59923. };
  59924. MultiRenderTarget.prototype.dispose = function () {
  59925. this.releaseInternalTextures();
  59926. _super.prototype.dispose.call(this);
  59927. };
  59928. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  59929. if (!this._internalTextures) {
  59930. return;
  59931. }
  59932. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  59933. if (this._internalTextures[i] !== undefined) {
  59934. this._internalTextures[i].dispose();
  59935. this._internalTextures.splice(i, 1);
  59936. }
  59937. }
  59938. };
  59939. return MultiRenderTarget;
  59940. }(BABYLON.RenderTargetTexture));
  59941. BABYLON.MultiRenderTarget = MultiRenderTarget;
  59942. })(BABYLON || (BABYLON = {}));
  59943. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  59944. "use strict";
  59945. var BABYLON;
  59946. (function (BABYLON) {
  59947. var MirrorTexture = /** @class */ (function (_super) {
  59948. __extends(MirrorTexture, _super);
  59949. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  59950. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59951. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59952. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59953. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  59954. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  59955. _this._transformMatrix = BABYLON.Matrix.Zero();
  59956. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59957. _this._adaptiveBlurKernel = 0;
  59958. _this._blurKernelX = 0;
  59959. _this._blurKernelY = 0;
  59960. _this._blurRatio = 1.0;
  59961. _this.ignoreCameraViewport = true;
  59962. _this.onBeforeRenderObservable.add(function () {
  59963. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59964. _this._savedViewMatrix = scene.getViewMatrix();
  59965. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  59966. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  59967. scene.clipPlane = _this.mirrorPlane;
  59968. scene.getEngine().cullBackFaces = false;
  59969. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  59970. });
  59971. _this.onAfterRenderObservable.add(function () {
  59972. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  59973. scene.getEngine().cullBackFaces = true;
  59974. scene._mirroredCameraPosition = null;
  59975. delete scene.clipPlane;
  59976. });
  59977. return _this;
  59978. }
  59979. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  59980. get: function () {
  59981. return this._blurRatio;
  59982. },
  59983. set: function (value) {
  59984. if (this._blurRatio === value) {
  59985. return;
  59986. }
  59987. this._blurRatio = value;
  59988. this._preparePostProcesses();
  59989. },
  59990. enumerable: true,
  59991. configurable: true
  59992. });
  59993. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  59994. set: function (value) {
  59995. this._adaptiveBlurKernel = value;
  59996. this._autoComputeBlurKernel();
  59997. },
  59998. enumerable: true,
  59999. configurable: true
  60000. });
  60001. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  60002. set: function (value) {
  60003. this.blurKernelX = value;
  60004. this.blurKernelY = value;
  60005. },
  60006. enumerable: true,
  60007. configurable: true
  60008. });
  60009. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  60010. get: function () {
  60011. return this._blurKernelX;
  60012. },
  60013. set: function (value) {
  60014. if (this._blurKernelX === value) {
  60015. return;
  60016. }
  60017. this._blurKernelX = value;
  60018. this._preparePostProcesses();
  60019. },
  60020. enumerable: true,
  60021. configurable: true
  60022. });
  60023. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  60024. get: function () {
  60025. return this._blurKernelY;
  60026. },
  60027. set: function (value) {
  60028. if (this._blurKernelY === value) {
  60029. return;
  60030. }
  60031. this._blurKernelY = value;
  60032. this._preparePostProcesses();
  60033. },
  60034. enumerable: true,
  60035. configurable: true
  60036. });
  60037. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  60038. var engine = this.getScene().getEngine();
  60039. var dw = this.getRenderWidth() / engine.getRenderWidth();
  60040. var dh = this.getRenderHeight() / engine.getRenderHeight();
  60041. this.blurKernelX = this._adaptiveBlurKernel * dw;
  60042. this.blurKernelY = this._adaptiveBlurKernel * dh;
  60043. };
  60044. MirrorTexture.prototype._onRatioRescale = function () {
  60045. if (this._sizeRatio) {
  60046. this.resize(this._initialSizeParameter);
  60047. if (!this._adaptiveBlurKernel) {
  60048. this._preparePostProcesses();
  60049. }
  60050. }
  60051. if (this._adaptiveBlurKernel) {
  60052. this._autoComputeBlurKernel();
  60053. }
  60054. };
  60055. MirrorTexture.prototype._preparePostProcesses = function () {
  60056. this.clearPostProcesses(true);
  60057. if (this._blurKernelX && this._blurKernelY) {
  60058. var engine = this.getScene().getEngine();
  60059. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60060. 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);
  60061. this._blurX.autoClear = false;
  60062. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  60063. this._blurX.inputTexture = this._texture;
  60064. }
  60065. else {
  60066. this._blurX.alwaysForcePOT = true;
  60067. }
  60068. 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);
  60069. this._blurY.autoClear = false;
  60070. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  60071. this.addPostProcess(this._blurX);
  60072. this.addPostProcess(this._blurY);
  60073. }
  60074. else {
  60075. if (this._blurY) {
  60076. this.removePostProcess(this._blurY);
  60077. this._blurY.dispose();
  60078. this._blurY = null;
  60079. }
  60080. if (this._blurX) {
  60081. this.removePostProcess(this._blurX);
  60082. this._blurX.dispose();
  60083. this._blurX = null;
  60084. }
  60085. }
  60086. };
  60087. MirrorTexture.prototype.clone = function () {
  60088. var scene = this.getScene();
  60089. if (!scene) {
  60090. return this;
  60091. }
  60092. var textureSize = this.getSize();
  60093. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  60094. // Base texture
  60095. newTexture.hasAlpha = this.hasAlpha;
  60096. newTexture.level = this.level;
  60097. // Mirror Texture
  60098. newTexture.mirrorPlane = this.mirrorPlane.clone();
  60099. if (this.renderList) {
  60100. newTexture.renderList = this.renderList.slice(0);
  60101. }
  60102. return newTexture;
  60103. };
  60104. MirrorTexture.prototype.serialize = function () {
  60105. if (!this.name) {
  60106. return null;
  60107. }
  60108. var serializationObject = _super.prototype.serialize.call(this);
  60109. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  60110. return serializationObject;
  60111. };
  60112. return MirrorTexture;
  60113. }(BABYLON.RenderTargetTexture));
  60114. BABYLON.MirrorTexture = MirrorTexture;
  60115. })(BABYLON || (BABYLON = {}));
  60116. //# sourceMappingURL=babylon.mirrorTexture.js.map
  60117. "use strict";
  60118. var BABYLON;
  60119. (function (BABYLON) {
  60120. /**
  60121. * Creates a refraction texture used by refraction channel of the standard material.
  60122. * @param name the texture name
  60123. * @param size size of the underlying texture
  60124. * @param scene root scene
  60125. */
  60126. var RefractionTexture = /** @class */ (function (_super) {
  60127. __extends(RefractionTexture, _super);
  60128. function RefractionTexture(name, size, scene, generateMipMaps) {
  60129. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  60130. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  60131. _this.depth = 2.0;
  60132. _this.onBeforeRenderObservable.add(function () {
  60133. scene.clipPlane = _this.refractionPlane;
  60134. });
  60135. _this.onAfterRenderObservable.add(function () {
  60136. delete scene.clipPlane;
  60137. });
  60138. return _this;
  60139. }
  60140. RefractionTexture.prototype.clone = function () {
  60141. var scene = this.getScene();
  60142. if (!scene) {
  60143. return this;
  60144. }
  60145. var textureSize = this.getSize();
  60146. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  60147. // Base texture
  60148. newTexture.hasAlpha = this.hasAlpha;
  60149. newTexture.level = this.level;
  60150. // Refraction Texture
  60151. newTexture.refractionPlane = this.refractionPlane.clone();
  60152. if (this.renderList) {
  60153. newTexture.renderList = this.renderList.slice(0);
  60154. }
  60155. newTexture.depth = this.depth;
  60156. return newTexture;
  60157. };
  60158. RefractionTexture.prototype.serialize = function () {
  60159. if (!this.name) {
  60160. return null;
  60161. }
  60162. var serializationObject = _super.prototype.serialize.call(this);
  60163. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  60164. serializationObject.depth = this.depth;
  60165. return serializationObject;
  60166. };
  60167. return RefractionTexture;
  60168. }(BABYLON.RenderTargetTexture));
  60169. BABYLON.RefractionTexture = RefractionTexture;
  60170. })(BABYLON || (BABYLON = {}));
  60171. //# sourceMappingURL=babylon.refractionTexture.js.map
  60172. "use strict";
  60173. var BABYLON;
  60174. (function (BABYLON) {
  60175. /**
  60176. * A class extending {BABYLON.Texture} allowing drawing on a texture
  60177. * @see http://doc.babylonjs.com/how_to/dynamictexture
  60178. */
  60179. var DynamicTexture = /** @class */ (function (_super) {
  60180. __extends(DynamicTexture, _super);
  60181. /**
  60182. * Creates a {BABYLON.DynamicTexture}
  60183. * @param name defines the name of the texture
  60184. * @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
  60185. * @param scene defines the scene where you want the texture
  60186. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  60187. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  60188. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  60189. */
  60190. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  60191. if (scene === void 0) { scene = null; }
  60192. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60193. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  60194. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  60195. _this.name = name;
  60196. _this._engine = _this.getScene().getEngine();
  60197. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60198. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60199. _this._generateMipMaps = generateMipMaps;
  60200. if (options.getContext) {
  60201. _this._canvas = options;
  60202. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  60203. }
  60204. else {
  60205. _this._canvas = document.createElement("canvas");
  60206. if (options.width) {
  60207. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  60208. }
  60209. else {
  60210. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  60211. }
  60212. }
  60213. var textureSize = _this.getSize();
  60214. _this._canvas.width = textureSize.width;
  60215. _this._canvas.height = textureSize.height;
  60216. _this._context = _this._canvas.getContext("2d");
  60217. return _this;
  60218. }
  60219. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  60220. /**
  60221. * Gets the current state of canRescale
  60222. */
  60223. get: function () {
  60224. return true;
  60225. },
  60226. enumerable: true,
  60227. configurable: true
  60228. });
  60229. DynamicTexture.prototype._recreate = function (textureSize) {
  60230. this._canvas.width = textureSize.width;
  60231. this._canvas.height = textureSize.height;
  60232. this.releaseInternalTexture();
  60233. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  60234. };
  60235. /**
  60236. * Scales the texture
  60237. * @param ratio the scale factor to apply to both width and height
  60238. */
  60239. DynamicTexture.prototype.scale = function (ratio) {
  60240. var textureSize = this.getSize();
  60241. textureSize.width *= ratio;
  60242. textureSize.height *= ratio;
  60243. this._recreate(textureSize);
  60244. };
  60245. /**
  60246. * Resizes the texture
  60247. * @param width the new width
  60248. * @param height the new height
  60249. */
  60250. DynamicTexture.prototype.scaleTo = function (width, height) {
  60251. var textureSize = this.getSize();
  60252. textureSize.width = width;
  60253. textureSize.height = height;
  60254. this._recreate(textureSize);
  60255. };
  60256. /**
  60257. * Gets the context of the canvas used by the texture
  60258. * @returns the canvas context of the dynamic texture
  60259. */
  60260. DynamicTexture.prototype.getContext = function () {
  60261. return this._context;
  60262. };
  60263. /**
  60264. * Clears the texture
  60265. */
  60266. DynamicTexture.prototype.clear = function () {
  60267. var size = this.getSize();
  60268. this._context.fillRect(0, 0, size.width, size.height);
  60269. };
  60270. /**
  60271. * Updates the texture
  60272. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  60273. */
  60274. DynamicTexture.prototype.update = function (invertY) {
  60275. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  60276. };
  60277. /**
  60278. * Draws text onto the texture
  60279. * @param text defines the text to be drawn
  60280. * @param x defines the placement of the text from the left
  60281. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  60282. * @param font defines the font to be used with font-style, font-size, font-name
  60283. * @param color defines the color used for the text
  60284. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  60285. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  60286. * @param update defines whether texture is immediately update (default is true)
  60287. */
  60288. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  60289. if (update === void 0) { update = true; }
  60290. var size = this.getSize();
  60291. if (clearColor) {
  60292. this._context.fillStyle = clearColor;
  60293. this._context.fillRect(0, 0, size.width, size.height);
  60294. }
  60295. this._context.font = font;
  60296. if (x === null || x === undefined) {
  60297. var textSize = this._context.measureText(text);
  60298. x = (size.width - textSize.width) / 2;
  60299. }
  60300. if (y === null || y === undefined) {
  60301. var fontSize = parseInt((font.replace(/\D/g, '')));
  60302. ;
  60303. y = (size.height / 2) + (fontSize / 3.65);
  60304. }
  60305. this._context.fillStyle = color;
  60306. this._context.fillText(text, x, y);
  60307. if (update) {
  60308. this.update(invertY);
  60309. }
  60310. };
  60311. /**
  60312. * Clones the texture
  60313. * @returns the clone of the texture.
  60314. */
  60315. DynamicTexture.prototype.clone = function () {
  60316. var scene = this.getScene();
  60317. if (!scene) {
  60318. return this;
  60319. }
  60320. var textureSize = this.getSize();
  60321. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  60322. // Base texture
  60323. newTexture.hasAlpha = this.hasAlpha;
  60324. newTexture.level = this.level;
  60325. // Dynamic Texture
  60326. newTexture.wrapU = this.wrapU;
  60327. newTexture.wrapV = this.wrapV;
  60328. return newTexture;
  60329. };
  60330. /** @ignore */
  60331. DynamicTexture.prototype._rebuild = function () {
  60332. this.update();
  60333. };
  60334. return DynamicTexture;
  60335. }(BABYLON.Texture));
  60336. BABYLON.DynamicTexture = DynamicTexture;
  60337. })(BABYLON || (BABYLON = {}));
  60338. //# sourceMappingURL=babylon.dynamicTexture.js.map
  60339. "use strict";
  60340. var BABYLON;
  60341. (function (BABYLON) {
  60342. var VideoTexture = /** @class */ (function (_super) {
  60343. __extends(VideoTexture, _super);
  60344. /**
  60345. * Creates a video texture.
  60346. * Sample : https://doc.babylonjs.com/how_to/video_texture
  60347. * @param {string | null} name optional name, will detect from video source, if not defined
  60348. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  60349. * @param {BABYLON.Scene} scene is obviously the current scene.
  60350. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  60351. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  60352. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  60353. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  60354. */
  60355. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  60356. if (generateMipMaps === void 0) { generateMipMaps = false; }
  60357. if (invertY === void 0) { invertY = false; }
  60358. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60359. if (settings === void 0) { settings = {
  60360. autoPlay: true,
  60361. loop: true,
  60362. autoUpdateTexture: true,
  60363. }; }
  60364. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60365. _this._createInternalTexture = function () {
  60366. if (_this._texture != null) {
  60367. return;
  60368. }
  60369. if (!_this._engine.needPOTTextures ||
  60370. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  60371. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60372. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60373. }
  60374. else {
  60375. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60376. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60377. _this._generateMipMaps = false;
  60378. }
  60379. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  60380. _this._texture.isReady = true;
  60381. _this._updateInternalTexture();
  60382. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  60383. _this.onLoadObservable.notifyObservers(_this);
  60384. }
  60385. };
  60386. _this.reset = function () {
  60387. if (_this._texture == null) {
  60388. return;
  60389. }
  60390. _this._texture.dispose();
  60391. _this._texture = null;
  60392. };
  60393. _this._updateInternalTexture = function (e) {
  60394. if (_this._texture == null || !_this._texture.isReady) {
  60395. return;
  60396. }
  60397. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  60398. return;
  60399. }
  60400. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  60401. };
  60402. _this._engine = _this.getScene().getEngine();
  60403. _this._generateMipMaps = generateMipMaps;
  60404. _this._samplingMode = samplingMode;
  60405. _this.autoUpdateTexture = settings.autoUpdateTexture;
  60406. _this.name = name || _this._getName(src);
  60407. _this.video = _this._getVideo(src);
  60408. if (settings.autoPlay !== undefined) {
  60409. _this.video.autoplay = settings.autoPlay;
  60410. }
  60411. if (settings.loop !== undefined) {
  60412. _this.video.loop = settings.loop;
  60413. }
  60414. _this.video.addEventListener("canplay", _this._createInternalTexture);
  60415. _this.video.addEventListener("paused", _this._updateInternalTexture);
  60416. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  60417. _this.video.addEventListener("emptied", _this.reset);
  60418. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  60419. _this._createInternalTexture();
  60420. }
  60421. return _this;
  60422. }
  60423. VideoTexture.prototype._getName = function (src) {
  60424. if (src instanceof HTMLVideoElement) {
  60425. return src.currentSrc;
  60426. }
  60427. if (typeof src === "object") {
  60428. return src.toString();
  60429. }
  60430. return src;
  60431. };
  60432. ;
  60433. VideoTexture.prototype._getVideo = function (src) {
  60434. if (src instanceof HTMLVideoElement) {
  60435. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  60436. return src;
  60437. }
  60438. var video = document.createElement("video");
  60439. if (typeof src === "string") {
  60440. BABYLON.Tools.SetCorsBehavior(src, video);
  60441. video.src = src;
  60442. }
  60443. else {
  60444. BABYLON.Tools.SetCorsBehavior(src[0], video);
  60445. src.forEach(function (url) {
  60446. var source = document.createElement("source");
  60447. source.src = url;
  60448. video.appendChild(source);
  60449. });
  60450. }
  60451. return video;
  60452. };
  60453. ;
  60454. /**
  60455. * Internal method to initiate `update`.
  60456. */
  60457. VideoTexture.prototype._rebuild = function () {
  60458. this.update();
  60459. };
  60460. /**
  60461. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  60462. */
  60463. VideoTexture.prototype.update = function () {
  60464. if (!this.autoUpdateTexture) {
  60465. // Expecting user to call `updateTexture` manually
  60466. return;
  60467. }
  60468. this.updateTexture(true);
  60469. };
  60470. /**
  60471. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  60472. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  60473. */
  60474. VideoTexture.prototype.updateTexture = function (isVisible) {
  60475. if (!isVisible) {
  60476. return;
  60477. }
  60478. if (this.video.paused) {
  60479. return;
  60480. }
  60481. this._updateInternalTexture();
  60482. };
  60483. /**
  60484. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  60485. * @param url New url.
  60486. */
  60487. VideoTexture.prototype.updateURL = function (url) {
  60488. this.video.src = url;
  60489. };
  60490. VideoTexture.prototype.dispose = function () {
  60491. _super.prototype.dispose.call(this);
  60492. this.video.removeEventListener("canplay", this._createInternalTexture);
  60493. this.video.removeEventListener("paused", this._updateInternalTexture);
  60494. this.video.removeEventListener("seeked", this._updateInternalTexture);
  60495. this.video.removeEventListener("emptied", this.reset);
  60496. this.video.pause();
  60497. };
  60498. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  60499. var video = document.createElement("video");
  60500. var constraintsDeviceId;
  60501. if (constraints && constraints.deviceId) {
  60502. constraintsDeviceId = {
  60503. exact: constraints.deviceId,
  60504. };
  60505. }
  60506. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  60507. if (navigator.mediaDevices) {
  60508. navigator.mediaDevices.getUserMedia({ video: constraints })
  60509. .then(function (stream) {
  60510. if (video.mozSrcObject !== undefined) {
  60511. // hack for Firefox < 19
  60512. video.mozSrcObject = stream;
  60513. }
  60514. else {
  60515. video.srcObject = stream;
  60516. }
  60517. var onPlaying = function () {
  60518. if (onReady) {
  60519. onReady(new VideoTexture("video", video, scene, true, true));
  60520. }
  60521. video.removeEventListener("playing", onPlaying);
  60522. };
  60523. video.addEventListener("playing", onPlaying);
  60524. video.play();
  60525. })
  60526. .catch(function (err) {
  60527. BABYLON.Tools.Error(err.name);
  60528. });
  60529. }
  60530. else {
  60531. navigator.getUserMedia =
  60532. navigator.getUserMedia ||
  60533. navigator.webkitGetUserMedia ||
  60534. navigator.mozGetUserMedia ||
  60535. navigator.msGetUserMedia;
  60536. if (navigator.getUserMedia) {
  60537. navigator.getUserMedia({
  60538. video: {
  60539. deviceId: constraintsDeviceId,
  60540. width: {
  60541. min: (constraints && constraints.minWidth) || 256,
  60542. max: (constraints && constraints.maxWidth) || 640,
  60543. },
  60544. height: {
  60545. min: (constraints && constraints.minHeight) || 256,
  60546. max: (constraints && constraints.maxHeight) || 480,
  60547. },
  60548. },
  60549. }, function (stream) {
  60550. if (video.mozSrcObject !== undefined) {
  60551. // hack for Firefox < 19
  60552. video.mozSrcObject = stream;
  60553. }
  60554. else {
  60555. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  60556. }
  60557. video.play();
  60558. if (onReady) {
  60559. onReady(new VideoTexture("video", video, scene, true, true));
  60560. }
  60561. }, function (e) {
  60562. BABYLON.Tools.Error(e.name);
  60563. });
  60564. }
  60565. }
  60566. };
  60567. return VideoTexture;
  60568. }(BABYLON.Texture));
  60569. BABYLON.VideoTexture = VideoTexture;
  60570. })(BABYLON || (BABYLON = {}));
  60571. //# sourceMappingURL=babylon.videoTexture.js.map
  60572. "use strict";
  60573. var BABYLON;
  60574. (function (BABYLON) {
  60575. var RawTexture = /** @class */ (function (_super) {
  60576. __extends(RawTexture, _super);
  60577. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  60578. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60579. if (invertY === void 0) { invertY = false; }
  60580. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60581. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60582. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60583. _this.format = format;
  60584. _this._engine = scene.getEngine();
  60585. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  60586. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60587. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60588. return _this;
  60589. }
  60590. RawTexture.prototype.update = function (data) {
  60591. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  60592. };
  60593. // Statics
  60594. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60595. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60596. if (invertY === void 0) { invertY = false; }
  60597. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60598. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  60599. };
  60600. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60601. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60602. if (invertY === void 0) { invertY = false; }
  60603. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60604. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60605. };
  60606. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60607. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60608. if (invertY === void 0) { invertY = false; }
  60609. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60610. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60611. };
  60612. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60613. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60614. if (invertY === void 0) { invertY = false; }
  60615. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60616. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60617. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  60618. };
  60619. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60620. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60621. if (invertY === void 0) { invertY = false; }
  60622. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60623. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60624. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  60625. };
  60626. return RawTexture;
  60627. }(BABYLON.Texture));
  60628. BABYLON.RawTexture = RawTexture;
  60629. })(BABYLON || (BABYLON = {}));
  60630. //# sourceMappingURL=babylon.rawTexture.js.map
  60631. "use strict";
  60632. var BABYLON;
  60633. (function (BABYLON) {
  60634. /**
  60635. * PostProcess can be used to apply a shader to a texture after it has been rendered
  60636. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  60637. */
  60638. var PostProcess = /** @class */ (function () {
  60639. /**
  60640. * Creates a new instance of @see PostProcess
  60641. * @param name The name of the PostProcess.
  60642. * @param fragmentUrl The url of the fragment shader to be used.
  60643. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  60644. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  60645. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  60646. * @param camera The camera to apply the render pass to.
  60647. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  60648. * @param engine The engine which the post process will be applied. (default: current engine)
  60649. * @param reusable If the post process can be reused on the same frame. (default: false)
  60650. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  60651. * @param textureType Type of textures used when performing the post process. (default: 0)
  60652. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  60653. * @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
  60654. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  60655. */
  60656. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  60657. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  60658. if (defines === void 0) { defines = null; }
  60659. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60660. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  60661. if (blockCompilation === void 0) { blockCompilation = false; }
  60662. this.name = name;
  60663. /**
  60664. * Width of the texture to apply the post process on
  60665. */
  60666. this.width = -1;
  60667. /**
  60668. * Height of the texture to apply the post process on
  60669. */
  60670. this.height = -1;
  60671. /**
  60672. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  60673. */
  60674. this._outputTexture = null;
  60675. /**
  60676. * If the buffer needs to be cleared before applying the post process. (default: true)
  60677. * Should be set to false if shader will overwrite all previous pixels.
  60678. */
  60679. this.autoClear = true;
  60680. /**
  60681. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  60682. */
  60683. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  60684. /**
  60685. * Animations to be used for the post processing
  60686. */
  60687. this.animations = new Array();
  60688. /**
  60689. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  60690. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  60691. */
  60692. this.enablePixelPerfectMode = false;
  60693. /**
  60694. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  60695. */
  60696. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  60697. /**
  60698. * Force textures to be a power of two (default: false)
  60699. */
  60700. this.alwaysForcePOT = false;
  60701. /**
  60702. * Number of sample textures (default: 1)
  60703. */
  60704. this.samples = 1;
  60705. /**
  60706. * Modify the scale of the post process to be the same as the viewport (default: false)
  60707. */
  60708. this.adaptScaleToCurrentViewport = false;
  60709. this._reusable = false;
  60710. /**
  60711. * Smart array of input and output textures for the post process.
  60712. */
  60713. this._textures = new BABYLON.SmartArray(2);
  60714. /**
  60715. * The index in _textures that corresponds to the output texture.
  60716. */
  60717. this._currentRenderTextureInd = 0;
  60718. this._scaleRatio = new BABYLON.Vector2(1, 1);
  60719. this._texelSize = BABYLON.Vector2.Zero();
  60720. // Events
  60721. /**
  60722. * An event triggered when the postprocess is activated.
  60723. * @type {BABYLON.Observable}
  60724. */
  60725. this.onActivateObservable = new BABYLON.Observable();
  60726. /**
  60727. * An event triggered when the postprocess changes its size.
  60728. * @type {BABYLON.Observable}
  60729. */
  60730. this.onSizeChangedObservable = new BABYLON.Observable();
  60731. /**
  60732. * An event triggered when the postprocess applies its effect.
  60733. * @type {BABYLON.Observable}
  60734. */
  60735. this.onApplyObservable = new BABYLON.Observable();
  60736. /**
  60737. * An event triggered before rendering the postprocess
  60738. * @type {BABYLON.Observable}
  60739. */
  60740. this.onBeforeRenderObservable = new BABYLON.Observable();
  60741. /**
  60742. * An event triggered after rendering the postprocess
  60743. * @type {BABYLON.Observable}
  60744. */
  60745. this.onAfterRenderObservable = new BABYLON.Observable();
  60746. if (camera != null) {
  60747. this._camera = camera;
  60748. this._scene = camera.getScene();
  60749. camera.attachPostProcess(this);
  60750. this._engine = this._scene.getEngine();
  60751. this._scene.postProcesses.push(this);
  60752. }
  60753. else if (engine) {
  60754. this._engine = engine;
  60755. this._engine.postProcesses.push(this);
  60756. }
  60757. this._options = options;
  60758. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  60759. this._reusable = reusable || false;
  60760. this._textureType = textureType;
  60761. this._samplers = samplers || [];
  60762. this._samplers.push("textureSampler");
  60763. this._fragmentUrl = fragmentUrl;
  60764. this._vertexUrl = vertexUrl;
  60765. this._parameters = parameters || [];
  60766. this._parameters.push("scale");
  60767. this._indexParameters = indexParameters;
  60768. if (!blockCompilation) {
  60769. this.updateEffect(defines);
  60770. }
  60771. }
  60772. Object.defineProperty(PostProcess.prototype, "onActivate", {
  60773. /**
  60774. * A function that is added to the onActivateObservable
  60775. */
  60776. set: function (callback) {
  60777. if (this._onActivateObserver) {
  60778. this.onActivateObservable.remove(this._onActivateObserver);
  60779. }
  60780. if (callback) {
  60781. this._onActivateObserver = this.onActivateObservable.add(callback);
  60782. }
  60783. },
  60784. enumerable: true,
  60785. configurable: true
  60786. });
  60787. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  60788. /**
  60789. * A function that is added to the onSizeChangedObservable
  60790. */
  60791. set: function (callback) {
  60792. if (this._onSizeChangedObserver) {
  60793. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  60794. }
  60795. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  60796. },
  60797. enumerable: true,
  60798. configurable: true
  60799. });
  60800. Object.defineProperty(PostProcess.prototype, "onApply", {
  60801. /**
  60802. * A function that is added to the onApplyObservable
  60803. */
  60804. set: function (callback) {
  60805. if (this._onApplyObserver) {
  60806. this.onApplyObservable.remove(this._onApplyObserver);
  60807. }
  60808. this._onApplyObserver = this.onApplyObservable.add(callback);
  60809. },
  60810. enumerable: true,
  60811. configurable: true
  60812. });
  60813. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  60814. /**
  60815. * A function that is added to the onBeforeRenderObservable
  60816. */
  60817. set: function (callback) {
  60818. if (this._onBeforeRenderObserver) {
  60819. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  60820. }
  60821. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  60822. },
  60823. enumerable: true,
  60824. configurable: true
  60825. });
  60826. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  60827. /**
  60828. * A function that is added to the onAfterRenderObservable
  60829. */
  60830. set: function (callback) {
  60831. if (this._onAfterRenderObserver) {
  60832. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  60833. }
  60834. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  60835. },
  60836. enumerable: true,
  60837. configurable: true
  60838. });
  60839. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  60840. /**
  60841. * 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
  60842. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  60843. */
  60844. get: function () {
  60845. return this._textures.data[this._currentRenderTextureInd];
  60846. },
  60847. set: function (value) {
  60848. this._forcedOutputTexture = value;
  60849. },
  60850. enumerable: true,
  60851. configurable: true
  60852. });
  60853. /**
  60854. * Gets the camera which post process is applied to.
  60855. * @returns The camera the post process is applied to.
  60856. */
  60857. PostProcess.prototype.getCamera = function () {
  60858. return this._camera;
  60859. };
  60860. Object.defineProperty(PostProcess.prototype, "texelSize", {
  60861. /**
  60862. * Gets the texel size of the postprocess.
  60863. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  60864. */
  60865. get: function () {
  60866. if (this._shareOutputWithPostProcess) {
  60867. return this._shareOutputWithPostProcess.texelSize;
  60868. }
  60869. if (this._forcedOutputTexture) {
  60870. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  60871. }
  60872. return this._texelSize;
  60873. },
  60874. enumerable: true,
  60875. configurable: true
  60876. });
  60877. /**
  60878. * Gets the engine which this post process belongs to.
  60879. * @returns The engine the post process was enabled with.
  60880. */
  60881. PostProcess.prototype.getEngine = function () {
  60882. return this._engine;
  60883. };
  60884. /**
  60885. * The effect that is created when initializing the post process.
  60886. * @returns The created effect corrisponding the the postprocess.
  60887. */
  60888. PostProcess.prototype.getEffect = function () {
  60889. return this._effect;
  60890. };
  60891. /**
  60892. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  60893. * @param postProcess The post process to share the output with.
  60894. * @returns This post process.
  60895. */
  60896. PostProcess.prototype.shareOutputWith = function (postProcess) {
  60897. this._disposeTextures();
  60898. this._shareOutputWithPostProcess = postProcess;
  60899. return this;
  60900. };
  60901. /**
  60902. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  60903. * This should be called if the post process that shares output with this post process is disabled/disposed.
  60904. */
  60905. PostProcess.prototype.useOwnOutput = function () {
  60906. if (this._textures.length == 0) {
  60907. this._textures = new BABYLON.SmartArray(2);
  60908. }
  60909. this._shareOutputWithPostProcess = null;
  60910. };
  60911. /**
  60912. * Updates the effect with the current post process compile time values and recompiles the shader.
  60913. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  60914. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  60915. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  60916. * @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
  60917. * @param onCompiled Called when the shader has been compiled.
  60918. * @param onError Called if there is an error when compiling a shader.
  60919. */
  60920. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  60921. if (defines === void 0) { defines = null; }
  60922. if (uniforms === void 0) { uniforms = null; }
  60923. if (samplers === void 0) { samplers = null; }
  60924. 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);
  60925. };
  60926. /**
  60927. * The post process is reusable if it can be used multiple times within one frame.
  60928. * @returns If the post process is reusable
  60929. */
  60930. PostProcess.prototype.isReusable = function () {
  60931. return this._reusable;
  60932. };
  60933. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  60934. PostProcess.prototype.markTextureDirty = function () {
  60935. this.width = -1;
  60936. };
  60937. /**
  60938. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  60939. * 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.
  60940. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  60941. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  60942. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  60943. * @returns The target texture that was bound to be written to.
  60944. */
  60945. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  60946. var _this = this;
  60947. if (sourceTexture === void 0) { sourceTexture = null; }
  60948. camera = camera || this._camera;
  60949. var scene = camera.getScene();
  60950. var engine = scene.getEngine();
  60951. var maxSize = engine.getCaps().maxTextureSize;
  60952. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  60953. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  60954. // 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
  60955. var webVRCamera = camera.parent;
  60956. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  60957. requiredWidth /= 2;
  60958. }
  60959. var desiredWidth = (this._options.width || requiredWidth);
  60960. var desiredHeight = this._options.height || requiredHeight;
  60961. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  60962. if (this.adaptScaleToCurrentViewport) {
  60963. var currentViewport = engine.currentViewport;
  60964. if (currentViewport) {
  60965. desiredWidth *= currentViewport.width;
  60966. desiredHeight *= currentViewport.height;
  60967. }
  60968. }
  60969. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  60970. if (!this._options.width) {
  60971. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  60972. }
  60973. if (!this._options.height) {
  60974. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  60975. }
  60976. }
  60977. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  60978. if (this._textures.length > 0) {
  60979. for (var i = 0; i < this._textures.length; i++) {
  60980. this._engine._releaseTexture(this._textures.data[i]);
  60981. }
  60982. this._textures.reset();
  60983. }
  60984. this.width = desiredWidth;
  60985. this.height = desiredHeight;
  60986. var textureSize = { width: this.width, height: this.height };
  60987. var textureOptions = {
  60988. generateMipMaps: false,
  60989. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  60990. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  60991. samplingMode: this.renderTargetSamplingMode,
  60992. type: this._textureType
  60993. };
  60994. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60995. if (this._reusable) {
  60996. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60997. }
  60998. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  60999. this.onSizeChangedObservable.notifyObservers(this);
  61000. }
  61001. this._textures.forEach(function (texture) {
  61002. if (texture.samples !== _this.samples) {
  61003. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  61004. }
  61005. });
  61006. }
  61007. var target;
  61008. if (this._shareOutputWithPostProcess) {
  61009. target = this._shareOutputWithPostProcess.inputTexture;
  61010. }
  61011. else if (this._forcedOutputTexture) {
  61012. target = this._forcedOutputTexture;
  61013. this.width = this._forcedOutputTexture.width;
  61014. this.height = this._forcedOutputTexture.height;
  61015. }
  61016. else {
  61017. target = this.inputTexture;
  61018. }
  61019. // Bind the input of this post process to be used as the output of the previous post process.
  61020. if (this.enablePixelPerfectMode) {
  61021. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  61022. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  61023. }
  61024. else {
  61025. this._scaleRatio.copyFromFloats(1, 1);
  61026. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  61027. }
  61028. this.onActivateObservable.notifyObservers(camera);
  61029. // Clear
  61030. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  61031. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  61032. }
  61033. if (this._reusable) {
  61034. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  61035. }
  61036. return target;
  61037. };
  61038. Object.defineProperty(PostProcess.prototype, "isSupported", {
  61039. /**
  61040. * If the post process is supported.
  61041. */
  61042. get: function () {
  61043. return this._effect.isSupported;
  61044. },
  61045. enumerable: true,
  61046. configurable: true
  61047. });
  61048. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  61049. /**
  61050. * The aspect ratio of the output texture.
  61051. */
  61052. get: function () {
  61053. if (this._shareOutputWithPostProcess) {
  61054. return this._shareOutputWithPostProcess.aspectRatio;
  61055. }
  61056. if (this._forcedOutputTexture) {
  61057. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  61058. }
  61059. return this.width / this.height;
  61060. },
  61061. enumerable: true,
  61062. configurable: true
  61063. });
  61064. /**
  61065. * Get a value indicating if the post-process is ready to be used
  61066. * @returns true if the post-process is ready (shader is compiled)
  61067. */
  61068. PostProcess.prototype.isReady = function () {
  61069. return this._effect && this._effect.isReady();
  61070. };
  61071. /**
  61072. * Binds all textures and uniforms to the shader, this will be run on every pass.
  61073. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  61074. */
  61075. PostProcess.prototype.apply = function () {
  61076. // Check
  61077. if (!this._effect || !this._effect.isReady())
  61078. return null;
  61079. // States
  61080. this._engine.enableEffect(this._effect);
  61081. this._engine.setState(false);
  61082. this._engine.setDepthBuffer(false);
  61083. this._engine.setDepthWrite(false);
  61084. // Alpha
  61085. this._engine.setAlphaMode(this.alphaMode);
  61086. if (this.alphaConstants) {
  61087. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  61088. }
  61089. // Bind the output texture of the preivous post process as the input to this post process.
  61090. var source;
  61091. if (this._shareOutputWithPostProcess) {
  61092. source = this._shareOutputWithPostProcess.inputTexture;
  61093. }
  61094. else if (this._forcedOutputTexture) {
  61095. source = this._forcedOutputTexture;
  61096. }
  61097. else {
  61098. source = this.inputTexture;
  61099. }
  61100. this._effect._bindTexture("textureSampler", source);
  61101. // Parameters
  61102. this._effect.setVector2("scale", this._scaleRatio);
  61103. this.onApplyObservable.notifyObservers(this._effect);
  61104. return this._effect;
  61105. };
  61106. PostProcess.prototype._disposeTextures = function () {
  61107. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  61108. return;
  61109. }
  61110. if (this._textures.length > 0) {
  61111. for (var i = 0; i < this._textures.length; i++) {
  61112. this._engine._releaseTexture(this._textures.data[i]);
  61113. }
  61114. }
  61115. this._textures.dispose();
  61116. };
  61117. /**
  61118. * Disposes the post process.
  61119. * @param camera The camera to dispose the post process on.
  61120. */
  61121. PostProcess.prototype.dispose = function (camera) {
  61122. camera = camera || this._camera;
  61123. this._disposeTextures();
  61124. if (this._scene) {
  61125. var index_1 = this._scene.postProcesses.indexOf(this);
  61126. if (index_1 !== -1) {
  61127. this._scene.postProcesses.splice(index_1, 1);
  61128. }
  61129. }
  61130. else {
  61131. var index_2 = this._engine.postProcesses.indexOf(this);
  61132. if (index_2 !== -1) {
  61133. this._engine.postProcesses.splice(index_2, 1);
  61134. }
  61135. }
  61136. if (!camera) {
  61137. return;
  61138. }
  61139. camera.detachPostProcess(this);
  61140. var index = camera._postProcesses.indexOf(this);
  61141. if (index === 0 && camera._postProcesses.length > 0) {
  61142. var firstPostProcess = this._camera._getFirstPostProcess();
  61143. if (firstPostProcess) {
  61144. firstPostProcess.markTextureDirty();
  61145. }
  61146. }
  61147. this.onActivateObservable.clear();
  61148. this.onAfterRenderObservable.clear();
  61149. this.onApplyObservable.clear();
  61150. this.onBeforeRenderObservable.clear();
  61151. this.onSizeChangedObservable.clear();
  61152. };
  61153. return PostProcess;
  61154. }());
  61155. BABYLON.PostProcess = PostProcess;
  61156. })(BABYLON || (BABYLON = {}));
  61157. //# sourceMappingURL=babylon.postProcess.js.map
  61158. "use strict";
  61159. var BABYLON;
  61160. (function (BABYLON) {
  61161. var PassPostProcess = /** @class */ (function (_super) {
  61162. __extends(PassPostProcess, _super);
  61163. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  61164. if (camera === void 0) { camera = null; }
  61165. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61166. if (blockCompilation === void 0) { blockCompilation = false; }
  61167. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  61168. }
  61169. return PassPostProcess;
  61170. }(BABYLON.PostProcess));
  61171. BABYLON.PassPostProcess = PassPostProcess;
  61172. })(BABYLON || (BABYLON = {}));
  61173. //# sourceMappingURL=babylon.passPostProcess.js.map
  61174. "use strict";
  61175. var __assign = (this && this.__assign) || Object.assign || function(t) {
  61176. for (var s, i = 1, n = arguments.length; i < n; i++) {
  61177. s = arguments[i];
  61178. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  61179. t[p] = s[p];
  61180. }
  61181. return t;
  61182. };
  61183. var BABYLON;
  61184. (function (BABYLON) {
  61185. /**
  61186. * Default implementation of @see IShadowGenerator.
  61187. * This is the main object responsible of generating shadows in the framework.
  61188. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  61189. */
  61190. var ShadowGenerator = /** @class */ (function () {
  61191. /**
  61192. * Creates a ShadowGenerator object.
  61193. * A ShadowGenerator is the required tool to use the shadows.
  61194. * Each light casting shadows needs to use its own ShadowGenerator.
  61195. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  61196. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  61197. * @param light The light object generating the shadows.
  61198. * @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.
  61199. */
  61200. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  61201. this._bias = 0.00005;
  61202. this._normalBias = 0;
  61203. this._blurBoxOffset = 1;
  61204. this._blurScale = 2;
  61205. this._blurKernel = 1;
  61206. this._useKernelBlur = false;
  61207. this._filter = ShadowGenerator.FILTER_NONE;
  61208. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  61209. this._contactHardeningLightSizeUVRatio = 0.1;
  61210. this._darkness = 0;
  61211. this._transparencyShadow = false;
  61212. /**
  61213. * Controls the extent to which the shadows fade out at the edge of the frustum
  61214. * Used only by directionals and spots
  61215. */
  61216. this.frustumEdgeFalloff = 0;
  61217. /**
  61218. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  61219. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  61220. * It might on the other hand introduce peter panning.
  61221. */
  61222. this.forceBackFacesOnly = false;
  61223. this._lightDirection = BABYLON.Vector3.Zero();
  61224. this._viewMatrix = BABYLON.Matrix.Zero();
  61225. this._projectionMatrix = BABYLON.Matrix.Zero();
  61226. this._transformMatrix = BABYLON.Matrix.Zero();
  61227. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  61228. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  61229. this._currentFaceIndex = 0;
  61230. this._currentFaceIndexCache = 0;
  61231. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  61232. this._mapSize = mapSize;
  61233. this._light = light;
  61234. this._scene = light.getScene();
  61235. light._shadowGenerator = this;
  61236. // Texture type fallback from float to int if not supported.
  61237. var caps = this._scene.getEngine().getCaps();
  61238. if (!useFullFloatFirst) {
  61239. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  61240. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61241. }
  61242. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  61243. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61244. }
  61245. else {
  61246. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61247. }
  61248. }
  61249. else {
  61250. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  61251. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61252. }
  61253. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  61254. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61255. }
  61256. else {
  61257. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61258. }
  61259. }
  61260. this._initializeGenerator();
  61261. this._applyFilterValues();
  61262. }
  61263. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  61264. /**
  61265. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  61266. */
  61267. get: function () {
  61268. return this._bias;
  61269. },
  61270. /**
  61271. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  61272. */
  61273. set: function (bias) {
  61274. this._bias = bias;
  61275. },
  61276. enumerable: true,
  61277. configurable: true
  61278. });
  61279. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  61280. /**
  61281. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  61282. */
  61283. get: function () {
  61284. return this._normalBias;
  61285. },
  61286. /**
  61287. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  61288. */
  61289. set: function (normalBias) {
  61290. this._normalBias = normalBias;
  61291. },
  61292. enumerable: true,
  61293. configurable: true
  61294. });
  61295. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  61296. /**
  61297. * Gets the blur box offset: offset applied during the blur pass.
  61298. * Only usefull if useKernelBlur = false
  61299. */
  61300. get: function () {
  61301. return this._blurBoxOffset;
  61302. },
  61303. /**
  61304. * Sets the blur box offset: offset applied during the blur pass.
  61305. * Only usefull if useKernelBlur = false
  61306. */
  61307. set: function (value) {
  61308. if (this._blurBoxOffset === value) {
  61309. return;
  61310. }
  61311. this._blurBoxOffset = value;
  61312. this._disposeBlurPostProcesses();
  61313. },
  61314. enumerable: true,
  61315. configurable: true
  61316. });
  61317. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  61318. /**
  61319. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  61320. * 2 means half of the size.
  61321. */
  61322. get: function () {
  61323. return this._blurScale;
  61324. },
  61325. /**
  61326. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  61327. * 2 means half of the size.
  61328. */
  61329. set: function (value) {
  61330. if (this._blurScale === value) {
  61331. return;
  61332. }
  61333. this._blurScale = value;
  61334. this._disposeBlurPostProcesses();
  61335. },
  61336. enumerable: true,
  61337. configurable: true
  61338. });
  61339. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  61340. /**
  61341. * Gets the blur kernel: kernel size of the blur pass.
  61342. * Only usefull if useKernelBlur = true
  61343. */
  61344. get: function () {
  61345. return this._blurKernel;
  61346. },
  61347. /**
  61348. * Sets the blur kernel: kernel size of the blur pass.
  61349. * Only usefull if useKernelBlur = true
  61350. */
  61351. set: function (value) {
  61352. if (this._blurKernel === value) {
  61353. return;
  61354. }
  61355. this._blurKernel = value;
  61356. this._disposeBlurPostProcesses();
  61357. },
  61358. enumerable: true,
  61359. configurable: true
  61360. });
  61361. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  61362. /**
  61363. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  61364. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61365. */
  61366. get: function () {
  61367. return this._useKernelBlur;
  61368. },
  61369. /**
  61370. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  61371. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61372. */
  61373. set: function (value) {
  61374. if (this._useKernelBlur === value) {
  61375. return;
  61376. }
  61377. this._useKernelBlur = value;
  61378. this._disposeBlurPostProcesses();
  61379. },
  61380. enumerable: true,
  61381. configurable: true
  61382. });
  61383. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  61384. /**
  61385. * Gets the depth scale used in ESM mode.
  61386. */
  61387. get: function () {
  61388. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  61389. },
  61390. /**
  61391. * Sets the depth scale used in ESM mode.
  61392. * This can override the scale stored on the light.
  61393. */
  61394. set: function (value) {
  61395. this._depthScale = value;
  61396. },
  61397. enumerable: true,
  61398. configurable: true
  61399. });
  61400. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  61401. /**
  61402. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  61403. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61404. */
  61405. get: function () {
  61406. return this._filter;
  61407. },
  61408. /**
  61409. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  61410. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61411. */
  61412. set: function (value) {
  61413. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  61414. if (this._light.needCube()) {
  61415. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61416. this.useExponentialShadowMap = true;
  61417. return;
  61418. }
  61419. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61420. this.useCloseExponentialShadowMap = true;
  61421. return;
  61422. }
  61423. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61424. this.usePoissonSampling = true;
  61425. return;
  61426. }
  61427. }
  61428. // Weblg1 fallback for PCF.
  61429. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61430. if (this._scene.getEngine().webGLVersion === 1) {
  61431. this.usePoissonSampling = true;
  61432. return;
  61433. }
  61434. }
  61435. if (this._filter === value) {
  61436. return;
  61437. }
  61438. this._filter = value;
  61439. this._disposeBlurPostProcesses();
  61440. this._applyFilterValues();
  61441. this._light._markMeshesAsLightDirty();
  61442. },
  61443. enumerable: true,
  61444. configurable: true
  61445. });
  61446. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  61447. /**
  61448. * Gets if the current filter is set to Poisson Sampling.
  61449. */
  61450. get: function () {
  61451. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  61452. },
  61453. /**
  61454. * Sets the current filter to Poisson Sampling.
  61455. */
  61456. set: function (value) {
  61457. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  61458. return;
  61459. }
  61460. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  61461. },
  61462. enumerable: true,
  61463. configurable: true
  61464. });
  61465. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  61466. /**
  61467. * Gets if the current filter is set to VSM.
  61468. * DEPRECATED. Should use useExponentialShadowMap instead.
  61469. */
  61470. get: function () {
  61471. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61472. return this.useExponentialShadowMap;
  61473. },
  61474. /**
  61475. * Sets the current filter is to VSM.
  61476. * DEPRECATED. Should use useExponentialShadowMap instead.
  61477. */
  61478. set: function (value) {
  61479. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61480. this.useExponentialShadowMap = value;
  61481. },
  61482. enumerable: true,
  61483. configurable: true
  61484. });
  61485. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  61486. /**
  61487. * Gets if the current filter is set to blurred VSM.
  61488. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61489. */
  61490. get: function () {
  61491. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61492. return this.useBlurExponentialShadowMap;
  61493. },
  61494. /**
  61495. * Sets the current filter is to blurred VSM.
  61496. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61497. */
  61498. set: function (value) {
  61499. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61500. this.useBlurExponentialShadowMap = value;
  61501. },
  61502. enumerable: true,
  61503. configurable: true
  61504. });
  61505. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  61506. /**
  61507. * Gets if the current filter is set to ESM.
  61508. */
  61509. get: function () {
  61510. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  61511. },
  61512. /**
  61513. * Sets the current filter is to ESM.
  61514. */
  61515. set: function (value) {
  61516. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  61517. return;
  61518. }
  61519. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61520. },
  61521. enumerable: true,
  61522. configurable: true
  61523. });
  61524. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  61525. /**
  61526. * Gets if the current filter is set to filtered ESM.
  61527. */
  61528. get: function () {
  61529. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  61530. },
  61531. /**
  61532. * Gets if the current filter is set to filtered ESM.
  61533. */
  61534. set: function (value) {
  61535. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61536. return;
  61537. }
  61538. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61539. },
  61540. enumerable: true,
  61541. configurable: true
  61542. });
  61543. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  61544. /**
  61545. * Gets if the current filter is set to "close ESM" (using the inverse of the
  61546. * exponential to prevent steep falloff artifacts).
  61547. */
  61548. get: function () {
  61549. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  61550. },
  61551. /**
  61552. * Sets the current filter to "close ESM" (using the inverse of the
  61553. * exponential to prevent steep falloff artifacts).
  61554. */
  61555. set: function (value) {
  61556. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  61557. return;
  61558. }
  61559. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61560. },
  61561. enumerable: true,
  61562. configurable: true
  61563. });
  61564. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  61565. /**
  61566. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  61567. * exponential to prevent steep falloff artifacts).
  61568. */
  61569. get: function () {
  61570. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  61571. },
  61572. /**
  61573. * Sets the current filter to filtered "close ESM" (using the inverse of the
  61574. * exponential to prevent steep falloff artifacts).
  61575. */
  61576. set: function (value) {
  61577. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61578. return;
  61579. }
  61580. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61581. },
  61582. enumerable: true,
  61583. configurable: true
  61584. });
  61585. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  61586. /**
  61587. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  61588. */
  61589. get: function () {
  61590. return this.filter === ShadowGenerator.FILTER_PCF;
  61591. },
  61592. /**
  61593. * Sets the current filter to "PCF" (percentage closer filtering).
  61594. */
  61595. set: function (value) {
  61596. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  61597. return;
  61598. }
  61599. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  61600. },
  61601. enumerable: true,
  61602. configurable: true
  61603. });
  61604. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  61605. /**
  61606. * Gets the PCF or PCSS Quality.
  61607. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61608. */
  61609. get: function () {
  61610. return this._filteringQuality;
  61611. },
  61612. /**
  61613. * Sets the PCF or PCSS Quality.
  61614. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61615. */
  61616. set: function (filteringQuality) {
  61617. this._filteringQuality = filteringQuality;
  61618. },
  61619. enumerable: true,
  61620. configurable: true
  61621. });
  61622. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  61623. /**
  61624. * Gets if the current filter is set to "PCSS" (contact hardening).
  61625. */
  61626. get: function () {
  61627. return this.filter === ShadowGenerator.FILTER_PCSS;
  61628. },
  61629. /**
  61630. * Sets the current filter to "PCSS" (contact hardening).
  61631. */
  61632. set: function (value) {
  61633. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  61634. return;
  61635. }
  61636. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  61637. },
  61638. enumerable: true,
  61639. configurable: true
  61640. });
  61641. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  61642. /**
  61643. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61644. * Using a ratio helps keeping shape stability independently of the map size.
  61645. *
  61646. * It does not account for the light projection as it was having too much
  61647. * instability during the light setup or during light position changes.
  61648. *
  61649. * Only valid if useContactHardeningShadow is true.
  61650. */
  61651. get: function () {
  61652. return this._contactHardeningLightSizeUVRatio;
  61653. },
  61654. /**
  61655. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61656. * Using a ratio helps keeping shape stability independently of the map size.
  61657. *
  61658. * It does not account for the light projection as it was having too much
  61659. * instability during the light setup or during light position changes.
  61660. *
  61661. * Only valid if useContactHardeningShadow is true.
  61662. */
  61663. set: function (contactHardeningLightSizeUVRatio) {
  61664. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  61665. },
  61666. enumerable: true,
  61667. configurable: true
  61668. });
  61669. /**
  61670. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  61671. * 0 means strongest and 1 would means no shadow.
  61672. * @returns the darkness.
  61673. */
  61674. ShadowGenerator.prototype.getDarkness = function () {
  61675. return this._darkness;
  61676. };
  61677. /**
  61678. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  61679. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  61680. * @returns the shadow generator allowing fluent coding.
  61681. */
  61682. ShadowGenerator.prototype.setDarkness = function (darkness) {
  61683. if (darkness >= 1.0)
  61684. this._darkness = 1.0;
  61685. else if (darkness <= 0.0)
  61686. this._darkness = 0.0;
  61687. else
  61688. this._darkness = darkness;
  61689. return this;
  61690. };
  61691. /**
  61692. * Sets the ability to have transparent shadow (boolean).
  61693. * @param transparent True if transparent else False
  61694. * @returns the shadow generator allowing fluent coding
  61695. */
  61696. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  61697. this._transparencyShadow = transparent;
  61698. return this;
  61699. };
  61700. /**
  61701. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  61702. * @returns The render target texture if present otherwise, null
  61703. */
  61704. ShadowGenerator.prototype.getShadowMap = function () {
  61705. return this._shadowMap;
  61706. };
  61707. /**
  61708. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  61709. * @returns The render target texture if the shadow map is present otherwise, null
  61710. */
  61711. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  61712. if (this._shadowMap2) {
  61713. return this._shadowMap2;
  61714. }
  61715. return this._shadowMap;
  61716. };
  61717. /**
  61718. * Helper function to add a mesh and its descendants to the list of shadow casters.
  61719. * @param mesh Mesh to add
  61720. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  61721. * @returns the Shadow Generator itself
  61722. */
  61723. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  61724. if (includeDescendants === void 0) { includeDescendants = true; }
  61725. if (!this._shadowMap) {
  61726. return this;
  61727. }
  61728. if (!this._shadowMap.renderList) {
  61729. this._shadowMap.renderList = [];
  61730. }
  61731. this._shadowMap.renderList.push(mesh);
  61732. if (includeDescendants) {
  61733. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  61734. }
  61735. return this;
  61736. var _a;
  61737. };
  61738. /**
  61739. * Helper function to remove a mesh and its descendants from the list of shadow casters
  61740. * @param mesh Mesh to remove
  61741. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  61742. * @returns the Shadow Generator itself
  61743. */
  61744. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  61745. if (includeDescendants === void 0) { includeDescendants = true; }
  61746. if (!this._shadowMap || !this._shadowMap.renderList) {
  61747. return this;
  61748. }
  61749. var index = this._shadowMap.renderList.indexOf(mesh);
  61750. if (index !== -1) {
  61751. this._shadowMap.renderList.splice(index, 1);
  61752. }
  61753. if (includeDescendants) {
  61754. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  61755. var child = _a[_i];
  61756. this.removeShadowCaster(child);
  61757. }
  61758. }
  61759. return this;
  61760. };
  61761. /**
  61762. * Returns the associated light object.
  61763. * @returns the light generating the shadow
  61764. */
  61765. ShadowGenerator.prototype.getLight = function () {
  61766. return this._light;
  61767. };
  61768. ShadowGenerator.prototype._initializeGenerator = function () {
  61769. this._light._markMeshesAsLightDirty();
  61770. this._initializeShadowMap();
  61771. };
  61772. ShadowGenerator.prototype._initializeShadowMap = function () {
  61773. var _this = this;
  61774. // Render target
  61775. var engine = this._scene.getEngine();
  61776. if (engine.webGLVersion > 1) {
  61777. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  61778. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  61779. }
  61780. else {
  61781. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  61782. }
  61783. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61784. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61785. this._shadowMap.anisotropicFilteringLevel = 1;
  61786. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61787. this._shadowMap.renderParticles = false;
  61788. this._shadowMap.ignoreCameraViewport = true;
  61789. // Record Face Index before render.
  61790. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  61791. _this._currentFaceIndex = faceIndex;
  61792. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61793. engine.setColorWrite(false);
  61794. }
  61795. });
  61796. // Custom render function.
  61797. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  61798. // Blur if required afer render.
  61799. this._shadowMap.onAfterUnbindObservable.add(function () {
  61800. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61801. engine.setColorWrite(true);
  61802. }
  61803. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  61804. return;
  61805. }
  61806. var shadowMap = _this.getShadowMapForRendering();
  61807. if (shadowMap) {
  61808. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  61809. }
  61810. });
  61811. // Clear according to the chosen filter.
  61812. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  61813. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61814. this._shadowMap.onClearObservable.add(function (engine) {
  61815. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61816. engine.clear(clearOne, false, true, false);
  61817. }
  61818. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  61819. engine.clear(clearZero, true, true, false);
  61820. }
  61821. else {
  61822. engine.clear(clearOne, true, true, false);
  61823. }
  61824. });
  61825. };
  61826. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  61827. var _this = this;
  61828. var engine = this._scene.getEngine();
  61829. var targetSize = this._mapSize / this.blurScale;
  61830. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  61831. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  61832. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61833. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61834. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61835. }
  61836. if (this.useKernelBlur) {
  61837. 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);
  61838. this._kernelBlurXPostprocess.width = targetSize;
  61839. this._kernelBlurXPostprocess.height = targetSize;
  61840. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  61841. effect.setTexture("textureSampler", _this._shadowMap);
  61842. });
  61843. 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);
  61844. this._kernelBlurXPostprocess.autoClear = false;
  61845. this._kernelBlurYPostprocess.autoClear = false;
  61846. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61847. this._kernelBlurXPostprocess.packedFloat = true;
  61848. this._kernelBlurYPostprocess.packedFloat = true;
  61849. }
  61850. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  61851. }
  61852. else {
  61853. 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);
  61854. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  61855. effect.setFloat2("screenSize", targetSize, targetSize);
  61856. effect.setTexture("textureSampler", _this._shadowMap);
  61857. });
  61858. this._boxBlurPostprocess.autoClear = false;
  61859. this._blurPostProcesses = [this._boxBlurPostprocess];
  61860. }
  61861. };
  61862. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61863. var index;
  61864. var engine = this._scene.getEngine();
  61865. if (depthOnlySubMeshes.length) {
  61866. engine.setColorWrite(false);
  61867. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61868. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  61869. }
  61870. engine.setColorWrite(true);
  61871. }
  61872. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61873. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  61874. }
  61875. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61876. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  61877. }
  61878. if (this._transparencyShadow) {
  61879. for (index = 0; index < transparentSubMeshes.length; index++) {
  61880. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  61881. }
  61882. }
  61883. };
  61884. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  61885. var _this = this;
  61886. var mesh = subMesh.getRenderingMesh();
  61887. var scene = this._scene;
  61888. var engine = scene.getEngine();
  61889. var material = subMesh.getMaterial();
  61890. if (!material) {
  61891. return;
  61892. }
  61893. // Culling
  61894. engine.setState(material.backFaceCulling);
  61895. // Managing instances
  61896. var batch = mesh._getInstancesRenderList(subMesh._id);
  61897. if (batch.mustReturn) {
  61898. return;
  61899. }
  61900. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  61901. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  61902. engine.enableEffect(this._effect);
  61903. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  61904. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  61905. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  61906. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61907. this._effect.setVector3("lightData", this._cachedDirection);
  61908. }
  61909. else {
  61910. this._effect.setVector3("lightData", this._cachedPosition);
  61911. }
  61912. if (scene.activeCamera) {
  61913. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  61914. }
  61915. // Alpha test
  61916. if (material && material.needAlphaTesting()) {
  61917. var alphaTexture = material.getAlphaTestTexture();
  61918. if (alphaTexture) {
  61919. this._effect.setTexture("diffuseSampler", alphaTexture);
  61920. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  61921. }
  61922. }
  61923. // Bones
  61924. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61925. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  61926. }
  61927. // Morph targets
  61928. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  61929. if (this.forceBackFacesOnly) {
  61930. engine.setState(true, 0, false, true);
  61931. }
  61932. // Draw
  61933. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61934. if (this.forceBackFacesOnly) {
  61935. engine.setState(true, 0, false, false);
  61936. }
  61937. }
  61938. else {
  61939. // Need to reset refresh rate of the shadowMap
  61940. if (this._shadowMap) {
  61941. this._shadowMap.resetRefreshCounter();
  61942. }
  61943. }
  61944. };
  61945. ShadowGenerator.prototype._applyFilterValues = function () {
  61946. if (!this._shadowMap) {
  61947. return;
  61948. }
  61949. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  61950. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61951. }
  61952. else {
  61953. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61954. }
  61955. };
  61956. /**
  61957. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61958. * @param onCompiled Callback triggered at the and of the effects compilation
  61959. * @param options Sets of optional options forcing the compilation with different modes
  61960. */
  61961. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  61962. var _this = this;
  61963. var localOptions = __assign({ useInstances: false }, options);
  61964. var shadowMap = this.getShadowMap();
  61965. if (!shadowMap) {
  61966. if (onCompiled) {
  61967. onCompiled(this);
  61968. }
  61969. return;
  61970. }
  61971. var renderList = shadowMap.renderList;
  61972. if (!renderList) {
  61973. if (onCompiled) {
  61974. onCompiled(this);
  61975. }
  61976. return;
  61977. }
  61978. var subMeshes = new Array();
  61979. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  61980. var mesh = renderList_1[_i];
  61981. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  61982. }
  61983. if (subMeshes.length === 0) {
  61984. if (onCompiled) {
  61985. onCompiled(this);
  61986. }
  61987. return;
  61988. }
  61989. var currentIndex = 0;
  61990. var checkReady = function () {
  61991. if (!_this._scene || !_this._scene.getEngine()) {
  61992. return;
  61993. }
  61994. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  61995. currentIndex++;
  61996. if (currentIndex >= subMeshes.length) {
  61997. if (onCompiled) {
  61998. onCompiled(_this);
  61999. }
  62000. return;
  62001. }
  62002. }
  62003. setTimeout(checkReady, 16);
  62004. };
  62005. checkReady();
  62006. };
  62007. /**
  62008. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  62009. * @param options Sets of optional options forcing the compilation with different modes
  62010. * @returns A promise that resolves when the compilation completes
  62011. */
  62012. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  62013. var _this = this;
  62014. return new Promise(function (resolve) {
  62015. _this.forceCompilation(function () {
  62016. resolve();
  62017. }, options);
  62018. });
  62019. };
  62020. /**
  62021. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  62022. * @param subMesh The submesh we want to render in the shadow map
  62023. * @param useInstances Defines wether will draw in the map using instances
  62024. * @returns true if ready otherwise, false
  62025. */
  62026. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  62027. var defines = [];
  62028. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62029. defines.push("#define FLOAT");
  62030. }
  62031. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  62032. defines.push("#define ESM");
  62033. }
  62034. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  62035. defines.push("#define DEPTHTEXTURE");
  62036. }
  62037. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62038. var mesh = subMesh.getMesh();
  62039. var material = subMesh.getMaterial();
  62040. // Normal bias.
  62041. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  62042. attribs.push(BABYLON.VertexBuffer.NormalKind);
  62043. defines.push("#define NORMAL");
  62044. if (mesh.nonUniformScaling) {
  62045. defines.push("#define NONUNIFORMSCALING");
  62046. }
  62047. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  62048. defines.push("#define DIRECTIONINLIGHTDATA");
  62049. }
  62050. }
  62051. // Alpha test
  62052. if (material && material.needAlphaTesting()) {
  62053. var alphaTexture = material.getAlphaTestTexture();
  62054. if (alphaTexture) {
  62055. defines.push("#define ALPHATEST");
  62056. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62057. attribs.push(BABYLON.VertexBuffer.UVKind);
  62058. defines.push("#define UV1");
  62059. }
  62060. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62061. if (alphaTexture.coordinatesIndex === 1) {
  62062. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62063. defines.push("#define UV2");
  62064. }
  62065. }
  62066. }
  62067. }
  62068. // Bones
  62069. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62070. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62071. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62072. if (mesh.numBoneInfluencers > 4) {
  62073. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62074. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62075. }
  62076. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62077. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  62078. }
  62079. else {
  62080. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62081. }
  62082. // Morph targets
  62083. var manager = mesh.morphTargetManager;
  62084. var morphInfluencers = 0;
  62085. if (manager) {
  62086. if (manager.numInfluencers > 0) {
  62087. defines.push("#define MORPHTARGETS");
  62088. morphInfluencers = manager.numInfluencers;
  62089. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  62090. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  62091. }
  62092. }
  62093. // Instances
  62094. if (useInstances) {
  62095. defines.push("#define INSTANCES");
  62096. attribs.push("world0");
  62097. attribs.push("world1");
  62098. attribs.push("world2");
  62099. attribs.push("world3");
  62100. }
  62101. // Get correct effect
  62102. var join = defines.join("\n");
  62103. if (this._cachedDefines !== join) {
  62104. this._cachedDefines = join;
  62105. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  62106. }
  62107. if (!this._effect.isReady()) {
  62108. return false;
  62109. }
  62110. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  62111. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  62112. this._initializeBlurRTTAndPostProcesses();
  62113. }
  62114. }
  62115. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  62116. return false;
  62117. }
  62118. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  62119. return false;
  62120. }
  62121. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  62122. return false;
  62123. }
  62124. return true;
  62125. };
  62126. /**
  62127. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  62128. * @param defines Defines of the material we want to update
  62129. * @param lightIndex Index of the light in the enabled light list of the material
  62130. */
  62131. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  62132. var scene = this._scene;
  62133. var light = this._light;
  62134. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  62135. return;
  62136. }
  62137. defines["SHADOW" + lightIndex] = true;
  62138. if (this.useContactHardeningShadow) {
  62139. defines["SHADOWPCSS" + lightIndex] = true;
  62140. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  62141. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  62142. }
  62143. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  62144. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  62145. }
  62146. // else default to high.
  62147. }
  62148. if (this.usePercentageCloserFiltering) {
  62149. defines["SHADOWPCF" + lightIndex] = true;
  62150. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  62151. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  62152. }
  62153. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  62154. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  62155. }
  62156. // else default to high.
  62157. }
  62158. else if (this.usePoissonSampling) {
  62159. defines["SHADOWPOISSON" + lightIndex] = true;
  62160. }
  62161. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  62162. defines["SHADOWESM" + lightIndex] = true;
  62163. }
  62164. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  62165. defines["SHADOWCLOSEESM" + lightIndex] = true;
  62166. }
  62167. if (light.needCube()) {
  62168. defines["SHADOWCUBE" + lightIndex] = true;
  62169. }
  62170. };
  62171. /**
  62172. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  62173. * defined in the generator but impacting the effect).
  62174. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  62175. * @param effect The effect we are binfing the information for
  62176. */
  62177. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  62178. var light = this._light;
  62179. var scene = this._scene;
  62180. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  62181. return;
  62182. }
  62183. var camera = scene.activeCamera;
  62184. if (!camera) {
  62185. return;
  62186. }
  62187. var shadowMap = this.getShadowMap();
  62188. if (!shadowMap) {
  62189. return;
  62190. }
  62191. if (!light.needCube()) {
  62192. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  62193. }
  62194. // Only PCF uses depth stencil texture.
  62195. if (this._filter === ShadowGenerator.FILTER_PCF) {
  62196. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62197. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  62198. }
  62199. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  62200. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62201. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  62202. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  62203. }
  62204. else {
  62205. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62206. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  62207. }
  62208. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  62209. };
  62210. /**
  62211. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  62212. * (eq to shadow prjection matrix * light transform matrix)
  62213. * @returns The transform matrix used to create the shadow map
  62214. */
  62215. ShadowGenerator.prototype.getTransformMatrix = function () {
  62216. var scene = this._scene;
  62217. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  62218. return this._transformMatrix;
  62219. }
  62220. this._currentRenderID = scene.getRenderId();
  62221. this._currentFaceIndexCache = this._currentFaceIndex;
  62222. var lightPosition = this._light.position;
  62223. if (this._light.computeTransformedInformation()) {
  62224. lightPosition = this._light.transformedPosition;
  62225. }
  62226. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  62227. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  62228. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  62229. }
  62230. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  62231. this._cachedPosition.copyFrom(lightPosition);
  62232. this._cachedDirection.copyFrom(this._lightDirection);
  62233. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  62234. var shadowMap = this.getShadowMap();
  62235. if (shadowMap) {
  62236. var renderList = shadowMap.renderList;
  62237. if (renderList) {
  62238. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  62239. }
  62240. }
  62241. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  62242. }
  62243. return this._transformMatrix;
  62244. };
  62245. /**
  62246. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  62247. * Cube and 2D textures for instance.
  62248. */
  62249. ShadowGenerator.prototype.recreateShadowMap = function () {
  62250. var shadowMap = this._shadowMap;
  62251. if (!shadowMap) {
  62252. return;
  62253. }
  62254. // Track render list.
  62255. var renderList = shadowMap.renderList;
  62256. // Clean up existing data.
  62257. this._disposeRTTandPostProcesses();
  62258. // Reinitializes.
  62259. this._initializeGenerator();
  62260. // Reaffect the filter to ensure a correct fallback if necessary.
  62261. this.filter = this.filter;
  62262. // Reaffect the filter.
  62263. this._applyFilterValues();
  62264. // Reaffect Render List.
  62265. this._shadowMap.renderList = renderList;
  62266. };
  62267. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  62268. if (this._shadowMap2) {
  62269. this._shadowMap2.dispose();
  62270. this._shadowMap2 = null;
  62271. }
  62272. if (this._boxBlurPostprocess) {
  62273. this._boxBlurPostprocess.dispose();
  62274. this._boxBlurPostprocess = null;
  62275. }
  62276. if (this._kernelBlurXPostprocess) {
  62277. this._kernelBlurXPostprocess.dispose();
  62278. this._kernelBlurXPostprocess = null;
  62279. }
  62280. if (this._kernelBlurYPostprocess) {
  62281. this._kernelBlurYPostprocess.dispose();
  62282. this._kernelBlurYPostprocess = null;
  62283. }
  62284. this._blurPostProcesses = [];
  62285. };
  62286. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  62287. if (this._shadowMap) {
  62288. this._shadowMap.dispose();
  62289. this._shadowMap = null;
  62290. }
  62291. this._disposeBlurPostProcesses();
  62292. };
  62293. /**
  62294. * Disposes the ShadowGenerator.
  62295. * Returns nothing.
  62296. */
  62297. ShadowGenerator.prototype.dispose = function () {
  62298. this._disposeRTTandPostProcesses();
  62299. if (this._light) {
  62300. this._light._shadowGenerator = null;
  62301. this._light._markMeshesAsLightDirty();
  62302. }
  62303. };
  62304. /**
  62305. * Serializes the shadow generator setup to a json object.
  62306. * @returns The serialized JSON object
  62307. */
  62308. ShadowGenerator.prototype.serialize = function () {
  62309. var serializationObject = {};
  62310. var shadowMap = this.getShadowMap();
  62311. if (!shadowMap) {
  62312. return serializationObject;
  62313. }
  62314. serializationObject.lightId = this._light.id;
  62315. serializationObject.mapSize = shadowMap.getRenderSize();
  62316. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  62317. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  62318. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62319. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62320. serializationObject.usePoissonSampling = this.usePoissonSampling;
  62321. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  62322. serializationObject.depthScale = this.depthScale;
  62323. serializationObject.darkness = this.getDarkness();
  62324. serializationObject.blurBoxOffset = this.blurBoxOffset;
  62325. serializationObject.blurKernel = this.blurKernel;
  62326. serializationObject.blurScale = this.blurScale;
  62327. serializationObject.useKernelBlur = this.useKernelBlur;
  62328. serializationObject.transparencyShadow = this._transparencyShadow;
  62329. serializationObject.bias = this.bias;
  62330. serializationObject.normalBias = this.normalBias;
  62331. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  62332. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  62333. serializationObject.filteringQuality = this.filteringQuality;
  62334. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  62335. serializationObject.renderList = [];
  62336. if (shadowMap.renderList) {
  62337. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  62338. var mesh = shadowMap.renderList[meshIndex];
  62339. serializationObject.renderList.push(mesh.id);
  62340. }
  62341. }
  62342. return serializationObject;
  62343. };
  62344. /**
  62345. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  62346. * @param parsedShadowGenerator The JSON object to parse
  62347. * @param scene The scene to create the shadow map for
  62348. * @returns The parsed shadow generator
  62349. */
  62350. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  62351. //casting to point light, as light is missing the position attr and typescript complains.
  62352. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  62353. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  62354. var shadowMap = shadowGenerator.getShadowMap();
  62355. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  62356. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  62357. meshes.forEach(function (mesh) {
  62358. if (!shadowMap) {
  62359. return;
  62360. }
  62361. if (!shadowMap.renderList) {
  62362. shadowMap.renderList = [];
  62363. }
  62364. shadowMap.renderList.push(mesh);
  62365. });
  62366. }
  62367. if (parsedShadowGenerator.usePoissonSampling) {
  62368. shadowGenerator.usePoissonSampling = true;
  62369. }
  62370. else if (parsedShadowGenerator.useExponentialShadowMap) {
  62371. shadowGenerator.useExponentialShadowMap = true;
  62372. }
  62373. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  62374. shadowGenerator.useBlurExponentialShadowMap = true;
  62375. }
  62376. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  62377. shadowGenerator.useCloseExponentialShadowMap = true;
  62378. }
  62379. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  62380. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  62381. }
  62382. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  62383. shadowGenerator.usePercentageCloserFiltering = true;
  62384. }
  62385. else if (parsedShadowGenerator.useContactHardeningShadow) {
  62386. shadowGenerator.useContactHardeningShadow = true;
  62387. }
  62388. if (parsedShadowGenerator.filteringQuality) {
  62389. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  62390. }
  62391. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  62392. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  62393. }
  62394. else if (parsedShadowGenerator.useVarianceShadowMap) {
  62395. shadowGenerator.useExponentialShadowMap = true;
  62396. }
  62397. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  62398. shadowGenerator.useBlurExponentialShadowMap = true;
  62399. }
  62400. if (parsedShadowGenerator.depthScale) {
  62401. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  62402. }
  62403. if (parsedShadowGenerator.blurScale) {
  62404. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  62405. }
  62406. if (parsedShadowGenerator.blurBoxOffset) {
  62407. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  62408. }
  62409. if (parsedShadowGenerator.useKernelBlur) {
  62410. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  62411. }
  62412. if (parsedShadowGenerator.blurKernel) {
  62413. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  62414. }
  62415. if (parsedShadowGenerator.bias !== undefined) {
  62416. shadowGenerator.bias = parsedShadowGenerator.bias;
  62417. }
  62418. if (parsedShadowGenerator.normalBias !== undefined) {
  62419. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  62420. }
  62421. if (parsedShadowGenerator.darkness) {
  62422. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  62423. }
  62424. if (parsedShadowGenerator.transparencyShadow) {
  62425. shadowGenerator.setTransparencyShadow(true);
  62426. }
  62427. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  62428. return shadowGenerator;
  62429. };
  62430. /**
  62431. * Shadow generator mode None: no filtering applied.
  62432. */
  62433. ShadowGenerator.FILTER_NONE = 0;
  62434. /**
  62435. * Shadow generator mode ESM: Exponential Shadow Mapping.
  62436. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62437. */
  62438. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  62439. /**
  62440. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  62441. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  62442. */
  62443. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  62444. /**
  62445. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  62446. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62447. */
  62448. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  62449. /**
  62450. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  62451. * edge artifacts on steep falloff.
  62452. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62453. */
  62454. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  62455. /**
  62456. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  62457. * edge artifacts on steep falloff.
  62458. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62459. */
  62460. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  62461. /**
  62462. * Shadow generator mode PCF: Percentage Closer Filtering
  62463. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62464. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  62465. */
  62466. ShadowGenerator.FILTER_PCF = 6;
  62467. /**
  62468. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  62469. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62470. * Contact Hardening
  62471. */
  62472. ShadowGenerator.FILTER_PCSS = 7;
  62473. /**
  62474. * Reserved for PCF and PCSS
  62475. * Highest Quality.
  62476. *
  62477. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  62478. *
  62479. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  62480. */
  62481. ShadowGenerator.QUALITY_HIGH = 0;
  62482. /**
  62483. * Reserved for PCF and PCSS
  62484. * Good tradeoff for quality/perf cross devices
  62485. *
  62486. * Execute PCF on a 3*3 kernel.
  62487. *
  62488. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  62489. */
  62490. ShadowGenerator.QUALITY_MEDIUM = 1;
  62491. /**
  62492. * Reserved for PCF and PCSS
  62493. * The lowest quality but the fastest.
  62494. *
  62495. * Execute PCF on a 1*1 kernel.
  62496. *
  62497. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  62498. */
  62499. ShadowGenerator.QUALITY_LOW = 2;
  62500. return ShadowGenerator;
  62501. }());
  62502. BABYLON.ShadowGenerator = ShadowGenerator;
  62503. })(BABYLON || (BABYLON = {}));
  62504. //# sourceMappingURL=babylon.shadowGenerator.js.map
  62505. "use strict";
  62506. var BABYLON;
  62507. (function (BABYLON) {
  62508. var DefaultLoadingScreen = /** @class */ (function () {
  62509. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  62510. if (_loadingText === void 0) { _loadingText = ""; }
  62511. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  62512. var _this = this;
  62513. this._renderingCanvas = _renderingCanvas;
  62514. this._loadingText = _loadingText;
  62515. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  62516. // Resize
  62517. this._resizeLoadingUI = function () {
  62518. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  62519. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  62520. if (!_this._loadingDiv) {
  62521. return;
  62522. }
  62523. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  62524. _this._loadingDiv.style.left = canvasRect.left + "px";
  62525. _this._loadingDiv.style.top = canvasRect.top + "px";
  62526. _this._loadingDiv.style.width = canvasRect.width + "px";
  62527. _this._loadingDiv.style.height = canvasRect.height + "px";
  62528. };
  62529. }
  62530. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  62531. if (this._loadingDiv) {
  62532. // Do not add a loading screen if there is already one
  62533. return;
  62534. }
  62535. this._loadingDiv = document.createElement("div");
  62536. this._loadingDiv.id = "babylonjsLoadingDiv";
  62537. this._loadingDiv.style.opacity = "0";
  62538. this._loadingDiv.style.transition = "opacity 1.5s ease";
  62539. this._loadingDiv.style.pointerEvents = "none";
  62540. // Loading text
  62541. this._loadingTextDiv = document.createElement("div");
  62542. this._loadingTextDiv.style.position = "absolute";
  62543. this._loadingTextDiv.style.left = "0";
  62544. this._loadingTextDiv.style.top = "50%";
  62545. this._loadingTextDiv.style.marginTop = "80px";
  62546. this._loadingTextDiv.style.width = "100%";
  62547. this._loadingTextDiv.style.height = "20px";
  62548. this._loadingTextDiv.style.fontFamily = "Arial";
  62549. this._loadingTextDiv.style.fontSize = "14px";
  62550. this._loadingTextDiv.style.color = "white";
  62551. this._loadingTextDiv.style.textAlign = "center";
  62552. this._loadingTextDiv.innerHTML = "Loading";
  62553. this._loadingDiv.appendChild(this._loadingTextDiv);
  62554. //set the predefined text
  62555. this._loadingTextDiv.innerHTML = this._loadingText;
  62556. // Generating keyframes
  62557. var style = document.createElement('style');
  62558. style.type = 'text/css';
  62559. 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 }";
  62560. style.innerHTML = keyFrames;
  62561. document.getElementsByTagName('head')[0].appendChild(style);
  62562. // Loading img
  62563. var imgBack = new Image();
  62564. 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";
  62565. imgBack.style.position = "absolute";
  62566. imgBack.style.left = "50%";
  62567. imgBack.style.top = "50%";
  62568. imgBack.style.marginLeft = "-60px";
  62569. imgBack.style.marginTop = "-60px";
  62570. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  62571. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  62572. imgBack.style.transformOrigin = "50% 50%";
  62573. imgBack.style.webkitTransformOrigin = "50% 50%";
  62574. this._loadingDiv.appendChild(imgBack);
  62575. this._resizeLoadingUI();
  62576. window.addEventListener("resize", this._resizeLoadingUI);
  62577. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62578. document.body.appendChild(this._loadingDiv);
  62579. this._loadingDiv.style.opacity = "1";
  62580. };
  62581. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  62582. var _this = this;
  62583. if (!this._loadingDiv) {
  62584. return;
  62585. }
  62586. var onTransitionEnd = function () {
  62587. if (!_this._loadingDiv) {
  62588. return;
  62589. }
  62590. document.body.removeChild(_this._loadingDiv);
  62591. window.removeEventListener("resize", _this._resizeLoadingUI);
  62592. _this._loadingDiv = null;
  62593. };
  62594. this._loadingDiv.style.opacity = "0";
  62595. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  62596. };
  62597. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  62598. set: function (text) {
  62599. this._loadingText = text;
  62600. if (this._loadingTextDiv) {
  62601. this._loadingTextDiv.innerHTML = this._loadingText;
  62602. }
  62603. },
  62604. enumerable: true,
  62605. configurable: true
  62606. });
  62607. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  62608. get: function () {
  62609. return this._loadingDivBackgroundColor;
  62610. },
  62611. set: function (color) {
  62612. this._loadingDivBackgroundColor = color;
  62613. if (!this._loadingDiv) {
  62614. return;
  62615. }
  62616. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62617. },
  62618. enumerable: true,
  62619. configurable: true
  62620. });
  62621. return DefaultLoadingScreen;
  62622. }());
  62623. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  62624. })(BABYLON || (BABYLON = {}));
  62625. //# sourceMappingURL=babylon.loadingScreen.js.map
  62626. "use strict";
  62627. var BABYLON;
  62628. (function (BABYLON) {
  62629. var SceneLoaderProgressEvent = /** @class */ (function () {
  62630. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  62631. this.lengthComputable = lengthComputable;
  62632. this.loaded = loaded;
  62633. this.total = total;
  62634. }
  62635. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  62636. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  62637. };
  62638. return SceneLoaderProgressEvent;
  62639. }());
  62640. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  62641. var SceneLoader = /** @class */ (function () {
  62642. function SceneLoader() {
  62643. }
  62644. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  62645. get: function () {
  62646. return 0;
  62647. },
  62648. enumerable: true,
  62649. configurable: true
  62650. });
  62651. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  62652. get: function () {
  62653. return 1;
  62654. },
  62655. enumerable: true,
  62656. configurable: true
  62657. });
  62658. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  62659. get: function () {
  62660. return 2;
  62661. },
  62662. enumerable: true,
  62663. configurable: true
  62664. });
  62665. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  62666. get: function () {
  62667. return 3;
  62668. },
  62669. enumerable: true,
  62670. configurable: true
  62671. });
  62672. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  62673. get: function () {
  62674. return SceneLoader._ForceFullSceneLoadingForIncremental;
  62675. },
  62676. set: function (value) {
  62677. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  62678. },
  62679. enumerable: true,
  62680. configurable: true
  62681. });
  62682. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  62683. get: function () {
  62684. return SceneLoader._ShowLoadingScreen;
  62685. },
  62686. set: function (value) {
  62687. SceneLoader._ShowLoadingScreen = value;
  62688. },
  62689. enumerable: true,
  62690. configurable: true
  62691. });
  62692. Object.defineProperty(SceneLoader, "loggingLevel", {
  62693. get: function () {
  62694. return SceneLoader._loggingLevel;
  62695. },
  62696. set: function (value) {
  62697. SceneLoader._loggingLevel = value;
  62698. },
  62699. enumerable: true,
  62700. configurable: true
  62701. });
  62702. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  62703. get: function () {
  62704. return SceneLoader._CleanBoneMatrixWeights;
  62705. },
  62706. set: function (value) {
  62707. SceneLoader._CleanBoneMatrixWeights = value;
  62708. },
  62709. enumerable: true,
  62710. configurable: true
  62711. });
  62712. SceneLoader._getDefaultPlugin = function () {
  62713. return SceneLoader._registeredPlugins[".babylon"];
  62714. };
  62715. SceneLoader._getPluginForExtension = function (extension) {
  62716. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  62717. if (registeredPlugin) {
  62718. return registeredPlugin;
  62719. }
  62720. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  62721. return SceneLoader._getDefaultPlugin();
  62722. };
  62723. SceneLoader._getPluginForDirectLoad = function (data) {
  62724. for (var extension in SceneLoader._registeredPlugins) {
  62725. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  62726. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  62727. return SceneLoader._registeredPlugins[extension];
  62728. }
  62729. }
  62730. return SceneLoader._getDefaultPlugin();
  62731. };
  62732. SceneLoader._getPluginForFilename = function (sceneFilename) {
  62733. if (sceneFilename.name) {
  62734. sceneFilename = sceneFilename.name;
  62735. }
  62736. var queryStringPosition = sceneFilename.indexOf("?");
  62737. if (queryStringPosition !== -1) {
  62738. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  62739. }
  62740. var dotPosition = sceneFilename.lastIndexOf(".");
  62741. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  62742. return SceneLoader._getPluginForExtension(extension);
  62743. };
  62744. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  62745. SceneLoader._getDirectLoad = function (sceneFilename) {
  62746. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  62747. return sceneFilename.substr(5);
  62748. }
  62749. return null;
  62750. };
  62751. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  62752. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  62753. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  62754. var plugin;
  62755. if (registeredPlugin.plugin.createPlugin) {
  62756. plugin = registeredPlugin.plugin.createPlugin();
  62757. }
  62758. else {
  62759. plugin = registeredPlugin.plugin;
  62760. }
  62761. var useArrayBuffer = registeredPlugin.isBinary;
  62762. var database;
  62763. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  62764. var dataCallback = function (data, responseURL) {
  62765. if (scene.isDisposed) {
  62766. onError("Scene has been disposed");
  62767. return;
  62768. }
  62769. scene.database = database;
  62770. onSuccess(plugin, data, responseURL);
  62771. };
  62772. var request = null;
  62773. var pluginDisposed = false;
  62774. var onDisposeObservable = plugin.onDisposeObservable;
  62775. if (onDisposeObservable) {
  62776. onDisposeObservable.add(function () {
  62777. pluginDisposed = true;
  62778. if (request) {
  62779. request.abort();
  62780. request = null;
  62781. }
  62782. onDispose();
  62783. });
  62784. }
  62785. var manifestChecked = function () {
  62786. if (pluginDisposed) {
  62787. return;
  62788. }
  62789. var url = rootUrl + sceneFilename;
  62790. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  62791. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  62792. } : undefined, database, useArrayBuffer, function (request, exception) {
  62793. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  62794. });
  62795. };
  62796. if (directLoad) {
  62797. dataCallback(directLoad);
  62798. return plugin;
  62799. }
  62800. if (rootUrl.indexOf("file:") === -1) {
  62801. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  62802. if (canUseOfflineSupport) {
  62803. // Also check for exceptions
  62804. var exceptionFound = false;
  62805. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  62806. var regex = _a[_i];
  62807. if (regex.test(rootUrl + sceneFilename)) {
  62808. exceptionFound = true;
  62809. break;
  62810. }
  62811. }
  62812. canUseOfflineSupport = !exceptionFound;
  62813. }
  62814. if (canUseOfflineSupport) {
  62815. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  62816. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  62817. }
  62818. else {
  62819. manifestChecked();
  62820. }
  62821. }
  62822. else {
  62823. var fileOrString = sceneFilename;
  62824. if (fileOrString.name) {
  62825. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  62826. }
  62827. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  62828. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  62829. }
  62830. else {
  62831. onError("Unable to find file named " + sceneFilename);
  62832. }
  62833. }
  62834. return plugin;
  62835. };
  62836. // Public functions
  62837. SceneLoader.GetPluginForExtension = function (extension) {
  62838. return SceneLoader._getPluginForExtension(extension).plugin;
  62839. };
  62840. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  62841. return !!SceneLoader._registeredPlugins[extension];
  62842. };
  62843. SceneLoader.RegisterPlugin = function (plugin) {
  62844. if (typeof plugin.extensions === "string") {
  62845. var extension = plugin.extensions;
  62846. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62847. plugin: plugin,
  62848. isBinary: false
  62849. };
  62850. }
  62851. else {
  62852. var extensions = plugin.extensions;
  62853. Object.keys(extensions).forEach(function (extension) {
  62854. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62855. plugin: plugin,
  62856. isBinary: extensions[extension].isBinary
  62857. };
  62858. });
  62859. }
  62860. };
  62861. /**
  62862. * Import meshes into a scene
  62863. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62864. * @param rootUrl a string that defines the root url for scene and resources
  62865. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62866. * @param scene the instance of BABYLON.Scene to append to
  62867. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  62868. * @param onProgress a callback with a progress event for each file being loaded
  62869. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62870. * @param pluginExtension the extension used to determine the plugin
  62871. * @returns The loaded plugin
  62872. */
  62873. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62874. if (onSuccess === void 0) { onSuccess = null; }
  62875. if (onProgress === void 0) { onProgress = null; }
  62876. if (onError === void 0) { onError = null; }
  62877. if (pluginExtension === void 0) { pluginExtension = null; }
  62878. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62879. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62880. return null;
  62881. }
  62882. var loadingToken = {};
  62883. scene._addPendingData(loadingToken);
  62884. var disposeHandler = function () {
  62885. scene._removePendingData(loadingToken);
  62886. };
  62887. var errorHandler = function (message, exception) {
  62888. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  62889. if (onError) {
  62890. onError(scene, errorMessage, exception);
  62891. }
  62892. else {
  62893. BABYLON.Tools.Error(errorMessage);
  62894. // should the exception be thrown?
  62895. }
  62896. disposeHandler();
  62897. };
  62898. var progressHandler = onProgress ? function (event) {
  62899. try {
  62900. onProgress(event);
  62901. }
  62902. catch (e) {
  62903. errorHandler("Error in onProgress callback", e);
  62904. }
  62905. } : undefined;
  62906. var successHandler = function (meshes, particleSystems, skeletons) {
  62907. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  62908. if (onSuccess) {
  62909. try {
  62910. onSuccess(meshes, particleSystems, skeletons);
  62911. }
  62912. catch (e) {
  62913. errorHandler("Error in onSuccess callback", e);
  62914. }
  62915. }
  62916. scene._removePendingData(loadingToken);
  62917. };
  62918. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62919. if (plugin.rewriteRootURL) {
  62920. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  62921. }
  62922. if (sceneFilename === "") {
  62923. if (sceneFilename === "") {
  62924. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62925. }
  62926. }
  62927. if (plugin.importMesh) {
  62928. var syncedPlugin = plugin;
  62929. var meshes = new Array();
  62930. var particleSystems = new Array();
  62931. var skeletons = new Array();
  62932. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  62933. return;
  62934. }
  62935. scene.loadingPluginName = plugin.name;
  62936. successHandler(meshes, particleSystems, skeletons);
  62937. }
  62938. else {
  62939. var asyncedPlugin = plugin;
  62940. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  62941. scene.loadingPluginName = plugin.name;
  62942. successHandler(result.meshes, result.particleSystems, result.skeletons);
  62943. }).catch(function (error) {
  62944. errorHandler(error.message, error);
  62945. });
  62946. }
  62947. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62948. };
  62949. /**
  62950. * Import meshes into a scene
  62951. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62952. * @param rootUrl a string that defines the root url for scene and resources
  62953. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62954. * @param scene the instance of BABYLON.Scene to append to
  62955. * @param onProgress a callback with a progress event for each file being loaded
  62956. * @param pluginExtension the extension used to determine the plugin
  62957. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  62958. */
  62959. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62960. if (onProgress === void 0) { onProgress = null; }
  62961. if (pluginExtension === void 0) { pluginExtension = null; }
  62962. return new Promise(function (resolve, reject) {
  62963. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  62964. resolve({
  62965. meshes: meshes,
  62966. particleSystems: particleSystems,
  62967. skeletons: skeletons
  62968. });
  62969. }, onProgress, function (scene, message, exception) {
  62970. reject(exception || new Error(message));
  62971. });
  62972. });
  62973. };
  62974. /**
  62975. * Load a scene
  62976. * @param rootUrl a string that defines the root url for scene and resources
  62977. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62978. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62979. * @param onSuccess a callback with the scene when import succeeds
  62980. * @param onProgress a callback with a progress event for each file being loaded
  62981. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62982. * @param pluginExtension the extension used to determine the plugin
  62983. * @returns The loaded plugin
  62984. */
  62985. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  62986. if (onSuccess === void 0) { onSuccess = null; }
  62987. if (onProgress === void 0) { onProgress = null; }
  62988. if (onError === void 0) { onError = null; }
  62989. if (pluginExtension === void 0) { pluginExtension = null; }
  62990. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  62991. };
  62992. /**
  62993. * Load a scene
  62994. * @param rootUrl a string that defines the root url for scene and resources
  62995. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62996. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62997. * @param onProgress a callback with a progress event for each file being loaded
  62998. * @param pluginExtension the extension used to determine the plugin
  62999. * @returns The loaded scene
  63000. */
  63001. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  63002. if (onProgress === void 0) { onProgress = null; }
  63003. if (pluginExtension === void 0) { pluginExtension = null; }
  63004. return new Promise(function (resolve, reject) {
  63005. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  63006. resolve(scene);
  63007. }, onProgress, function (scene, message, exception) {
  63008. reject(exception || new Error(message));
  63009. }, pluginExtension);
  63010. });
  63011. };
  63012. /**
  63013. * Append a scene
  63014. * @param rootUrl a string that defines the root url for scene and resources
  63015. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63016. * @param scene is the instance of BABYLON.Scene to append to
  63017. * @param onSuccess a callback with the scene when import succeeds
  63018. * @param onProgress a callback with a progress event for each file being loaded
  63019. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  63020. * @param pluginExtension the extension used to determine the plugin
  63021. * @returns The loaded plugin
  63022. */
  63023. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  63024. if (onSuccess === void 0) { onSuccess = null; }
  63025. if (onProgress === void 0) { onProgress = null; }
  63026. if (onError === void 0) { onError = null; }
  63027. if (pluginExtension === void 0) { pluginExtension = null; }
  63028. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  63029. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  63030. return null;
  63031. }
  63032. if (SceneLoader.ShowLoadingScreen) {
  63033. scene.getEngine().displayLoadingUI();
  63034. }
  63035. var loadingToken = {};
  63036. scene._addPendingData(loadingToken);
  63037. var disposeHandler = function () {
  63038. scene._removePendingData(loadingToken);
  63039. scene.getEngine().hideLoadingUI();
  63040. };
  63041. var errorHandler = function (message, exception) {
  63042. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  63043. if (onError) {
  63044. onError(scene, errorMessage, exception);
  63045. }
  63046. else {
  63047. BABYLON.Tools.Error(errorMessage);
  63048. // should the exception be thrown?
  63049. }
  63050. disposeHandler();
  63051. };
  63052. var progressHandler = onProgress ? function (event) {
  63053. try {
  63054. onProgress(event);
  63055. }
  63056. catch (e) {
  63057. errorHandler("Error in onProgress callback", e);
  63058. }
  63059. } : undefined;
  63060. var successHandler = function () {
  63061. if (onSuccess) {
  63062. try {
  63063. onSuccess(scene);
  63064. }
  63065. catch (e) {
  63066. errorHandler("Error in onSuccess callback", e);
  63067. }
  63068. }
  63069. scene._removePendingData(loadingToken);
  63070. };
  63071. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  63072. if (sceneFilename === "") {
  63073. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  63074. }
  63075. if (plugin.load) {
  63076. var syncedPlugin = plugin;
  63077. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  63078. return;
  63079. }
  63080. scene.loadingPluginName = plugin.name;
  63081. successHandler();
  63082. }
  63083. else {
  63084. var asyncedPlugin = plugin;
  63085. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  63086. scene.loadingPluginName = plugin.name;
  63087. successHandler();
  63088. }).catch(function (error) {
  63089. errorHandler(error.message, error);
  63090. });
  63091. }
  63092. if (SceneLoader.ShowLoadingScreen) {
  63093. scene.executeWhenReady(function () {
  63094. scene.getEngine().hideLoadingUI();
  63095. });
  63096. }
  63097. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  63098. };
  63099. /**
  63100. * Append a scene
  63101. * @param rootUrl a string that defines the root url for scene and resources
  63102. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63103. * @param scene is the instance of BABYLON.Scene to append to
  63104. * @param onProgress a callback with a progress event for each file being loaded
  63105. * @param pluginExtension the extension used to determine the plugin
  63106. * @returns The given scene
  63107. */
  63108. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  63109. if (onProgress === void 0) { onProgress = null; }
  63110. if (pluginExtension === void 0) { pluginExtension = null; }
  63111. return new Promise(function (resolve, reject) {
  63112. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  63113. resolve(scene);
  63114. }, onProgress, function (scene, message, exception) {
  63115. reject(exception || new Error(message));
  63116. }, pluginExtension);
  63117. });
  63118. };
  63119. /**
  63120. * Load a scene into an asset container
  63121. * @param rootUrl a string that defines the root url for scene and resources
  63122. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63123. * @param scene is the instance of BABYLON.Scene to append to
  63124. * @param onSuccess a callback with the scene when import succeeds
  63125. * @param onProgress a callback with a progress event for each file being loaded
  63126. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  63127. * @param pluginExtension the extension used to determine the plugin
  63128. * @returns The loaded plugin
  63129. */
  63130. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  63131. if (onSuccess === void 0) { onSuccess = null; }
  63132. if (onProgress === void 0) { onProgress = null; }
  63133. if (onError === void 0) { onError = null; }
  63134. if (pluginExtension === void 0) { pluginExtension = null; }
  63135. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  63136. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  63137. return null;
  63138. }
  63139. var loadingToken = {};
  63140. scene._addPendingData(loadingToken);
  63141. var disposeHandler = function () {
  63142. scene._removePendingData(loadingToken);
  63143. };
  63144. var errorHandler = function (message, exception) {
  63145. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  63146. if (onError) {
  63147. onError(scene, errorMessage, exception);
  63148. }
  63149. else {
  63150. BABYLON.Tools.Error(errorMessage);
  63151. // should the exception be thrown?
  63152. }
  63153. disposeHandler();
  63154. };
  63155. var progressHandler = onProgress ? function (event) {
  63156. try {
  63157. onProgress(event);
  63158. }
  63159. catch (e) {
  63160. errorHandler("Error in onProgress callback", e);
  63161. }
  63162. } : undefined;
  63163. var successHandler = function (assets) {
  63164. if (onSuccess) {
  63165. try {
  63166. onSuccess(assets);
  63167. }
  63168. catch (e) {
  63169. errorHandler("Error in onSuccess callback", e);
  63170. }
  63171. }
  63172. scene._removePendingData(loadingToken);
  63173. };
  63174. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  63175. if (plugin.loadAssetContainer) {
  63176. var syncedPlugin = plugin;
  63177. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  63178. if (!assetContainer) {
  63179. return;
  63180. }
  63181. scene.loadingPluginName = plugin.name;
  63182. successHandler(assetContainer);
  63183. }
  63184. else if (plugin.loadAssetContainerAsync) {
  63185. var asyncedPlugin = plugin;
  63186. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  63187. scene.loadingPluginName = plugin.name;
  63188. successHandler(assetContainer);
  63189. }).catch(function (error) {
  63190. errorHandler(error.message, error);
  63191. });
  63192. }
  63193. else {
  63194. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  63195. }
  63196. if (SceneLoader.ShowLoadingScreen) {
  63197. scene.executeWhenReady(function () {
  63198. scene.getEngine().hideLoadingUI();
  63199. });
  63200. }
  63201. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  63202. };
  63203. /**
  63204. * Load a scene into an asset container
  63205. * @param rootUrl a string that defines the root url for scene and resources
  63206. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63207. * @param scene is the instance of BABYLON.Scene to append to
  63208. * @param onProgress a callback with a progress event for each file being loaded
  63209. * @param pluginExtension the extension used to determine the plugin
  63210. * @returns The loaded asset container
  63211. */
  63212. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  63213. if (onProgress === void 0) { onProgress = null; }
  63214. if (pluginExtension === void 0) { pluginExtension = null; }
  63215. return new Promise(function (resolve, reject) {
  63216. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  63217. resolve(assetContainer);
  63218. }, onProgress, function (scene, message, exception) {
  63219. reject(exception || new Error(message));
  63220. }, pluginExtension);
  63221. });
  63222. };
  63223. // Flags
  63224. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  63225. SceneLoader._ShowLoadingScreen = true;
  63226. SceneLoader._CleanBoneMatrixWeights = false;
  63227. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  63228. // Members
  63229. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  63230. SceneLoader._registeredPlugins = {};
  63231. return SceneLoader;
  63232. }());
  63233. BABYLON.SceneLoader = SceneLoader;
  63234. ;
  63235. })(BABYLON || (BABYLON = {}));
  63236. //# sourceMappingURL=babylon.sceneLoader.js.map
  63237. "use strict";
  63238. var BABYLON;
  63239. (function (BABYLON) {
  63240. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  63241. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  63242. var parsedMaterial = parsedData.materials[index];
  63243. if (parsedMaterial.id === id) {
  63244. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  63245. }
  63246. }
  63247. return null;
  63248. };
  63249. var isDescendantOf = function (mesh, names, hierarchyIds) {
  63250. for (var i in names) {
  63251. if (mesh.name === names[i]) {
  63252. hierarchyIds.push(mesh.id);
  63253. return true;
  63254. }
  63255. }
  63256. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  63257. hierarchyIds.push(mesh.id);
  63258. return true;
  63259. }
  63260. return false;
  63261. };
  63262. var logOperation = function (operation, producer) {
  63263. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  63264. };
  63265. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  63266. if (addToScene === void 0) { addToScene = false; }
  63267. var container = new BABYLON.AssetContainer(scene);
  63268. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63269. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63270. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63271. // and avoid problems with multiple concurrent .babylon loads.
  63272. var log = "importScene has failed JSON parse";
  63273. try {
  63274. var parsedData = JSON.parse(data);
  63275. log = "";
  63276. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63277. var index;
  63278. var cache;
  63279. // Lights
  63280. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  63281. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  63282. var parsedLight = parsedData.lights[index];
  63283. var light = BABYLON.Light.Parse(parsedLight, scene);
  63284. if (light) {
  63285. container.lights.push(light);
  63286. log += (index === 0 ? "\n\tLights:" : "");
  63287. log += "\n\t\t" + light.toString(fullDetails);
  63288. }
  63289. }
  63290. }
  63291. // Animations
  63292. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  63293. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  63294. var parsedAnimation = parsedData.animations[index];
  63295. var animation = BABYLON.Animation.Parse(parsedAnimation);
  63296. scene.animations.push(animation);
  63297. container.animations.push(animation);
  63298. log += (index === 0 ? "\n\tAnimations:" : "");
  63299. log += "\n\t\t" + animation.toString(fullDetails);
  63300. }
  63301. }
  63302. // Materials
  63303. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  63304. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  63305. var parsedMaterial = parsedData.materials[index];
  63306. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  63307. container.materials.push(mat);
  63308. log += (index === 0 ? "\n\tMaterials:" : "");
  63309. log += "\n\t\t" + mat.toString(fullDetails);
  63310. }
  63311. }
  63312. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63313. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  63314. var parsedMultiMaterial = parsedData.multiMaterials[index];
  63315. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63316. container.multiMaterials.push(mmat);
  63317. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  63318. log += "\n\t\t" + mmat.toString(fullDetails);
  63319. }
  63320. }
  63321. // Morph targets
  63322. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  63323. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  63324. var managerData = _a[_i];
  63325. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  63326. }
  63327. }
  63328. // Skeletons
  63329. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63330. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  63331. var parsedSkeleton = parsedData.skeletons[index];
  63332. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63333. container.skeletons.push(skeleton);
  63334. log += (index === 0 ? "\n\tSkeletons:" : "");
  63335. log += "\n\t\t" + skeleton.toString(fullDetails);
  63336. }
  63337. }
  63338. // Geometries
  63339. var geometries = parsedData.geometries;
  63340. if (geometries !== undefined && geometries !== null) {
  63341. var addedGeometry = new Array();
  63342. // Boxes
  63343. var boxes = geometries.boxes;
  63344. if (boxes !== undefined && boxes !== null) {
  63345. for (index = 0, cache = boxes.length; index < cache; index++) {
  63346. var parsedBox = boxes[index];
  63347. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  63348. }
  63349. }
  63350. // Spheres
  63351. var spheres = geometries.spheres;
  63352. if (spheres !== undefined && spheres !== null) {
  63353. for (index = 0, cache = spheres.length; index < cache; index++) {
  63354. var parsedSphere = spheres[index];
  63355. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  63356. }
  63357. }
  63358. // Cylinders
  63359. var cylinders = geometries.cylinders;
  63360. if (cylinders !== undefined && cylinders !== null) {
  63361. for (index = 0, cache = cylinders.length; index < cache; index++) {
  63362. var parsedCylinder = cylinders[index];
  63363. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  63364. }
  63365. }
  63366. // Toruses
  63367. var toruses = geometries.toruses;
  63368. if (toruses !== undefined && toruses !== null) {
  63369. for (index = 0, cache = toruses.length; index < cache; index++) {
  63370. var parsedTorus = toruses[index];
  63371. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  63372. }
  63373. }
  63374. // Grounds
  63375. var grounds = geometries.grounds;
  63376. if (grounds !== undefined && grounds !== null) {
  63377. for (index = 0, cache = grounds.length; index < cache; index++) {
  63378. var parsedGround = grounds[index];
  63379. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  63380. }
  63381. }
  63382. // Planes
  63383. var planes = geometries.planes;
  63384. if (planes !== undefined && planes !== null) {
  63385. for (index = 0, cache = planes.length; index < cache; index++) {
  63386. var parsedPlane = planes[index];
  63387. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  63388. }
  63389. }
  63390. // TorusKnots
  63391. var torusKnots = geometries.torusKnots;
  63392. if (torusKnots !== undefined && torusKnots !== null) {
  63393. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  63394. var parsedTorusKnot = torusKnots[index];
  63395. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  63396. }
  63397. }
  63398. // VertexData
  63399. var vertexData = geometries.vertexData;
  63400. if (vertexData !== undefined && vertexData !== null) {
  63401. for (index = 0, cache = vertexData.length; index < cache; index++) {
  63402. var parsedVertexData = vertexData[index];
  63403. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  63404. }
  63405. }
  63406. addedGeometry.forEach(function (g) {
  63407. if (g) {
  63408. container.geometries.push(g);
  63409. }
  63410. });
  63411. }
  63412. // Transform nodes
  63413. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  63414. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  63415. var parsedTransformNode = parsedData.transformNodes[index];
  63416. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  63417. container.transformNodes.push(node);
  63418. }
  63419. }
  63420. // Meshes
  63421. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63422. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63423. var parsedMesh = parsedData.meshes[index];
  63424. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63425. container.meshes.push(mesh);
  63426. log += (index === 0 ? "\n\tMeshes:" : "");
  63427. log += "\n\t\t" + mesh.toString(fullDetails);
  63428. }
  63429. }
  63430. // Cameras
  63431. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  63432. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  63433. var parsedCamera = parsedData.cameras[index];
  63434. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  63435. container.cameras.push(camera);
  63436. log += (index === 0 ? "\n\tCameras:" : "");
  63437. log += "\n\t\t" + camera.toString(fullDetails);
  63438. }
  63439. }
  63440. // Browsing all the graph to connect the dots
  63441. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  63442. var camera = scene.cameras[index];
  63443. if (camera._waitingParentId) {
  63444. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  63445. camera._waitingParentId = null;
  63446. }
  63447. }
  63448. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63449. var light_1 = scene.lights[index];
  63450. if (light_1 && light_1._waitingParentId) {
  63451. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  63452. light_1._waitingParentId = null;
  63453. }
  63454. }
  63455. // Sounds
  63456. // TODO: add sound
  63457. var loadedSounds = [];
  63458. var loadedSound;
  63459. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  63460. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  63461. var parsedSound = parsedData.sounds[index];
  63462. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63463. if (!parsedSound.url)
  63464. parsedSound.url = parsedSound.name;
  63465. if (!loadedSounds[parsedSound.url]) {
  63466. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  63467. loadedSounds[parsedSound.url] = loadedSound;
  63468. container.sounds.push(loadedSound);
  63469. }
  63470. else {
  63471. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  63472. }
  63473. }
  63474. else {
  63475. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  63476. }
  63477. }
  63478. }
  63479. loadedSounds = [];
  63480. // Connect parents & children and parse actions
  63481. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  63482. var transformNode = scene.transformNodes[index];
  63483. if (transformNode._waitingParentId) {
  63484. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  63485. transformNode._waitingParentId = null;
  63486. }
  63487. }
  63488. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63489. var mesh = scene.meshes[index];
  63490. if (mesh._waitingParentId) {
  63491. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  63492. mesh._waitingParentId = null;
  63493. }
  63494. if (mesh._waitingActions) {
  63495. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  63496. mesh._waitingActions = null;
  63497. }
  63498. }
  63499. // freeze world matrix application
  63500. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63501. var currentMesh = scene.meshes[index];
  63502. if (currentMesh._waitingFreezeWorldMatrix) {
  63503. currentMesh.freezeWorldMatrix();
  63504. currentMesh._waitingFreezeWorldMatrix = null;
  63505. }
  63506. else {
  63507. currentMesh.computeWorldMatrix(true);
  63508. }
  63509. }
  63510. // Particles Systems
  63511. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63512. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63513. var parsedParticleSystem = parsedData.particleSystems[index];
  63514. if (parsedParticleSystem.activeParticleCount) {
  63515. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63516. container.particleSystems.push(ps);
  63517. }
  63518. else {
  63519. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63520. container.particleSystems.push(ps);
  63521. }
  63522. }
  63523. }
  63524. // Lens flares
  63525. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  63526. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  63527. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  63528. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  63529. container.lensFlareSystems.push(lf);
  63530. }
  63531. }
  63532. // Shadows
  63533. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  63534. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  63535. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  63536. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  63537. container.shadowGenerators.push(sg);
  63538. }
  63539. }
  63540. // Lights exclusions / inclusions
  63541. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63542. var light_2 = scene.lights[index];
  63543. // Excluded check
  63544. if (light_2._excludedMeshesIds.length > 0) {
  63545. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  63546. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  63547. if (excludedMesh) {
  63548. light_2.excludedMeshes.push(excludedMesh);
  63549. }
  63550. }
  63551. light_2._excludedMeshesIds = [];
  63552. }
  63553. // Included check
  63554. if (light_2._includedOnlyMeshesIds.length > 0) {
  63555. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  63556. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  63557. if (includedOnlyMesh) {
  63558. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  63559. }
  63560. }
  63561. light_2._includedOnlyMeshesIds = [];
  63562. }
  63563. }
  63564. // Actions (scene)
  63565. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  63566. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  63567. }
  63568. if (!addToScene) {
  63569. container.removeAllFromScene();
  63570. }
  63571. }
  63572. catch (err) {
  63573. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  63574. if (onError) {
  63575. onError(msg, err);
  63576. }
  63577. else {
  63578. BABYLON.Tools.Log(msg);
  63579. throw err;
  63580. }
  63581. }
  63582. finally {
  63583. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63584. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63585. }
  63586. }
  63587. return container;
  63588. };
  63589. BABYLON.SceneLoader.RegisterPlugin({
  63590. name: "babylon.js",
  63591. extensions: ".babylon",
  63592. canDirectLoad: function (data) {
  63593. if (data.indexOf("babylon") !== -1) {
  63594. return true;
  63595. }
  63596. return false;
  63597. },
  63598. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  63599. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63600. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63601. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63602. // and avoid problems with multiple concurrent .babylon loads.
  63603. var log = "importMesh has failed JSON parse";
  63604. try {
  63605. var parsedData = JSON.parse(data);
  63606. log = "";
  63607. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63608. if (!meshesNames) {
  63609. meshesNames = null;
  63610. }
  63611. else if (!Array.isArray(meshesNames)) {
  63612. meshesNames = [meshesNames];
  63613. }
  63614. var hierarchyIds = new Array();
  63615. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63616. var loadedSkeletonsIds = [];
  63617. var loadedMaterialsIds = [];
  63618. var index;
  63619. var cache;
  63620. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63621. var parsedMesh = parsedData.meshes[index];
  63622. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  63623. if (meshesNames !== null) {
  63624. // Remove found mesh name from list.
  63625. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  63626. }
  63627. //Geometry?
  63628. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  63629. //does the file contain geometries?
  63630. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  63631. //find the correct geometry and add it to the scene
  63632. var found = false;
  63633. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  63634. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  63635. return;
  63636. }
  63637. else {
  63638. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  63639. if (parsedGeometryData.id === parsedMesh.geometryId) {
  63640. switch (geometryType) {
  63641. case "boxes":
  63642. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  63643. break;
  63644. case "spheres":
  63645. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  63646. break;
  63647. case "cylinders":
  63648. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  63649. break;
  63650. case "toruses":
  63651. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  63652. break;
  63653. case "grounds":
  63654. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  63655. break;
  63656. case "planes":
  63657. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  63658. break;
  63659. case "torusKnots":
  63660. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  63661. break;
  63662. case "vertexData":
  63663. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  63664. break;
  63665. }
  63666. found = true;
  63667. }
  63668. });
  63669. }
  63670. });
  63671. if (found === false) {
  63672. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  63673. }
  63674. }
  63675. }
  63676. // Material ?
  63677. if (parsedMesh.materialId) {
  63678. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  63679. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63680. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  63681. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  63682. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  63683. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  63684. var subMatId = parsedMultiMaterial.materials[matIndex];
  63685. loadedMaterialsIds.push(subMatId);
  63686. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  63687. if (mat) {
  63688. log += "\n\tMaterial " + mat.toString(fullDetails);
  63689. }
  63690. }
  63691. loadedMaterialsIds.push(parsedMultiMaterial.id);
  63692. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63693. if (mmat) {
  63694. materialFound = true;
  63695. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  63696. }
  63697. break;
  63698. }
  63699. }
  63700. }
  63701. if (materialFound === false) {
  63702. loadedMaterialsIds.push(parsedMesh.materialId);
  63703. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  63704. if (!mat) {
  63705. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  63706. }
  63707. else {
  63708. log += "\n\tMaterial " + mat.toString(fullDetails);
  63709. }
  63710. }
  63711. }
  63712. // Skeleton ?
  63713. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63714. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  63715. if (skeletonAlreadyLoaded === false) {
  63716. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  63717. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  63718. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  63719. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63720. skeletons.push(skeleton);
  63721. loadedSkeletonsIds.push(parsedSkeleton.id);
  63722. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  63723. }
  63724. }
  63725. }
  63726. }
  63727. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63728. meshes.push(mesh);
  63729. log += "\n\tMesh " + mesh.toString(fullDetails);
  63730. }
  63731. }
  63732. // Connecting parents
  63733. var currentMesh;
  63734. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63735. currentMesh = scene.meshes[index];
  63736. if (currentMesh._waitingParentId) {
  63737. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  63738. currentMesh._waitingParentId = null;
  63739. }
  63740. }
  63741. // freeze and compute world matrix application
  63742. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63743. currentMesh = scene.meshes[index];
  63744. if (currentMesh._waitingFreezeWorldMatrix) {
  63745. currentMesh.freezeWorldMatrix();
  63746. currentMesh._waitingFreezeWorldMatrix = null;
  63747. }
  63748. else {
  63749. currentMesh.computeWorldMatrix(true);
  63750. }
  63751. }
  63752. }
  63753. // Particles
  63754. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63755. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63756. var parsedParticleSystem = parsedData.particleSystems[index];
  63757. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  63758. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  63759. }
  63760. }
  63761. }
  63762. return true;
  63763. }
  63764. catch (err) {
  63765. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  63766. if (onError) {
  63767. onError(msg, err);
  63768. }
  63769. else {
  63770. BABYLON.Tools.Log(msg);
  63771. throw err;
  63772. }
  63773. }
  63774. finally {
  63775. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63776. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63777. }
  63778. }
  63779. return false;
  63780. },
  63781. load: function (scene, data, rootUrl, onError) {
  63782. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63783. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63784. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63785. // and avoid problems with multiple concurrent .babylon loads.
  63786. var log = "importScene has failed JSON parse";
  63787. try {
  63788. var parsedData = JSON.parse(data);
  63789. log = "";
  63790. // Scene
  63791. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  63792. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  63793. }
  63794. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  63795. scene.autoClear = parsedData.autoClear;
  63796. }
  63797. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  63798. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  63799. }
  63800. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  63801. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  63802. }
  63803. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  63804. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  63805. }
  63806. // Fog
  63807. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  63808. scene.fogMode = parsedData.fogMode;
  63809. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  63810. scene.fogStart = parsedData.fogStart;
  63811. scene.fogEnd = parsedData.fogEnd;
  63812. scene.fogDensity = parsedData.fogDensity;
  63813. log += "\tFog mode for scene: ";
  63814. switch (scene.fogMode) {
  63815. // getters not compiling, so using hardcoded
  63816. case 1:
  63817. log += "exp\n";
  63818. break;
  63819. case 2:
  63820. log += "exp2\n";
  63821. break;
  63822. case 3:
  63823. log += "linear\n";
  63824. break;
  63825. }
  63826. }
  63827. //Physics
  63828. if (parsedData.physicsEnabled) {
  63829. var physicsPlugin;
  63830. if (parsedData.physicsEngine === "cannon") {
  63831. physicsPlugin = new BABYLON.CannonJSPlugin();
  63832. }
  63833. else if (parsedData.physicsEngine === "oimo") {
  63834. physicsPlugin = new BABYLON.OimoJSPlugin();
  63835. }
  63836. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  63837. //else - default engine, which is currently oimo
  63838. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  63839. scene.enablePhysics(physicsGravity, physicsPlugin);
  63840. }
  63841. // Metadata
  63842. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  63843. scene.metadata = parsedData.metadata;
  63844. }
  63845. //collisions, if defined. otherwise, default is true
  63846. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  63847. scene.collisionsEnabled = parsedData.collisionsEnabled;
  63848. }
  63849. scene.workerCollisions = !!parsedData.workerCollisions;
  63850. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  63851. if (!container) {
  63852. return false;
  63853. }
  63854. if (parsedData.autoAnimate) {
  63855. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  63856. }
  63857. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  63858. scene.setActiveCameraByID(parsedData.activeCameraID);
  63859. }
  63860. // Environment texture
  63861. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  63862. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  63863. if (parsedData.createDefaultSkybox === true) {
  63864. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  63865. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  63866. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  63867. }
  63868. }
  63869. // Finish
  63870. return true;
  63871. }
  63872. catch (err) {
  63873. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  63874. if (onError) {
  63875. onError(msg, err);
  63876. }
  63877. else {
  63878. BABYLON.Tools.Log(msg);
  63879. throw err;
  63880. }
  63881. }
  63882. finally {
  63883. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63884. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63885. }
  63886. }
  63887. return false;
  63888. },
  63889. loadAssetContainer: function (scene, data, rootUrl, onError) {
  63890. var container = loadAssetContainer(scene, data, rootUrl, onError);
  63891. return container;
  63892. }
  63893. });
  63894. })(BABYLON || (BABYLON = {}));
  63895. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  63896. "use strict";
  63897. var BABYLON;
  63898. (function (BABYLON) {
  63899. var FilesInput = /** @class */ (function () {
  63900. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  63901. this.onProcessFileCallback = function () { return true; };
  63902. this._engine = engine;
  63903. this._currentScene = scene;
  63904. this._sceneLoadedCallback = sceneLoadedCallback;
  63905. this._progressCallback = progressCallback;
  63906. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  63907. this._textureLoadingCallback = textureLoadingCallback;
  63908. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  63909. this._onReloadCallback = onReloadCallback;
  63910. this._errorCallback = errorCallback;
  63911. }
  63912. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  63913. var _this = this;
  63914. if (elementToMonitor) {
  63915. this._elementToMonitor = elementToMonitor;
  63916. this._dragEnterHandler = function (e) { _this.drag(e); };
  63917. this._dragOverHandler = function (e) { _this.drag(e); };
  63918. this._dropHandler = function (e) { _this.drop(e); };
  63919. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  63920. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  63921. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  63922. }
  63923. };
  63924. FilesInput.prototype.dispose = function () {
  63925. if (!this._elementToMonitor) {
  63926. return;
  63927. }
  63928. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  63929. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  63930. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  63931. };
  63932. FilesInput.prototype.renderFunction = function () {
  63933. if (this._additionalRenderLoopLogicCallback) {
  63934. this._additionalRenderLoopLogicCallback();
  63935. }
  63936. if (this._currentScene) {
  63937. if (this._textureLoadingCallback) {
  63938. var remaining = this._currentScene.getWaitingItemsCount();
  63939. if (remaining > 0) {
  63940. this._textureLoadingCallback(remaining);
  63941. }
  63942. }
  63943. this._currentScene.render();
  63944. }
  63945. };
  63946. FilesInput.prototype.drag = function (e) {
  63947. e.stopPropagation();
  63948. e.preventDefault();
  63949. };
  63950. FilesInput.prototype.drop = function (eventDrop) {
  63951. eventDrop.stopPropagation();
  63952. eventDrop.preventDefault();
  63953. this.loadFiles(eventDrop);
  63954. };
  63955. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  63956. var _this = this;
  63957. var reader = folder.createReader();
  63958. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  63959. reader.readEntries(function (entries) {
  63960. remaining.count += entries.length;
  63961. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  63962. var entry = entries_1[_i];
  63963. if (entry.isFile) {
  63964. entry.file(function (file) {
  63965. file.correctName = relativePath + file.name;
  63966. files.push(file);
  63967. if (--remaining.count === 0) {
  63968. callback();
  63969. }
  63970. });
  63971. }
  63972. else if (entry.isDirectory) {
  63973. _this._traverseFolder(entry, files, remaining, callback);
  63974. }
  63975. }
  63976. if (--remaining.count) {
  63977. callback();
  63978. }
  63979. });
  63980. };
  63981. FilesInput.prototype._processFiles = function (files) {
  63982. for (var i = 0; i < files.length; i++) {
  63983. var name = files[i].correctName.toLowerCase();
  63984. var extension = name.split('.').pop();
  63985. if (!this.onProcessFileCallback(files[i], name, extension)) {
  63986. continue;
  63987. }
  63988. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  63989. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  63990. this._sceneFileToLoad = files[i];
  63991. }
  63992. else {
  63993. FilesInput.FilesToLoad[name] = files[i];
  63994. }
  63995. }
  63996. };
  63997. FilesInput.prototype.loadFiles = function (event) {
  63998. var _this = this;
  63999. if (this._startingProcessingFilesCallback)
  64000. this._startingProcessingFilesCallback();
  64001. // Handling data transfer via drag'n'drop
  64002. if (event && event.dataTransfer && event.dataTransfer.files) {
  64003. this._filesToLoad = event.dataTransfer.files;
  64004. }
  64005. // Handling files from input files
  64006. if (event && event.target && event.target.files) {
  64007. this._filesToLoad = event.target.files;
  64008. }
  64009. if (this._filesToLoad && this._filesToLoad.length > 0) {
  64010. var files_1 = new Array();
  64011. var folders = [];
  64012. var items = event.dataTransfer ? event.dataTransfer.items : null;
  64013. for (var i = 0; i < this._filesToLoad.length; i++) {
  64014. var fileToLoad = this._filesToLoad[i];
  64015. var name_1 = fileToLoad.name.toLowerCase();
  64016. var entry = void 0;
  64017. fileToLoad.correctName = name_1;
  64018. if (items) {
  64019. var item = items[i];
  64020. if (item.getAsEntry) {
  64021. entry = item.getAsEntry();
  64022. }
  64023. else if (item.webkitGetAsEntry) {
  64024. entry = item.webkitGetAsEntry();
  64025. }
  64026. }
  64027. if (!entry) {
  64028. files_1.push(fileToLoad);
  64029. }
  64030. else {
  64031. if (entry.isDirectory) {
  64032. folders.push(entry);
  64033. }
  64034. else {
  64035. files_1.push(fileToLoad);
  64036. }
  64037. }
  64038. }
  64039. if (folders.length === 0) {
  64040. this._processFiles(files_1);
  64041. this._processReload();
  64042. }
  64043. else {
  64044. var remaining = { count: folders.length };
  64045. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  64046. var folder = folders_1[_i];
  64047. this._traverseFolder(folder, files_1, remaining, function () {
  64048. _this._processFiles(files_1);
  64049. if (remaining.count === 0) {
  64050. _this._processReload();
  64051. }
  64052. });
  64053. }
  64054. }
  64055. }
  64056. };
  64057. FilesInput.prototype._processReload = function () {
  64058. if (this._onReloadCallback) {
  64059. this._onReloadCallback(this._sceneFileToLoad);
  64060. }
  64061. else {
  64062. this.reload();
  64063. }
  64064. };
  64065. FilesInput.prototype.reload = function () {
  64066. var _this = this;
  64067. // If a scene file has been provided
  64068. if (this._sceneFileToLoad) {
  64069. if (this._currentScene) {
  64070. if (BABYLON.Tools.errorsCount > 0) {
  64071. BABYLON.Tools.ClearLogCache();
  64072. }
  64073. this._engine.stopRenderLoop();
  64074. this._currentScene.dispose();
  64075. }
  64076. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  64077. if (_this._progressCallback) {
  64078. _this._progressCallback(progress);
  64079. }
  64080. }).then(function (scene) {
  64081. _this._currentScene = scene;
  64082. if (_this._sceneLoadedCallback) {
  64083. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  64084. }
  64085. // Wait for textures and shaders to be ready
  64086. _this._currentScene.executeWhenReady(function () {
  64087. _this._engine.runRenderLoop(function () {
  64088. _this.renderFunction();
  64089. });
  64090. });
  64091. }).catch(function (error) {
  64092. if (_this._errorCallback) {
  64093. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  64094. }
  64095. });
  64096. }
  64097. else {
  64098. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  64099. }
  64100. };
  64101. FilesInput.FilesToLoad = {};
  64102. return FilesInput;
  64103. }());
  64104. BABYLON.FilesInput = FilesInput;
  64105. })(BABYLON || (BABYLON = {}));
  64106. //# sourceMappingURL=babylon.filesInput.js.map
  64107. "use strict";
  64108. var BABYLON;
  64109. (function (BABYLON) {
  64110. /**
  64111. * This class implement a typical dictionary using a string as key and the generic type T as value.
  64112. * The underlying implementation relies on an associative array to ensure the best performances.
  64113. * The value can be anything including 'null' but except 'undefined'
  64114. */
  64115. var StringDictionary = /** @class */ (function () {
  64116. function StringDictionary() {
  64117. this._count = 0;
  64118. this._data = {};
  64119. }
  64120. /**
  64121. * This will clear this dictionary and copy the content from the 'source' one.
  64122. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  64123. * @param source the dictionary to take the content from and copy to this dictionary
  64124. */
  64125. StringDictionary.prototype.copyFrom = function (source) {
  64126. var _this = this;
  64127. this.clear();
  64128. source.forEach(function (t, v) { return _this.add(t, v); });
  64129. };
  64130. /**
  64131. * Get a value based from its key
  64132. * @param key the given key to get the matching value from
  64133. * @return the value if found, otherwise undefined is returned
  64134. */
  64135. StringDictionary.prototype.get = function (key) {
  64136. var val = this._data[key];
  64137. if (val !== undefined) {
  64138. return val;
  64139. }
  64140. return undefined;
  64141. };
  64142. /**
  64143. * Get a value from its key or add it if it doesn't exist.
  64144. * This method will ensure you that a given key/data will be present in the dictionary.
  64145. * @param key the given key to get the matching value from
  64146. * @param factory the factory that will create the value if the key is not present in the dictionary.
  64147. * The factory will only be invoked if there's no data for the given key.
  64148. * @return the value corresponding to the key.
  64149. */
  64150. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  64151. var val = this.get(key);
  64152. if (val !== undefined) {
  64153. return val;
  64154. }
  64155. val = factory(key);
  64156. if (val) {
  64157. this.add(key, val);
  64158. }
  64159. return val;
  64160. };
  64161. /**
  64162. * Get a value from its key if present in the dictionary otherwise add it
  64163. * @param key the key to get the value from
  64164. * @param val if there's no such key/value pair in the dictionary add it with this value
  64165. * @return the value corresponding to the key
  64166. */
  64167. StringDictionary.prototype.getOrAdd = function (key, val) {
  64168. var curVal = this.get(key);
  64169. if (curVal !== undefined) {
  64170. return curVal;
  64171. }
  64172. this.add(key, val);
  64173. return val;
  64174. };
  64175. /**
  64176. * Check if there's a given key in the dictionary
  64177. * @param key the key to check for
  64178. * @return true if the key is present, false otherwise
  64179. */
  64180. StringDictionary.prototype.contains = function (key) {
  64181. return this._data[key] !== undefined;
  64182. };
  64183. /**
  64184. * Add a new key and its corresponding value
  64185. * @param key the key to add
  64186. * @param value the value corresponding to the key
  64187. * @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
  64188. */
  64189. StringDictionary.prototype.add = function (key, value) {
  64190. if (this._data[key] !== undefined) {
  64191. return false;
  64192. }
  64193. this._data[key] = value;
  64194. ++this._count;
  64195. return true;
  64196. };
  64197. StringDictionary.prototype.set = function (key, value) {
  64198. if (this._data[key] === undefined) {
  64199. return false;
  64200. }
  64201. this._data[key] = value;
  64202. return true;
  64203. };
  64204. /**
  64205. * Get the element of the given key and remove it from the dictionary
  64206. * @param key
  64207. */
  64208. StringDictionary.prototype.getAndRemove = function (key) {
  64209. var val = this.get(key);
  64210. if (val !== undefined) {
  64211. delete this._data[key];
  64212. --this._count;
  64213. return val;
  64214. }
  64215. return null;
  64216. };
  64217. /**
  64218. * Remove a key/value from the dictionary.
  64219. * @param key the key to remove
  64220. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  64221. */
  64222. StringDictionary.prototype.remove = function (key) {
  64223. if (this.contains(key)) {
  64224. delete this._data[key];
  64225. --this._count;
  64226. return true;
  64227. }
  64228. return false;
  64229. };
  64230. /**
  64231. * Clear the whole content of the dictionary
  64232. */
  64233. StringDictionary.prototype.clear = function () {
  64234. this._data = {};
  64235. this._count = 0;
  64236. };
  64237. Object.defineProperty(StringDictionary.prototype, "count", {
  64238. get: function () {
  64239. return this._count;
  64240. },
  64241. enumerable: true,
  64242. configurable: true
  64243. });
  64244. /**
  64245. * Execute a callback on each key/val of the dictionary.
  64246. * Note that you can remove any element in this dictionary in the callback implementation
  64247. * @param callback the callback to execute on a given key/value pair
  64248. */
  64249. StringDictionary.prototype.forEach = function (callback) {
  64250. for (var cur in this._data) {
  64251. var val = this._data[cur];
  64252. callback(cur, val);
  64253. }
  64254. };
  64255. /**
  64256. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  64257. * If the callback returns null or undefined the method will iterate to the next key/value pair
  64258. * Note that you can remove any element in this dictionary in the callback implementation
  64259. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  64260. */
  64261. StringDictionary.prototype.first = function (callback) {
  64262. for (var cur in this._data) {
  64263. var val = this._data[cur];
  64264. var res = callback(cur, val);
  64265. if (res) {
  64266. return res;
  64267. }
  64268. }
  64269. return null;
  64270. };
  64271. return StringDictionary;
  64272. }());
  64273. BABYLON.StringDictionary = StringDictionary;
  64274. })(BABYLON || (BABYLON = {}));
  64275. //# sourceMappingURL=babylon.stringDictionary.js.map
  64276. "use strict";
  64277. var BABYLON;
  64278. (function (BABYLON) {
  64279. var Tags = /** @class */ (function () {
  64280. function Tags() {
  64281. }
  64282. Tags.EnableFor = function (obj) {
  64283. obj._tags = obj._tags || {};
  64284. obj.hasTags = function () {
  64285. return Tags.HasTags(obj);
  64286. };
  64287. obj.addTags = function (tagsString) {
  64288. return Tags.AddTagsTo(obj, tagsString);
  64289. };
  64290. obj.removeTags = function (tagsString) {
  64291. return Tags.RemoveTagsFrom(obj, tagsString);
  64292. };
  64293. obj.matchesTagsQuery = function (tagsQuery) {
  64294. return Tags.MatchesQuery(obj, tagsQuery);
  64295. };
  64296. };
  64297. Tags.DisableFor = function (obj) {
  64298. delete obj._tags;
  64299. delete obj.hasTags;
  64300. delete obj.addTags;
  64301. delete obj.removeTags;
  64302. delete obj.matchesTagsQuery;
  64303. };
  64304. Tags.HasTags = function (obj) {
  64305. if (!obj._tags) {
  64306. return false;
  64307. }
  64308. return !BABYLON.Tools.IsEmpty(obj._tags);
  64309. };
  64310. Tags.GetTags = function (obj, asString) {
  64311. if (asString === void 0) { asString = true; }
  64312. if (!obj._tags) {
  64313. return null;
  64314. }
  64315. if (asString) {
  64316. var tagsArray = [];
  64317. for (var tag in obj._tags) {
  64318. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  64319. tagsArray.push(tag);
  64320. }
  64321. }
  64322. return tagsArray.join(" ");
  64323. }
  64324. else {
  64325. return obj._tags;
  64326. }
  64327. };
  64328. // the tags 'true' and 'false' are reserved and cannot be used as tags
  64329. // a tag cannot start with '||', '&&', and '!'
  64330. // it cannot contain whitespaces
  64331. Tags.AddTagsTo = function (obj, tagsString) {
  64332. if (!tagsString) {
  64333. return;
  64334. }
  64335. if (typeof tagsString !== "string") {
  64336. return;
  64337. }
  64338. var tags = tagsString.split(" ");
  64339. tags.forEach(function (tag, index, array) {
  64340. Tags._AddTagTo(obj, tag);
  64341. });
  64342. };
  64343. Tags._AddTagTo = function (obj, tag) {
  64344. tag = tag.trim();
  64345. if (tag === "" || tag === "true" || tag === "false") {
  64346. return;
  64347. }
  64348. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  64349. return;
  64350. }
  64351. Tags.EnableFor(obj);
  64352. obj._tags[tag] = true;
  64353. };
  64354. Tags.RemoveTagsFrom = function (obj, tagsString) {
  64355. if (!Tags.HasTags(obj)) {
  64356. return;
  64357. }
  64358. var tags = tagsString.split(" ");
  64359. for (var t in tags) {
  64360. Tags._RemoveTagFrom(obj, tags[t]);
  64361. }
  64362. };
  64363. Tags._RemoveTagFrom = function (obj, tag) {
  64364. delete obj._tags[tag];
  64365. };
  64366. Tags.MatchesQuery = function (obj, tagsQuery) {
  64367. if (tagsQuery === undefined) {
  64368. return true;
  64369. }
  64370. if (tagsQuery === "") {
  64371. return Tags.HasTags(obj);
  64372. }
  64373. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  64374. };
  64375. return Tags;
  64376. }());
  64377. BABYLON.Tags = Tags;
  64378. })(BABYLON || (BABYLON = {}));
  64379. //# sourceMappingURL=babylon.tags.js.map
  64380. "use strict";
  64381. var BABYLON;
  64382. (function (BABYLON) {
  64383. var AndOrNotEvaluator = /** @class */ (function () {
  64384. function AndOrNotEvaluator() {
  64385. }
  64386. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  64387. if (!query.match(/\([^\(\)]*\)/g)) {
  64388. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  64389. }
  64390. else {
  64391. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  64392. // remove parenthesis
  64393. r = r.slice(1, r.length - 1);
  64394. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  64395. });
  64396. }
  64397. if (query === "true") {
  64398. return true;
  64399. }
  64400. if (query === "false") {
  64401. return false;
  64402. }
  64403. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  64404. };
  64405. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  64406. evaluateCallback = evaluateCallback || (function (r) {
  64407. return r === "true" ? true : false;
  64408. });
  64409. var result;
  64410. var or = parenthesisContent.split("||");
  64411. for (var i in or) {
  64412. if (or.hasOwnProperty(i)) {
  64413. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  64414. var and = ori.split("&&");
  64415. if (and.length > 1) {
  64416. for (var j = 0; j < and.length; ++j) {
  64417. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  64418. if (andj !== "true" && andj !== "false") {
  64419. if (andj[0] === "!") {
  64420. result = !evaluateCallback(andj.substring(1));
  64421. }
  64422. else {
  64423. result = evaluateCallback(andj);
  64424. }
  64425. }
  64426. else {
  64427. result = andj === "true" ? true : false;
  64428. }
  64429. if (!result) {
  64430. ori = "false";
  64431. break;
  64432. }
  64433. }
  64434. }
  64435. if (result || ori === "true") {
  64436. result = true;
  64437. break;
  64438. }
  64439. // result equals false (or undefined)
  64440. if (ori !== "true" && ori !== "false") {
  64441. if (ori[0] === "!") {
  64442. result = !evaluateCallback(ori.substring(1));
  64443. }
  64444. else {
  64445. result = evaluateCallback(ori);
  64446. }
  64447. }
  64448. else {
  64449. result = ori === "true" ? true : false;
  64450. }
  64451. }
  64452. }
  64453. // the whole parenthesis scope is replaced by 'true' or 'false'
  64454. return result ? "true" : "false";
  64455. };
  64456. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  64457. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  64458. // remove whitespaces
  64459. r = r.replace(/[\s]/g, function () { return ""; });
  64460. return r.length % 2 ? "!" : "";
  64461. });
  64462. booleanString = booleanString.trim();
  64463. if (booleanString === "!true") {
  64464. booleanString = "false";
  64465. }
  64466. else if (booleanString === "!false") {
  64467. booleanString = "true";
  64468. }
  64469. return booleanString;
  64470. };
  64471. return AndOrNotEvaluator;
  64472. }());
  64473. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  64474. })(BABYLON || (BABYLON = {}));
  64475. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  64476. "use strict";
  64477. var BABYLON;
  64478. (function (BABYLON) {
  64479. var Database = /** @class */ (function () {
  64480. function Database(urlToScene, callbackManifestChecked) {
  64481. // Handling various flavors of prefixed version of IndexedDB
  64482. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  64483. this.callbackManifestChecked = callbackManifestChecked;
  64484. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  64485. this.db = null;
  64486. this._enableSceneOffline = false;
  64487. this._enableTexturesOffline = false;
  64488. this.manifestVersionFound = 0;
  64489. this.mustUpdateRessources = false;
  64490. this.hasReachedQuota = false;
  64491. if (!Database.IDBStorageEnabled) {
  64492. this.callbackManifestChecked(true);
  64493. }
  64494. else {
  64495. this.checkManifestFile();
  64496. }
  64497. }
  64498. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  64499. get: function () {
  64500. return this._enableSceneOffline;
  64501. },
  64502. enumerable: true,
  64503. configurable: true
  64504. });
  64505. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  64506. get: function () {
  64507. return this._enableTexturesOffline;
  64508. },
  64509. enumerable: true,
  64510. configurable: true
  64511. });
  64512. Database.prototype.checkManifestFile = function () {
  64513. var _this = this;
  64514. var noManifestFile = function () {
  64515. _this._enableSceneOffline = false;
  64516. _this._enableTexturesOffline = false;
  64517. _this.callbackManifestChecked(false);
  64518. };
  64519. var timeStampUsed = false;
  64520. var manifestURL = this.currentSceneUrl + ".manifest";
  64521. var xhr = new XMLHttpRequest();
  64522. if (navigator.onLine) {
  64523. // Adding a timestamp to by-pass browsers' cache
  64524. timeStampUsed = true;
  64525. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  64526. }
  64527. xhr.open("GET", manifestURL, true);
  64528. xhr.addEventListener("load", function () {
  64529. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64530. try {
  64531. var manifestFile = JSON.parse(xhr.response);
  64532. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  64533. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  64534. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  64535. _this.manifestVersionFound = manifestFile.version;
  64536. }
  64537. if (_this.callbackManifestChecked) {
  64538. _this.callbackManifestChecked(true);
  64539. }
  64540. }
  64541. catch (ex) {
  64542. noManifestFile();
  64543. }
  64544. }
  64545. else {
  64546. noManifestFile();
  64547. }
  64548. }, false);
  64549. xhr.addEventListener("error", function (event) {
  64550. if (timeStampUsed) {
  64551. timeStampUsed = false;
  64552. // Let's retry without the timeStamp
  64553. // It could fail when coupled with HTML5 Offline API
  64554. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  64555. xhr.open("GET", retryManifestURL, true);
  64556. xhr.send();
  64557. }
  64558. else {
  64559. noManifestFile();
  64560. }
  64561. }, false);
  64562. try {
  64563. xhr.send();
  64564. }
  64565. catch (ex) {
  64566. BABYLON.Tools.Error("Error on XHR send request.");
  64567. this.callbackManifestChecked(false);
  64568. }
  64569. };
  64570. Database.prototype.openAsync = function (successCallback, errorCallback) {
  64571. var _this = this;
  64572. var handleError = function () {
  64573. _this.isSupported = false;
  64574. if (errorCallback)
  64575. errorCallback();
  64576. };
  64577. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  64578. // Your browser doesn't support IndexedDB
  64579. this.isSupported = false;
  64580. if (errorCallback)
  64581. errorCallback();
  64582. }
  64583. else {
  64584. // If the DB hasn't been opened or created yet
  64585. if (!this.db) {
  64586. this.hasReachedQuota = false;
  64587. this.isSupported = true;
  64588. var request = this.idbFactory.open("babylonjs", 1);
  64589. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  64590. request.onerror = function (event) {
  64591. handleError();
  64592. };
  64593. // executes when a version change transaction cannot complete due to other active transactions
  64594. request.onblocked = function (event) {
  64595. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  64596. handleError();
  64597. };
  64598. // DB has been opened successfully
  64599. request.onsuccess = function (event) {
  64600. _this.db = request.result;
  64601. successCallback();
  64602. };
  64603. // Initialization of the DB. Creating Scenes & Textures stores
  64604. request.onupgradeneeded = function (event) {
  64605. _this.db = (event.target).result;
  64606. if (_this.db) {
  64607. try {
  64608. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  64609. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  64610. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  64611. }
  64612. catch (ex) {
  64613. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  64614. handleError();
  64615. }
  64616. }
  64617. };
  64618. }
  64619. else {
  64620. if (successCallback)
  64621. successCallback();
  64622. }
  64623. }
  64624. };
  64625. Database.prototype.loadImageFromDB = function (url, image) {
  64626. var _this = this;
  64627. var completeURL = Database.ReturnFullUrlLocation(url);
  64628. var saveAndLoadImage = function () {
  64629. if (!_this.hasReachedQuota && _this.db !== null) {
  64630. // the texture is not yet in the DB, let's try to save it
  64631. _this._saveImageIntoDBAsync(completeURL, image);
  64632. }
  64633. else {
  64634. image.src = url;
  64635. }
  64636. };
  64637. if (!this.mustUpdateRessources) {
  64638. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  64639. }
  64640. else {
  64641. saveAndLoadImage();
  64642. }
  64643. };
  64644. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  64645. if (this.isSupported && this.db !== null) {
  64646. var texture;
  64647. var transaction = this.db.transaction(["textures"]);
  64648. transaction.onabort = function (event) {
  64649. image.src = url;
  64650. };
  64651. transaction.oncomplete = function (event) {
  64652. var blobTextureURL;
  64653. if (texture) {
  64654. var URL = window.URL || window.webkitURL;
  64655. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  64656. image.onerror = function () {
  64657. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  64658. image.src = url;
  64659. };
  64660. image.src = blobTextureURL;
  64661. }
  64662. else {
  64663. notInDBCallback();
  64664. }
  64665. };
  64666. var getRequest = transaction.objectStore("textures").get(url);
  64667. getRequest.onsuccess = function (event) {
  64668. texture = (event.target).result;
  64669. };
  64670. getRequest.onerror = function (event) {
  64671. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  64672. image.src = url;
  64673. };
  64674. }
  64675. else {
  64676. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64677. image.src = url;
  64678. }
  64679. };
  64680. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  64681. var _this = this;
  64682. if (this.isSupported) {
  64683. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  64684. var generateBlobUrl = function () {
  64685. var blobTextureURL;
  64686. if (blob) {
  64687. var URL = window.URL || window.webkitURL;
  64688. try {
  64689. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  64690. }
  64691. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  64692. catch (ex) {
  64693. blobTextureURL = URL.createObjectURL(blob);
  64694. }
  64695. }
  64696. if (blobTextureURL) {
  64697. image.src = blobTextureURL;
  64698. }
  64699. };
  64700. if (Database.IsUASupportingBlobStorage) {
  64701. var xhr = new XMLHttpRequest(), blob;
  64702. xhr.open("GET", url, true);
  64703. xhr.responseType = "blob";
  64704. xhr.addEventListener("load", function () {
  64705. if (xhr.status === 200 && _this.db) {
  64706. // Blob as response (XHR2)
  64707. blob = xhr.response;
  64708. var transaction = _this.db.transaction(["textures"], "readwrite");
  64709. // the transaction could abort because of a QuotaExceededError error
  64710. transaction.onabort = function (event) {
  64711. try {
  64712. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64713. var srcElement = (event.srcElement || event.target);
  64714. var error = srcElement.error;
  64715. if (error && error.name === "QuotaExceededError") {
  64716. _this.hasReachedQuota = true;
  64717. }
  64718. }
  64719. catch (ex) { }
  64720. generateBlobUrl();
  64721. };
  64722. transaction.oncomplete = function (event) {
  64723. generateBlobUrl();
  64724. };
  64725. var newTexture = { textureUrl: url, data: blob };
  64726. try {
  64727. // Put the blob into the dabase
  64728. var addRequest = transaction.objectStore("textures").put(newTexture);
  64729. addRequest.onsuccess = function (event) {
  64730. };
  64731. addRequest.onerror = function (event) {
  64732. generateBlobUrl();
  64733. };
  64734. }
  64735. catch (ex) {
  64736. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  64737. if (ex.code === 25) {
  64738. Database.IsUASupportingBlobStorage = false;
  64739. }
  64740. image.src = url;
  64741. }
  64742. }
  64743. else {
  64744. image.src = url;
  64745. }
  64746. }, false);
  64747. xhr.addEventListener("error", function (event) {
  64748. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  64749. image.src = url;
  64750. }, false);
  64751. xhr.send();
  64752. }
  64753. else {
  64754. image.src = url;
  64755. }
  64756. }
  64757. else {
  64758. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64759. image.src = url;
  64760. }
  64761. };
  64762. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  64763. var _this = this;
  64764. var updateVersion = function () {
  64765. // the version is not yet in the DB or we need to update it
  64766. _this._saveVersionIntoDBAsync(url, versionLoaded);
  64767. };
  64768. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  64769. };
  64770. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  64771. var _this = this;
  64772. if (this.isSupported && this.db) {
  64773. var version;
  64774. try {
  64775. var transaction = this.db.transaction(["versions"]);
  64776. transaction.oncomplete = function (event) {
  64777. if (version) {
  64778. // If the version in the JSON file is > than the version in DB
  64779. if (_this.manifestVersionFound > version.data) {
  64780. _this.mustUpdateRessources = true;
  64781. updateInDBCallback();
  64782. }
  64783. else {
  64784. callback(version.data);
  64785. }
  64786. }
  64787. else {
  64788. _this.mustUpdateRessources = true;
  64789. updateInDBCallback();
  64790. }
  64791. };
  64792. transaction.onabort = function (event) {
  64793. callback(-1);
  64794. };
  64795. var getRequest = transaction.objectStore("versions").get(url);
  64796. getRequest.onsuccess = function (event) {
  64797. version = (event.target).result;
  64798. };
  64799. getRequest.onerror = function (event) {
  64800. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  64801. callback(-1);
  64802. };
  64803. }
  64804. catch (ex) {
  64805. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  64806. callback(-1);
  64807. }
  64808. }
  64809. else {
  64810. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64811. callback(-1);
  64812. }
  64813. };
  64814. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  64815. var _this = this;
  64816. if (this.isSupported && !this.hasReachedQuota && this.db) {
  64817. try {
  64818. // Open a transaction to the database
  64819. var transaction = this.db.transaction(["versions"], "readwrite");
  64820. // the transaction could abort because of a QuotaExceededError error
  64821. transaction.onabort = function (event) {
  64822. try {
  64823. var error = event.srcElement['error'];
  64824. if (error && error.name === "QuotaExceededError") {
  64825. _this.hasReachedQuota = true;
  64826. }
  64827. }
  64828. catch (ex) { }
  64829. callback(-1);
  64830. };
  64831. transaction.oncomplete = function (event) {
  64832. callback(_this.manifestVersionFound);
  64833. };
  64834. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  64835. // Put the scene into the database
  64836. var addRequest = transaction.objectStore("versions").put(newVersion);
  64837. addRequest.onsuccess = function (event) {
  64838. };
  64839. addRequest.onerror = function (event) {
  64840. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  64841. };
  64842. }
  64843. catch (ex) {
  64844. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  64845. callback(-1);
  64846. }
  64847. }
  64848. else {
  64849. callback(-1);
  64850. }
  64851. };
  64852. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  64853. var _this = this;
  64854. var completeUrl = Database.ReturnFullUrlLocation(url);
  64855. var saveAndLoadFile = function () {
  64856. // the scene is not yet in the DB, let's try to save it
  64857. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  64858. };
  64859. this._checkVersionFromDB(completeUrl, function (version) {
  64860. if (version !== -1) {
  64861. if (!_this.mustUpdateRessources) {
  64862. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  64863. }
  64864. else {
  64865. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  64866. }
  64867. }
  64868. else {
  64869. if (errorCallback) {
  64870. errorCallback();
  64871. }
  64872. }
  64873. });
  64874. };
  64875. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  64876. if (this.isSupported && this.db) {
  64877. var targetStore;
  64878. if (url.indexOf(".babylon") !== -1) {
  64879. targetStore = "scenes";
  64880. }
  64881. else {
  64882. targetStore = "textures";
  64883. }
  64884. var file;
  64885. var transaction = this.db.transaction([targetStore]);
  64886. transaction.oncomplete = function (event) {
  64887. if (file) {
  64888. callback(file.data);
  64889. }
  64890. else {
  64891. notInDBCallback();
  64892. }
  64893. };
  64894. transaction.onabort = function (event) {
  64895. notInDBCallback();
  64896. };
  64897. var getRequest = transaction.objectStore(targetStore).get(url);
  64898. getRequest.onsuccess = function (event) {
  64899. file = (event.target).result;
  64900. };
  64901. getRequest.onerror = function (event) {
  64902. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  64903. notInDBCallback();
  64904. };
  64905. }
  64906. else {
  64907. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64908. callback();
  64909. }
  64910. };
  64911. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  64912. var _this = this;
  64913. if (this.isSupported) {
  64914. var targetStore;
  64915. if (url.indexOf(".babylon") !== -1) {
  64916. targetStore = "scenes";
  64917. }
  64918. else {
  64919. targetStore = "textures";
  64920. }
  64921. // Create XHR
  64922. var xhr = new XMLHttpRequest();
  64923. var fileData;
  64924. xhr.open("GET", url, true);
  64925. if (useArrayBuffer) {
  64926. xhr.responseType = "arraybuffer";
  64927. }
  64928. if (progressCallback) {
  64929. xhr.onprogress = progressCallback;
  64930. }
  64931. xhr.addEventListener("load", function () {
  64932. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  64933. // Blob as response (XHR2)
  64934. //fileData = xhr.responseText;
  64935. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  64936. if (!_this.hasReachedQuota && _this.db) {
  64937. // Open a transaction to the database
  64938. var transaction = _this.db.transaction([targetStore], "readwrite");
  64939. // the transaction could abort because of a QuotaExceededError error
  64940. transaction.onabort = function (event) {
  64941. try {
  64942. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64943. var error = event.srcElement['error'];
  64944. if (error && error.name === "QuotaExceededError") {
  64945. _this.hasReachedQuota = true;
  64946. }
  64947. }
  64948. catch (ex) { }
  64949. callback(fileData);
  64950. };
  64951. transaction.oncomplete = function (event) {
  64952. callback(fileData);
  64953. };
  64954. var newFile;
  64955. if (targetStore === "scenes") {
  64956. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  64957. }
  64958. else {
  64959. newFile = { textureUrl: url, data: fileData };
  64960. }
  64961. try {
  64962. // Put the scene into the database
  64963. var addRequest = transaction.objectStore(targetStore).put(newFile);
  64964. addRequest.onsuccess = function (event) {
  64965. };
  64966. addRequest.onerror = function (event) {
  64967. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  64968. };
  64969. }
  64970. catch (ex) {
  64971. callback(fileData);
  64972. }
  64973. }
  64974. else {
  64975. callback(fileData);
  64976. }
  64977. }
  64978. else {
  64979. callback();
  64980. }
  64981. }, false);
  64982. xhr.addEventListener("error", function (event) {
  64983. BABYLON.Tools.Error("error on XHR request.");
  64984. callback();
  64985. }, false);
  64986. xhr.send();
  64987. }
  64988. else {
  64989. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64990. callback();
  64991. }
  64992. };
  64993. Database.IsUASupportingBlobStorage = true;
  64994. Database.IDBStorageEnabled = true;
  64995. Database.parseURL = function (url) {
  64996. var a = document.createElement('a');
  64997. a.href = url;
  64998. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  64999. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  65000. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  65001. return absLocation;
  65002. };
  65003. Database.ReturnFullUrlLocation = function (url) {
  65004. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  65005. return (Database.parseURL(window.location.href) + url);
  65006. }
  65007. else {
  65008. return url;
  65009. }
  65010. };
  65011. return Database;
  65012. }());
  65013. BABYLON.Database = Database;
  65014. })(BABYLON || (BABYLON = {}));
  65015. //# sourceMappingURL=babylon.database.js.map
  65016. "use strict";
  65017. var BABYLON;
  65018. (function (BABYLON) {
  65019. var FresnelParameters = /** @class */ (function () {
  65020. function FresnelParameters() {
  65021. this._isEnabled = true;
  65022. this.leftColor = BABYLON.Color3.White();
  65023. this.rightColor = BABYLON.Color3.Black();
  65024. this.bias = 0;
  65025. this.power = 1;
  65026. }
  65027. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  65028. get: function () {
  65029. return this._isEnabled;
  65030. },
  65031. set: function (value) {
  65032. if (this._isEnabled === value) {
  65033. return;
  65034. }
  65035. this._isEnabled = value;
  65036. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  65037. },
  65038. enumerable: true,
  65039. configurable: true
  65040. });
  65041. FresnelParameters.prototype.clone = function () {
  65042. var newFresnelParameters = new FresnelParameters();
  65043. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  65044. return newFresnelParameters;
  65045. };
  65046. FresnelParameters.prototype.serialize = function () {
  65047. var serializationObject = {};
  65048. serializationObject.isEnabled = this.isEnabled;
  65049. serializationObject.leftColor = this.leftColor.asArray();
  65050. serializationObject.rightColor = this.rightColor.asArray();
  65051. serializationObject.bias = this.bias;
  65052. serializationObject.power = this.power;
  65053. return serializationObject;
  65054. };
  65055. FresnelParameters.Parse = function (parsedFresnelParameters) {
  65056. var fresnelParameters = new FresnelParameters();
  65057. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  65058. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  65059. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  65060. fresnelParameters.bias = parsedFresnelParameters.bias;
  65061. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  65062. return fresnelParameters;
  65063. };
  65064. return FresnelParameters;
  65065. }());
  65066. BABYLON.FresnelParameters = FresnelParameters;
  65067. })(BABYLON || (BABYLON = {}));
  65068. //# sourceMappingURL=babylon.fresnelParameters.js.map
  65069. "use strict";
  65070. var BABYLON;
  65071. (function (BABYLON) {
  65072. var MultiMaterial = /** @class */ (function (_super) {
  65073. __extends(MultiMaterial, _super);
  65074. function MultiMaterial(name, scene) {
  65075. var _this = _super.call(this, name, scene, true) || this;
  65076. scene.multiMaterials.push(_this);
  65077. _this.subMaterials = new Array();
  65078. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  65079. return _this;
  65080. }
  65081. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  65082. get: function () {
  65083. return this._subMaterials;
  65084. },
  65085. set: function (value) {
  65086. this._subMaterials = value;
  65087. this._hookArray(value);
  65088. },
  65089. enumerable: true,
  65090. configurable: true
  65091. });
  65092. MultiMaterial.prototype._hookArray = function (array) {
  65093. var _this = this;
  65094. var oldPush = array.push;
  65095. array.push = function () {
  65096. var items = [];
  65097. for (var _i = 0; _i < arguments.length; _i++) {
  65098. items[_i] = arguments[_i];
  65099. }
  65100. var result = oldPush.apply(array, items);
  65101. _this._markAllSubMeshesAsTexturesDirty();
  65102. return result;
  65103. };
  65104. var oldSplice = array.splice;
  65105. array.splice = function (index, deleteCount) {
  65106. var deleted = oldSplice.apply(array, [index, deleteCount]);
  65107. _this._markAllSubMeshesAsTexturesDirty();
  65108. return deleted;
  65109. };
  65110. };
  65111. // Properties
  65112. MultiMaterial.prototype.getSubMaterial = function (index) {
  65113. if (index < 0 || index >= this.subMaterials.length) {
  65114. return this.getScene().defaultMaterial;
  65115. }
  65116. return this.subMaterials[index];
  65117. };
  65118. MultiMaterial.prototype.getActiveTextures = function () {
  65119. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  65120. if (subMaterial) {
  65121. return subMaterial.getActiveTextures();
  65122. }
  65123. else {
  65124. return [];
  65125. }
  65126. }));
  65127. var _a;
  65128. };
  65129. // Methods
  65130. MultiMaterial.prototype.getClassName = function () {
  65131. return "MultiMaterial";
  65132. };
  65133. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  65134. for (var index = 0; index < this.subMaterials.length; index++) {
  65135. var subMaterial = this.subMaterials[index];
  65136. if (subMaterial) {
  65137. if (subMaterial.storeEffectOnSubMeshes) {
  65138. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  65139. return false;
  65140. }
  65141. continue;
  65142. }
  65143. if (!subMaterial.isReady(mesh)) {
  65144. return false;
  65145. }
  65146. }
  65147. }
  65148. return true;
  65149. };
  65150. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  65151. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  65152. for (var index = 0; index < this.subMaterials.length; index++) {
  65153. var subMaterial = null;
  65154. var current = this.subMaterials[index];
  65155. if (cloneChildren && current) {
  65156. subMaterial = current.clone(name + "-" + current.name);
  65157. }
  65158. else {
  65159. subMaterial = this.subMaterials[index];
  65160. }
  65161. newMultiMaterial.subMaterials.push(subMaterial);
  65162. }
  65163. return newMultiMaterial;
  65164. };
  65165. MultiMaterial.prototype.serialize = function () {
  65166. var serializationObject = {};
  65167. serializationObject.name = this.name;
  65168. serializationObject.id = this.id;
  65169. if (BABYLON.Tags) {
  65170. serializationObject.tags = BABYLON.Tags.GetTags(this);
  65171. }
  65172. serializationObject.materials = [];
  65173. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  65174. var subMat = this.subMaterials[matIndex];
  65175. if (subMat) {
  65176. serializationObject.materials.push(subMat.id);
  65177. }
  65178. else {
  65179. serializationObject.materials.push(null);
  65180. }
  65181. }
  65182. return serializationObject;
  65183. };
  65184. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  65185. var scene = this.getScene();
  65186. if (!scene) {
  65187. return;
  65188. }
  65189. var index = scene.multiMaterials.indexOf(this);
  65190. if (index >= 0) {
  65191. scene.multiMaterials.splice(index, 1);
  65192. }
  65193. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  65194. };
  65195. return MultiMaterial;
  65196. }(BABYLON.Material));
  65197. BABYLON.MultiMaterial = MultiMaterial;
  65198. })(BABYLON || (BABYLON = {}));
  65199. //# sourceMappingURL=babylon.multiMaterial.js.map
  65200. "use strict";
  65201. var BABYLON;
  65202. (function (BABYLON) {
  65203. var FreeCameraTouchInput = /** @class */ (function () {
  65204. function FreeCameraTouchInput() {
  65205. this._offsetX = null;
  65206. this._offsetY = null;
  65207. this._pointerPressed = new Array();
  65208. this.touchAngularSensibility = 200000.0;
  65209. this.touchMoveSensibility = 250.0;
  65210. }
  65211. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  65212. var _this = this;
  65213. var previousPosition = null;
  65214. if (this._pointerInput === undefined) {
  65215. this._onLostFocus = function (evt) {
  65216. _this._offsetX = null;
  65217. _this._offsetY = null;
  65218. };
  65219. this._pointerInput = function (p, s) {
  65220. var evt = p.event;
  65221. if (evt.pointerType === "mouse") {
  65222. return;
  65223. }
  65224. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  65225. if (!noPreventDefault) {
  65226. evt.preventDefault();
  65227. }
  65228. _this._pointerPressed.push(evt.pointerId);
  65229. if (_this._pointerPressed.length !== 1) {
  65230. return;
  65231. }
  65232. previousPosition = {
  65233. x: evt.clientX,
  65234. y: evt.clientY
  65235. };
  65236. }
  65237. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  65238. if (!noPreventDefault) {
  65239. evt.preventDefault();
  65240. }
  65241. var index = _this._pointerPressed.indexOf(evt.pointerId);
  65242. if (index === -1) {
  65243. return;
  65244. }
  65245. _this._pointerPressed.splice(index, 1);
  65246. if (index != 0) {
  65247. return;
  65248. }
  65249. previousPosition = null;
  65250. _this._offsetX = null;
  65251. _this._offsetY = null;
  65252. }
  65253. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  65254. if (!noPreventDefault) {
  65255. evt.preventDefault();
  65256. }
  65257. if (!previousPosition) {
  65258. return;
  65259. }
  65260. var index = _this._pointerPressed.indexOf(evt.pointerId);
  65261. if (index != 0) {
  65262. return;
  65263. }
  65264. _this._offsetX = evt.clientX - previousPosition.x;
  65265. _this._offsetY = -(evt.clientY - previousPosition.y);
  65266. }
  65267. };
  65268. }
  65269. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  65270. if (this._onLostFocus) {
  65271. element.addEventListener("blur", this._onLostFocus);
  65272. }
  65273. };
  65274. FreeCameraTouchInput.prototype.detachControl = function (element) {
  65275. if (this._pointerInput && element) {
  65276. if (this._observer) {
  65277. this.camera.getScene().onPointerObservable.remove(this._observer);
  65278. this._observer = null;
  65279. }
  65280. if (this._onLostFocus) {
  65281. element.removeEventListener("blur", this._onLostFocus);
  65282. this._onLostFocus = null;
  65283. }
  65284. this._pointerPressed = [];
  65285. this._offsetX = null;
  65286. this._offsetY = null;
  65287. }
  65288. };
  65289. FreeCameraTouchInput.prototype.checkInputs = function () {
  65290. if (this._offsetX && this._offsetY) {
  65291. var camera = this.camera;
  65292. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  65293. if (this._pointerPressed.length > 1) {
  65294. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  65295. }
  65296. else {
  65297. var speed = camera._computeLocalCameraSpeed();
  65298. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  65299. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  65300. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  65301. }
  65302. }
  65303. };
  65304. FreeCameraTouchInput.prototype.getClassName = function () {
  65305. return "FreeCameraTouchInput";
  65306. };
  65307. FreeCameraTouchInput.prototype.getSimpleName = function () {
  65308. return "touch";
  65309. };
  65310. __decorate([
  65311. BABYLON.serialize()
  65312. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  65313. __decorate([
  65314. BABYLON.serialize()
  65315. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  65316. return FreeCameraTouchInput;
  65317. }());
  65318. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  65319. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  65320. })(BABYLON || (BABYLON = {}));
  65321. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  65322. "use strict";
  65323. var BABYLON;
  65324. (function (BABYLON) {
  65325. // We're mainly based on the logic defined into the FreeCamera code
  65326. var TouchCamera = /** @class */ (function (_super) {
  65327. __extends(TouchCamera, _super);
  65328. //-- end properties for backward compatibility for inputs
  65329. function TouchCamera(name, position, scene) {
  65330. var _this = _super.call(this, name, position, scene) || this;
  65331. _this.inputs.addTouch();
  65332. _this._setupInputs();
  65333. return _this;
  65334. }
  65335. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  65336. //-- Begin properties for backward compatibility for inputs
  65337. get: function () {
  65338. var touch = this.inputs.attached["touch"];
  65339. if (touch)
  65340. return touch.touchAngularSensibility;
  65341. return 0;
  65342. },
  65343. set: function (value) {
  65344. var touch = this.inputs.attached["touch"];
  65345. if (touch)
  65346. touch.touchAngularSensibility = value;
  65347. },
  65348. enumerable: true,
  65349. configurable: true
  65350. });
  65351. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  65352. get: function () {
  65353. var touch = this.inputs.attached["touch"];
  65354. if (touch)
  65355. return touch.touchMoveSensibility;
  65356. return 0;
  65357. },
  65358. set: function (value) {
  65359. var touch = this.inputs.attached["touch"];
  65360. if (touch)
  65361. touch.touchMoveSensibility = value;
  65362. },
  65363. enumerable: true,
  65364. configurable: true
  65365. });
  65366. TouchCamera.prototype.getClassName = function () {
  65367. return "TouchCamera";
  65368. };
  65369. TouchCamera.prototype._setupInputs = function () {
  65370. var mouse = this.inputs.attached["mouse"];
  65371. if (mouse) {
  65372. mouse.touchEnabled = false;
  65373. }
  65374. };
  65375. return TouchCamera;
  65376. }(BABYLON.FreeCamera));
  65377. BABYLON.TouchCamera = TouchCamera;
  65378. })(BABYLON || (BABYLON = {}));
  65379. //# sourceMappingURL=babylon.touchCamera.js.map
  65380. "use strict";
  65381. var BABYLON;
  65382. (function (BABYLON) {
  65383. var ProceduralTexture = /** @class */ (function (_super) {
  65384. __extends(ProceduralTexture, _super);
  65385. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  65386. if (fallbackTexture === void 0) { fallbackTexture = null; }
  65387. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65388. if (isCube === void 0) { isCube = false; }
  65389. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  65390. _this.isCube = isCube;
  65391. _this.isEnabled = true;
  65392. _this._currentRefreshId = -1;
  65393. _this._refreshRate = 1;
  65394. _this._vertexBuffers = {};
  65395. _this._uniforms = new Array();
  65396. _this._samplers = new Array();
  65397. _this._textures = {};
  65398. _this._floats = {};
  65399. _this._floatsArrays = {};
  65400. _this._colors3 = {};
  65401. _this._colors4 = {};
  65402. _this._vectors2 = {};
  65403. _this._vectors3 = {};
  65404. _this._matrices = {};
  65405. _this._fallbackTextureUsed = false;
  65406. scene._proceduralTextures.push(_this);
  65407. _this._engine = scene.getEngine();
  65408. _this.name = name;
  65409. _this.isRenderTarget = true;
  65410. _this._size = size;
  65411. _this._generateMipMaps = generateMipMaps;
  65412. _this.setFragment(fragment);
  65413. _this._fallbackTexture = fallbackTexture;
  65414. if (isCube) {
  65415. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  65416. _this.setFloat("face", 0);
  65417. }
  65418. else {
  65419. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  65420. }
  65421. // VBO
  65422. var vertices = [];
  65423. vertices.push(1, 1);
  65424. vertices.push(-1, 1);
  65425. vertices.push(-1, -1);
  65426. vertices.push(1, -1);
  65427. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65428. _this._createIndexBuffer();
  65429. return _this;
  65430. }
  65431. ProceduralTexture.prototype._createIndexBuffer = function () {
  65432. var engine = this._engine;
  65433. // Indices
  65434. var indices = [];
  65435. indices.push(0);
  65436. indices.push(1);
  65437. indices.push(2);
  65438. indices.push(0);
  65439. indices.push(2);
  65440. indices.push(3);
  65441. this._indexBuffer = engine.createIndexBuffer(indices);
  65442. };
  65443. ProceduralTexture.prototype._rebuild = function () {
  65444. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65445. if (vb) {
  65446. vb._rebuild();
  65447. }
  65448. this._createIndexBuffer();
  65449. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65450. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65451. }
  65452. };
  65453. ProceduralTexture.prototype.reset = function () {
  65454. if (this._effect === undefined) {
  65455. return;
  65456. }
  65457. var engine = this._engine;
  65458. engine._releaseEffect(this._effect);
  65459. };
  65460. ProceduralTexture.prototype.isReady = function () {
  65461. var _this = this;
  65462. var engine = this._engine;
  65463. var shaders;
  65464. if (!this._fragment) {
  65465. return false;
  65466. }
  65467. if (this._fallbackTextureUsed) {
  65468. return true;
  65469. }
  65470. if (this._fragment.fragmentElement !== undefined) {
  65471. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  65472. }
  65473. else {
  65474. shaders = { vertex: "procedural", fragment: this._fragment };
  65475. }
  65476. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  65477. _this.releaseInternalTexture();
  65478. if (_this._fallbackTexture) {
  65479. _this._texture = _this._fallbackTexture._texture;
  65480. if (_this._texture) {
  65481. _this._texture.incrementReferences();
  65482. }
  65483. }
  65484. _this._fallbackTextureUsed = true;
  65485. });
  65486. return this._effect.isReady();
  65487. };
  65488. ProceduralTexture.prototype.resetRefreshCounter = function () {
  65489. this._currentRefreshId = -1;
  65490. };
  65491. ProceduralTexture.prototype.setFragment = function (fragment) {
  65492. this._fragment = fragment;
  65493. };
  65494. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  65495. get: function () {
  65496. return this._refreshRate;
  65497. },
  65498. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65499. set: function (value) {
  65500. this._refreshRate = value;
  65501. this.resetRefreshCounter();
  65502. },
  65503. enumerable: true,
  65504. configurable: true
  65505. });
  65506. ProceduralTexture.prototype._shouldRender = function () {
  65507. if (!this.isEnabled || !this.isReady() || !this._texture) {
  65508. return false;
  65509. }
  65510. if (this._fallbackTextureUsed) {
  65511. return false;
  65512. }
  65513. if (this._currentRefreshId === -1) {
  65514. this._currentRefreshId = 1;
  65515. return true;
  65516. }
  65517. if (this.refreshRate === this._currentRefreshId) {
  65518. this._currentRefreshId = 1;
  65519. return true;
  65520. }
  65521. this._currentRefreshId++;
  65522. return false;
  65523. };
  65524. ProceduralTexture.prototype.getRenderSize = function () {
  65525. return this._size;
  65526. };
  65527. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  65528. if (this._fallbackTextureUsed) {
  65529. return;
  65530. }
  65531. this.releaseInternalTexture();
  65532. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  65533. };
  65534. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  65535. if (this._uniforms.indexOf(uniformName) === -1) {
  65536. this._uniforms.push(uniformName);
  65537. }
  65538. };
  65539. ProceduralTexture.prototype.setTexture = function (name, texture) {
  65540. if (this._samplers.indexOf(name) === -1) {
  65541. this._samplers.push(name);
  65542. }
  65543. this._textures[name] = texture;
  65544. return this;
  65545. };
  65546. ProceduralTexture.prototype.setFloat = function (name, value) {
  65547. this._checkUniform(name);
  65548. this._floats[name] = value;
  65549. return this;
  65550. };
  65551. ProceduralTexture.prototype.setFloats = function (name, value) {
  65552. this._checkUniform(name);
  65553. this._floatsArrays[name] = value;
  65554. return this;
  65555. };
  65556. ProceduralTexture.prototype.setColor3 = function (name, value) {
  65557. this._checkUniform(name);
  65558. this._colors3[name] = value;
  65559. return this;
  65560. };
  65561. ProceduralTexture.prototype.setColor4 = function (name, value) {
  65562. this._checkUniform(name);
  65563. this._colors4[name] = value;
  65564. return this;
  65565. };
  65566. ProceduralTexture.prototype.setVector2 = function (name, value) {
  65567. this._checkUniform(name);
  65568. this._vectors2[name] = value;
  65569. return this;
  65570. };
  65571. ProceduralTexture.prototype.setVector3 = function (name, value) {
  65572. this._checkUniform(name);
  65573. this._vectors3[name] = value;
  65574. return this;
  65575. };
  65576. ProceduralTexture.prototype.setMatrix = function (name, value) {
  65577. this._checkUniform(name);
  65578. this._matrices[name] = value;
  65579. return this;
  65580. };
  65581. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65582. var scene = this.getScene();
  65583. if (!scene) {
  65584. return;
  65585. }
  65586. var engine = this._engine;
  65587. // Render
  65588. engine.enableEffect(this._effect);
  65589. engine.setState(false);
  65590. // Texture
  65591. for (var name in this._textures) {
  65592. this._effect.setTexture(name, this._textures[name]);
  65593. }
  65594. // Float
  65595. for (name in this._floats) {
  65596. this._effect.setFloat(name, this._floats[name]);
  65597. }
  65598. // Floats
  65599. for (name in this._floatsArrays) {
  65600. this._effect.setArray(name, this._floatsArrays[name]);
  65601. }
  65602. // Color3
  65603. for (name in this._colors3) {
  65604. this._effect.setColor3(name, this._colors3[name]);
  65605. }
  65606. // Color4
  65607. for (name in this._colors4) {
  65608. var color = this._colors4[name];
  65609. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  65610. }
  65611. // Vector2
  65612. for (name in this._vectors2) {
  65613. this._effect.setVector2(name, this._vectors2[name]);
  65614. }
  65615. // Vector3
  65616. for (name in this._vectors3) {
  65617. this._effect.setVector3(name, this._vectors3[name]);
  65618. }
  65619. // Matrix
  65620. for (name in this._matrices) {
  65621. this._effect.setMatrix(name, this._matrices[name]);
  65622. }
  65623. if (!this._texture) {
  65624. return;
  65625. }
  65626. if (this.isCube) {
  65627. for (var face = 0; face < 6; face++) {
  65628. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  65629. // VBOs
  65630. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65631. this._effect.setFloat("face", face);
  65632. // Clear
  65633. engine.clear(scene.clearColor, true, true, true);
  65634. // Draw order
  65635. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65636. // Mipmaps
  65637. if (face === 5) {
  65638. engine.generateMipMapsForCubemap(this._texture);
  65639. }
  65640. }
  65641. }
  65642. else {
  65643. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  65644. // VBOs
  65645. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65646. // Clear
  65647. engine.clear(scene.clearColor, true, true, true);
  65648. // Draw order
  65649. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65650. }
  65651. // Unbind
  65652. engine.unBindFramebuffer(this._texture, this.isCube);
  65653. if (this.onGenerated) {
  65654. this.onGenerated();
  65655. }
  65656. };
  65657. ProceduralTexture.prototype.clone = function () {
  65658. var textureSize = this.getSize();
  65659. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  65660. // Base texture
  65661. newTexture.hasAlpha = this.hasAlpha;
  65662. newTexture.level = this.level;
  65663. // RenderTarget Texture
  65664. newTexture.coordinatesMode = this.coordinatesMode;
  65665. return newTexture;
  65666. };
  65667. ProceduralTexture.prototype.dispose = function () {
  65668. var scene = this.getScene();
  65669. if (!scene) {
  65670. return;
  65671. }
  65672. var index = scene._proceduralTextures.indexOf(this);
  65673. if (index >= 0) {
  65674. scene._proceduralTextures.splice(index, 1);
  65675. }
  65676. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65677. if (vertexBuffer) {
  65678. vertexBuffer.dispose();
  65679. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65680. }
  65681. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  65682. this._indexBuffer = null;
  65683. }
  65684. _super.prototype.dispose.call(this);
  65685. };
  65686. return ProceduralTexture;
  65687. }(BABYLON.Texture));
  65688. BABYLON.ProceduralTexture = ProceduralTexture;
  65689. })(BABYLON || (BABYLON = {}));
  65690. //# sourceMappingURL=babylon.proceduralTexture.js.map
  65691. "use strict";
  65692. var BABYLON;
  65693. (function (BABYLON) {
  65694. var CustomProceduralTexture = /** @class */ (function (_super) {
  65695. __extends(CustomProceduralTexture, _super);
  65696. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  65697. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  65698. _this._animate = true;
  65699. _this._time = 0;
  65700. _this._texturePath = texturePath;
  65701. //Try to load json
  65702. _this.loadJson(texturePath);
  65703. _this.refreshRate = 1;
  65704. return _this;
  65705. }
  65706. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  65707. var _this = this;
  65708. var noConfigFile = function () {
  65709. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  65710. try {
  65711. _this.setFragment(_this._texturePath);
  65712. }
  65713. catch (ex) {
  65714. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  65715. }
  65716. };
  65717. var configFileUrl = jsonUrl + "/config.json";
  65718. var xhr = new XMLHttpRequest();
  65719. xhr.open("GET", configFileUrl, true);
  65720. xhr.addEventListener("load", function () {
  65721. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  65722. try {
  65723. _this._config = JSON.parse(xhr.response);
  65724. _this.updateShaderUniforms();
  65725. _this.updateTextures();
  65726. _this.setFragment(_this._texturePath + "/custom");
  65727. _this._animate = _this._config.animate;
  65728. _this.refreshRate = _this._config.refreshrate;
  65729. }
  65730. catch (ex) {
  65731. noConfigFile();
  65732. }
  65733. }
  65734. else {
  65735. noConfigFile();
  65736. }
  65737. }, false);
  65738. xhr.addEventListener("error", function () {
  65739. noConfigFile();
  65740. }, false);
  65741. try {
  65742. xhr.send();
  65743. }
  65744. catch (ex) {
  65745. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  65746. }
  65747. };
  65748. CustomProceduralTexture.prototype.isReady = function () {
  65749. if (!_super.prototype.isReady.call(this)) {
  65750. return false;
  65751. }
  65752. for (var name in this._textures) {
  65753. var texture = this._textures[name];
  65754. if (!texture.isReady()) {
  65755. return false;
  65756. }
  65757. }
  65758. return true;
  65759. };
  65760. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65761. var scene = this.getScene();
  65762. if (this._animate && scene) {
  65763. this._time += scene.getAnimationRatio() * 0.03;
  65764. this.updateShaderUniforms();
  65765. }
  65766. _super.prototype.render.call(this, useCameraPostProcess);
  65767. };
  65768. CustomProceduralTexture.prototype.updateTextures = function () {
  65769. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  65770. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  65771. }
  65772. };
  65773. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  65774. if (this._config) {
  65775. for (var j = 0; j < this._config.uniforms.length; j++) {
  65776. var uniform = this._config.uniforms[j];
  65777. switch (uniform.type) {
  65778. case "float":
  65779. this.setFloat(uniform.name, uniform.value);
  65780. break;
  65781. case "color3":
  65782. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  65783. break;
  65784. case "color4":
  65785. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  65786. break;
  65787. case "vector2":
  65788. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  65789. break;
  65790. case "vector3":
  65791. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  65792. break;
  65793. }
  65794. }
  65795. }
  65796. this.setFloat("time", this._time);
  65797. };
  65798. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  65799. get: function () {
  65800. return this._animate;
  65801. },
  65802. set: function (value) {
  65803. this._animate = value;
  65804. },
  65805. enumerable: true,
  65806. configurable: true
  65807. });
  65808. return CustomProceduralTexture;
  65809. }(BABYLON.ProceduralTexture));
  65810. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  65811. })(BABYLON || (BABYLON = {}));
  65812. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  65813. "use strict";
  65814. var BABYLON;
  65815. (function (BABYLON) {
  65816. var FreeCameraGamepadInput = /** @class */ (function () {
  65817. function FreeCameraGamepadInput() {
  65818. this.gamepadAngularSensibility = 200;
  65819. this.gamepadMoveSensibility = 40;
  65820. // private members
  65821. this._cameraTransform = BABYLON.Matrix.Identity();
  65822. this._deltaTransform = BABYLON.Vector3.Zero();
  65823. this._vector3 = BABYLON.Vector3.Zero();
  65824. this._vector2 = BABYLON.Vector2.Zero();
  65825. }
  65826. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65827. var _this = this;
  65828. var manager = this.camera.getScene().gamepadManager;
  65829. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65830. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65831. // prioritize XBOX gamepads.
  65832. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65833. _this.gamepad = gamepad;
  65834. }
  65835. }
  65836. });
  65837. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65838. if (_this.gamepad === gamepad) {
  65839. _this.gamepad = null;
  65840. }
  65841. });
  65842. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65843. };
  65844. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  65845. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65846. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65847. this.gamepad = null;
  65848. };
  65849. FreeCameraGamepadInput.prototype.checkInputs = function () {
  65850. if (this.gamepad && this.gamepad.leftStick) {
  65851. var camera = this.camera;
  65852. var LSValues = this.gamepad.leftStick;
  65853. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  65854. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65855. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  65856. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  65857. var RSValues = this.gamepad.rightStick;
  65858. if (RSValues) {
  65859. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  65860. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  65861. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  65862. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  65863. }
  65864. else {
  65865. RSValues = { x: 0, y: 0 };
  65866. }
  65867. if (!camera.rotationQuaternion) {
  65868. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  65869. }
  65870. else {
  65871. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  65872. }
  65873. var speed = camera._computeLocalCameraSpeed() * 50.0;
  65874. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  65875. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  65876. camera.cameraDirection.addInPlace(this._deltaTransform);
  65877. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  65878. camera.cameraRotation.addInPlace(this._vector2);
  65879. }
  65880. };
  65881. FreeCameraGamepadInput.prototype.getClassName = function () {
  65882. return "FreeCameraGamepadInput";
  65883. };
  65884. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  65885. return "gamepad";
  65886. };
  65887. __decorate([
  65888. BABYLON.serialize()
  65889. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  65890. __decorate([
  65891. BABYLON.serialize()
  65892. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65893. return FreeCameraGamepadInput;
  65894. }());
  65895. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  65896. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  65897. })(BABYLON || (BABYLON = {}));
  65898. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  65899. "use strict";
  65900. var BABYLON;
  65901. (function (BABYLON) {
  65902. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  65903. function ArcRotateCameraGamepadInput() {
  65904. this.gamepadRotationSensibility = 80;
  65905. this.gamepadMoveSensibility = 40;
  65906. }
  65907. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65908. var _this = this;
  65909. var manager = this.camera.getScene().gamepadManager;
  65910. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65911. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65912. // prioritize XBOX gamepads.
  65913. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65914. _this.gamepad = gamepad;
  65915. }
  65916. }
  65917. });
  65918. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65919. if (_this.gamepad === gamepad) {
  65920. _this.gamepad = null;
  65921. }
  65922. });
  65923. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65924. };
  65925. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  65926. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65927. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65928. this.gamepad = null;
  65929. };
  65930. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  65931. if (this.gamepad) {
  65932. var camera = this.camera;
  65933. var RSValues = this.gamepad.rightStick;
  65934. if (RSValues) {
  65935. if (RSValues.x != 0) {
  65936. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  65937. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  65938. camera.inertialAlphaOffset += normalizedRX;
  65939. }
  65940. }
  65941. if (RSValues.y != 0) {
  65942. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  65943. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  65944. camera.inertialBetaOffset += normalizedRY;
  65945. }
  65946. }
  65947. }
  65948. var LSValues = this.gamepad.leftStick;
  65949. if (LSValues && LSValues.y != 0) {
  65950. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65951. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  65952. this.camera.inertialRadiusOffset -= normalizedLY;
  65953. }
  65954. }
  65955. }
  65956. };
  65957. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  65958. return "ArcRotateCameraGamepadInput";
  65959. };
  65960. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  65961. return "gamepad";
  65962. };
  65963. __decorate([
  65964. BABYLON.serialize()
  65965. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  65966. __decorate([
  65967. BABYLON.serialize()
  65968. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65969. return ArcRotateCameraGamepadInput;
  65970. }());
  65971. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  65972. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  65973. })(BABYLON || (BABYLON = {}));
  65974. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  65975. "use strict";
  65976. var BABYLON;
  65977. (function (BABYLON) {
  65978. var GamepadManager = /** @class */ (function () {
  65979. function GamepadManager(_scene) {
  65980. var _this = this;
  65981. this._scene = _scene;
  65982. this._babylonGamepads = [];
  65983. this._oneGamepadConnected = false;
  65984. this._isMonitoring = false;
  65985. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  65986. if (!BABYLON.Tools.IsWindowObjectExist()) {
  65987. this._gamepadEventSupported = false;
  65988. }
  65989. else {
  65990. this._gamepadEventSupported = 'GamepadEvent' in window;
  65991. this._gamepadSupport = (navigator.getGamepads ||
  65992. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  65993. }
  65994. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  65995. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  65996. for (var i in _this._babylonGamepads) {
  65997. var gamepad = _this._babylonGamepads[i];
  65998. if (gamepad && gamepad._isConnected) {
  65999. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  66000. }
  66001. }
  66002. });
  66003. this._onGamepadConnectedEvent = function (evt) {
  66004. var gamepad = evt.gamepad;
  66005. if (gamepad.index in _this._babylonGamepads) {
  66006. if (_this._babylonGamepads[gamepad.index].isConnected) {
  66007. return;
  66008. }
  66009. }
  66010. var newGamepad;
  66011. if (_this._babylonGamepads[gamepad.index]) {
  66012. newGamepad = _this._babylonGamepads[gamepad.index];
  66013. newGamepad.browserGamepad = gamepad;
  66014. newGamepad._isConnected = true;
  66015. }
  66016. else {
  66017. newGamepad = _this._addNewGamepad(gamepad);
  66018. }
  66019. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  66020. _this._startMonitoringGamepads();
  66021. };
  66022. this._onGamepadDisconnectedEvent = function (evt) {
  66023. var gamepad = evt.gamepad;
  66024. // Remove the gamepad from the list of gamepads to monitor.
  66025. for (var i in _this._babylonGamepads) {
  66026. if (_this._babylonGamepads[i].index === gamepad.index) {
  66027. var disconnectedGamepad = _this._babylonGamepads[i];
  66028. disconnectedGamepad._isConnected = false;
  66029. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  66030. break;
  66031. }
  66032. }
  66033. };
  66034. if (this._gamepadSupport) {
  66035. //first add already-connected gamepads
  66036. this._updateGamepadObjects();
  66037. if (this._babylonGamepads.length) {
  66038. this._startMonitoringGamepads();
  66039. }
  66040. // Checking if the gamepad connected event is supported (like in Firefox)
  66041. if (this._gamepadEventSupported) {
  66042. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  66043. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  66044. }
  66045. else {
  66046. this._startMonitoringGamepads();
  66047. }
  66048. }
  66049. }
  66050. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  66051. get: function () {
  66052. return this._babylonGamepads;
  66053. },
  66054. enumerable: true,
  66055. configurable: true
  66056. });
  66057. GamepadManager.prototype.getGamepadByType = function (type) {
  66058. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  66059. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  66060. var gamepad = _a[_i];
  66061. if (gamepad && gamepad.type === type) {
  66062. return gamepad;
  66063. }
  66064. }
  66065. return null;
  66066. };
  66067. GamepadManager.prototype.dispose = function () {
  66068. if (this._gamepadEventSupported) {
  66069. if (this._onGamepadConnectedEvent) {
  66070. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  66071. }
  66072. if (this._onGamepadDisconnectedEvent) {
  66073. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  66074. }
  66075. this._onGamepadConnectedEvent = null;
  66076. this._onGamepadDisconnectedEvent = null;
  66077. }
  66078. this._babylonGamepads.forEach(function (gamepad) {
  66079. gamepad.dispose();
  66080. });
  66081. this.onGamepadConnectedObservable.clear();
  66082. this.onGamepadDisconnectedObservable.clear();
  66083. this._oneGamepadConnected = false;
  66084. this._stopMonitoringGamepads();
  66085. this._babylonGamepads = [];
  66086. };
  66087. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  66088. if (!this._oneGamepadConnected) {
  66089. this._oneGamepadConnected = true;
  66090. }
  66091. var newGamepad;
  66092. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  66093. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  66094. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  66095. }
  66096. else if (gamepad.pose) {
  66097. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  66098. }
  66099. else {
  66100. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  66101. }
  66102. this._babylonGamepads[newGamepad.index] = newGamepad;
  66103. return newGamepad;
  66104. };
  66105. GamepadManager.prototype._startMonitoringGamepads = function () {
  66106. if (!this._isMonitoring) {
  66107. this._isMonitoring = true;
  66108. //back-comp
  66109. if (!this._scene) {
  66110. this._checkGamepadsStatus();
  66111. }
  66112. }
  66113. };
  66114. GamepadManager.prototype._stopMonitoringGamepads = function () {
  66115. this._isMonitoring = false;
  66116. };
  66117. GamepadManager.prototype._checkGamepadsStatus = function () {
  66118. var _this = this;
  66119. // Hack to be compatible Chrome
  66120. this._updateGamepadObjects();
  66121. for (var i in this._babylonGamepads) {
  66122. var gamepad = this._babylonGamepads[i];
  66123. if (!gamepad || !gamepad.isConnected) {
  66124. continue;
  66125. }
  66126. gamepad.update();
  66127. }
  66128. if (this._isMonitoring && !this._scene) {
  66129. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  66130. }
  66131. };
  66132. // This function is called only on Chrome, which does not properly support
  66133. // connection/disconnection events and forces you to recopy again the gamepad object
  66134. GamepadManager.prototype._updateGamepadObjects = function () {
  66135. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  66136. for (var i = 0; i < gamepads.length; i++) {
  66137. if (gamepads[i]) {
  66138. if (!this._babylonGamepads[gamepads[i].index]) {
  66139. var newGamepad = this._addNewGamepad(gamepads[i]);
  66140. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  66141. }
  66142. else {
  66143. // Forced to copy again this object for Chrome for unknown reason
  66144. this._babylonGamepads[i].browserGamepad = gamepads[i];
  66145. if (!this._babylonGamepads[i].isConnected) {
  66146. this._babylonGamepads[i]._isConnected = true;
  66147. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  66148. }
  66149. }
  66150. }
  66151. }
  66152. };
  66153. return GamepadManager;
  66154. }());
  66155. BABYLON.GamepadManager = GamepadManager;
  66156. })(BABYLON || (BABYLON = {}));
  66157. //# sourceMappingURL=babylon.gamepadManager.js.map
  66158. "use strict";
  66159. var BABYLON;
  66160. (function (BABYLON) {
  66161. var StickValues = /** @class */ (function () {
  66162. function StickValues(x, y) {
  66163. this.x = x;
  66164. this.y = y;
  66165. }
  66166. return StickValues;
  66167. }());
  66168. BABYLON.StickValues = StickValues;
  66169. var Gamepad = /** @class */ (function () {
  66170. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  66171. if (leftStickX === void 0) { leftStickX = 0; }
  66172. if (leftStickY === void 0) { leftStickY = 1; }
  66173. if (rightStickX === void 0) { rightStickX = 2; }
  66174. if (rightStickY === void 0) { rightStickY = 3; }
  66175. this.id = id;
  66176. this.index = index;
  66177. this.browserGamepad = browserGamepad;
  66178. this._isConnected = true;
  66179. this._invertLeftStickY = false;
  66180. this.type = Gamepad.GAMEPAD;
  66181. this._leftStickAxisX = leftStickX;
  66182. this._leftStickAxisY = leftStickY;
  66183. this._rightStickAxisX = rightStickX;
  66184. this._rightStickAxisY = rightStickY;
  66185. if (this.browserGamepad.axes.length >= 2) {
  66186. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  66187. }
  66188. if (this.browserGamepad.axes.length >= 4) {
  66189. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  66190. }
  66191. }
  66192. Object.defineProperty(Gamepad.prototype, "isConnected", {
  66193. get: function () {
  66194. return this._isConnected;
  66195. },
  66196. enumerable: true,
  66197. configurable: true
  66198. });
  66199. Gamepad.prototype.onleftstickchanged = function (callback) {
  66200. this._onleftstickchanged = callback;
  66201. };
  66202. Gamepad.prototype.onrightstickchanged = function (callback) {
  66203. this._onrightstickchanged = callback;
  66204. };
  66205. Object.defineProperty(Gamepad.prototype, "leftStick", {
  66206. get: function () {
  66207. return this._leftStick;
  66208. },
  66209. set: function (newValues) {
  66210. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  66211. this._onleftstickchanged(newValues);
  66212. }
  66213. this._leftStick = newValues;
  66214. },
  66215. enumerable: true,
  66216. configurable: true
  66217. });
  66218. Object.defineProperty(Gamepad.prototype, "rightStick", {
  66219. get: function () {
  66220. return this._rightStick;
  66221. },
  66222. set: function (newValues) {
  66223. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  66224. this._onrightstickchanged(newValues);
  66225. }
  66226. this._rightStick = newValues;
  66227. },
  66228. enumerable: true,
  66229. configurable: true
  66230. });
  66231. Gamepad.prototype.update = function () {
  66232. if (this._leftStick) {
  66233. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  66234. if (this._invertLeftStickY) {
  66235. this.leftStick.y *= -1;
  66236. }
  66237. }
  66238. if (this._rightStick) {
  66239. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  66240. }
  66241. };
  66242. Gamepad.prototype.dispose = function () {
  66243. };
  66244. Gamepad.GAMEPAD = 0;
  66245. Gamepad.GENERIC = 1;
  66246. Gamepad.XBOX = 2;
  66247. Gamepad.POSE_ENABLED = 3;
  66248. return Gamepad;
  66249. }());
  66250. BABYLON.Gamepad = Gamepad;
  66251. var GenericPad = /** @class */ (function (_super) {
  66252. __extends(GenericPad, _super);
  66253. function GenericPad(id, index, browserGamepad) {
  66254. var _this = _super.call(this, id, index, browserGamepad) || this;
  66255. _this.onButtonDownObservable = new BABYLON.Observable();
  66256. _this.onButtonUpObservable = new BABYLON.Observable();
  66257. _this.type = Gamepad.GENERIC;
  66258. _this._buttons = new Array(browserGamepad.buttons.length);
  66259. return _this;
  66260. }
  66261. GenericPad.prototype.onbuttondown = function (callback) {
  66262. this._onbuttondown = callback;
  66263. };
  66264. GenericPad.prototype.onbuttonup = function (callback) {
  66265. this._onbuttonup = callback;
  66266. };
  66267. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  66268. if (newValue !== currentValue) {
  66269. if (newValue === 1) {
  66270. if (this._onbuttondown) {
  66271. this._onbuttondown(buttonIndex);
  66272. }
  66273. this.onButtonDownObservable.notifyObservers(buttonIndex);
  66274. }
  66275. if (newValue === 0) {
  66276. if (this._onbuttonup) {
  66277. this._onbuttonup(buttonIndex);
  66278. }
  66279. this.onButtonUpObservable.notifyObservers(buttonIndex);
  66280. }
  66281. }
  66282. return newValue;
  66283. };
  66284. GenericPad.prototype.update = function () {
  66285. _super.prototype.update.call(this);
  66286. for (var index = 0; index < this._buttons.length; index++) {
  66287. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  66288. }
  66289. };
  66290. GenericPad.prototype.dispose = function () {
  66291. _super.prototype.dispose.call(this);
  66292. this.onButtonDownObservable.clear();
  66293. this.onButtonUpObservable.clear();
  66294. };
  66295. return GenericPad;
  66296. }(Gamepad));
  66297. BABYLON.GenericPad = GenericPad;
  66298. })(BABYLON || (BABYLON = {}));
  66299. //# sourceMappingURL=babylon.gamepad.js.map
  66300. "use strict";
  66301. var BABYLON;
  66302. (function (BABYLON) {
  66303. var Xbox360Button;
  66304. (function (Xbox360Button) {
  66305. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  66306. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  66307. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  66308. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  66309. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  66310. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  66311. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  66312. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  66313. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  66314. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  66315. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  66316. var Xbox360Dpad;
  66317. (function (Xbox360Dpad) {
  66318. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  66319. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  66320. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  66321. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  66322. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  66323. var Xbox360Pad = /** @class */ (function (_super) {
  66324. __extends(Xbox360Pad, _super);
  66325. function Xbox360Pad(id, index, gamepad, xboxOne) {
  66326. if (xboxOne === void 0) { xboxOne = false; }
  66327. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  66328. _this._leftTrigger = 0;
  66329. _this._rightTrigger = 0;
  66330. _this.onButtonDownObservable = new BABYLON.Observable();
  66331. _this.onButtonUpObservable = new BABYLON.Observable();
  66332. _this.onPadDownObservable = new BABYLON.Observable();
  66333. _this.onPadUpObservable = new BABYLON.Observable();
  66334. _this._buttonA = 0;
  66335. _this._buttonB = 0;
  66336. _this._buttonX = 0;
  66337. _this._buttonY = 0;
  66338. _this._buttonBack = 0;
  66339. _this._buttonStart = 0;
  66340. _this._buttonLB = 0;
  66341. _this._buttonRB = 0;
  66342. _this._buttonLeftStick = 0;
  66343. _this._buttonRightStick = 0;
  66344. _this._dPadUp = 0;
  66345. _this._dPadDown = 0;
  66346. _this._dPadLeft = 0;
  66347. _this._dPadRight = 0;
  66348. _this._isXboxOnePad = false;
  66349. _this.type = BABYLON.Gamepad.XBOX;
  66350. _this._isXboxOnePad = xboxOne;
  66351. return _this;
  66352. }
  66353. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  66354. this._onlefttriggerchanged = callback;
  66355. };
  66356. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  66357. this._onrighttriggerchanged = callback;
  66358. };
  66359. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  66360. get: function () {
  66361. return this._leftTrigger;
  66362. },
  66363. set: function (newValue) {
  66364. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  66365. this._onlefttriggerchanged(newValue);
  66366. }
  66367. this._leftTrigger = newValue;
  66368. },
  66369. enumerable: true,
  66370. configurable: true
  66371. });
  66372. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  66373. get: function () {
  66374. return this._rightTrigger;
  66375. },
  66376. set: function (newValue) {
  66377. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  66378. this._onrighttriggerchanged(newValue);
  66379. }
  66380. this._rightTrigger = newValue;
  66381. },
  66382. enumerable: true,
  66383. configurable: true
  66384. });
  66385. Xbox360Pad.prototype.onbuttondown = function (callback) {
  66386. this._onbuttondown = callback;
  66387. };
  66388. Xbox360Pad.prototype.onbuttonup = function (callback) {
  66389. this._onbuttonup = callback;
  66390. };
  66391. Xbox360Pad.prototype.ondpaddown = function (callback) {
  66392. this._ondpaddown = callback;
  66393. };
  66394. Xbox360Pad.prototype.ondpadup = function (callback) {
  66395. this._ondpadup = callback;
  66396. };
  66397. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  66398. if (newValue !== currentValue) {
  66399. if (newValue === 1) {
  66400. if (this._onbuttondown) {
  66401. this._onbuttondown(buttonType);
  66402. }
  66403. this.onButtonDownObservable.notifyObservers(buttonType);
  66404. }
  66405. if (newValue === 0) {
  66406. if (this._onbuttonup) {
  66407. this._onbuttonup(buttonType);
  66408. }
  66409. this.onButtonUpObservable.notifyObservers(buttonType);
  66410. }
  66411. }
  66412. return newValue;
  66413. };
  66414. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  66415. if (newValue !== currentValue) {
  66416. if (newValue === 1) {
  66417. if (this._ondpaddown) {
  66418. this._ondpaddown(buttonType);
  66419. }
  66420. this.onPadDownObservable.notifyObservers(buttonType);
  66421. }
  66422. if (newValue === 0) {
  66423. if (this._ondpadup) {
  66424. this._ondpadup(buttonType);
  66425. }
  66426. this.onPadUpObservable.notifyObservers(buttonType);
  66427. }
  66428. }
  66429. return newValue;
  66430. };
  66431. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  66432. get: function () {
  66433. return this._buttonA;
  66434. },
  66435. set: function (value) {
  66436. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  66437. },
  66438. enumerable: true,
  66439. configurable: true
  66440. });
  66441. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  66442. get: function () {
  66443. return this._buttonB;
  66444. },
  66445. set: function (value) {
  66446. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  66447. },
  66448. enumerable: true,
  66449. configurable: true
  66450. });
  66451. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  66452. get: function () {
  66453. return this._buttonX;
  66454. },
  66455. set: function (value) {
  66456. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  66457. },
  66458. enumerable: true,
  66459. configurable: true
  66460. });
  66461. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  66462. get: function () {
  66463. return this._buttonY;
  66464. },
  66465. set: function (value) {
  66466. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  66467. },
  66468. enumerable: true,
  66469. configurable: true
  66470. });
  66471. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  66472. get: function () {
  66473. return this._buttonStart;
  66474. },
  66475. set: function (value) {
  66476. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  66477. },
  66478. enumerable: true,
  66479. configurable: true
  66480. });
  66481. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  66482. get: function () {
  66483. return this._buttonBack;
  66484. },
  66485. set: function (value) {
  66486. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  66487. },
  66488. enumerable: true,
  66489. configurable: true
  66490. });
  66491. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  66492. get: function () {
  66493. return this._buttonLB;
  66494. },
  66495. set: function (value) {
  66496. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  66497. },
  66498. enumerable: true,
  66499. configurable: true
  66500. });
  66501. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  66502. get: function () {
  66503. return this._buttonRB;
  66504. },
  66505. set: function (value) {
  66506. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  66507. },
  66508. enumerable: true,
  66509. configurable: true
  66510. });
  66511. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  66512. get: function () {
  66513. return this._buttonLeftStick;
  66514. },
  66515. set: function (value) {
  66516. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  66517. },
  66518. enumerable: true,
  66519. configurable: true
  66520. });
  66521. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  66522. get: function () {
  66523. return this._buttonRightStick;
  66524. },
  66525. set: function (value) {
  66526. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  66527. },
  66528. enumerable: true,
  66529. configurable: true
  66530. });
  66531. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  66532. get: function () {
  66533. return this._dPadUp;
  66534. },
  66535. set: function (value) {
  66536. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  66537. },
  66538. enumerable: true,
  66539. configurable: true
  66540. });
  66541. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  66542. get: function () {
  66543. return this._dPadDown;
  66544. },
  66545. set: function (value) {
  66546. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  66547. },
  66548. enumerable: true,
  66549. configurable: true
  66550. });
  66551. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  66552. get: function () {
  66553. return this._dPadLeft;
  66554. },
  66555. set: function (value) {
  66556. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  66557. },
  66558. enumerable: true,
  66559. configurable: true
  66560. });
  66561. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  66562. get: function () {
  66563. return this._dPadRight;
  66564. },
  66565. set: function (value) {
  66566. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  66567. },
  66568. enumerable: true,
  66569. configurable: true
  66570. });
  66571. Xbox360Pad.prototype.update = function () {
  66572. _super.prototype.update.call(this);
  66573. if (this._isXboxOnePad) {
  66574. this.buttonA = this.browserGamepad.buttons[0].value;
  66575. this.buttonB = this.browserGamepad.buttons[1].value;
  66576. this.buttonX = this.browserGamepad.buttons[2].value;
  66577. this.buttonY = this.browserGamepad.buttons[3].value;
  66578. this.buttonLB = this.browserGamepad.buttons[4].value;
  66579. this.buttonRB = this.browserGamepad.buttons[5].value;
  66580. this.leftTrigger = this.browserGamepad.axes[2];
  66581. this.rightTrigger = this.browserGamepad.axes[5];
  66582. this.buttonBack = this.browserGamepad.buttons[9].value;
  66583. this.buttonStart = this.browserGamepad.buttons[8].value;
  66584. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  66585. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  66586. this.dPadUp = this.browserGamepad.buttons[11].value;
  66587. this.dPadDown = this.browserGamepad.buttons[12].value;
  66588. this.dPadLeft = this.browserGamepad.buttons[13].value;
  66589. this.dPadRight = this.browserGamepad.buttons[14].value;
  66590. }
  66591. else {
  66592. this.buttonA = this.browserGamepad.buttons[0].value;
  66593. this.buttonB = this.browserGamepad.buttons[1].value;
  66594. this.buttonX = this.browserGamepad.buttons[2].value;
  66595. this.buttonY = this.browserGamepad.buttons[3].value;
  66596. this.buttonLB = this.browserGamepad.buttons[4].value;
  66597. this.buttonRB = this.browserGamepad.buttons[5].value;
  66598. this.leftTrigger = this.browserGamepad.buttons[6].value;
  66599. this.rightTrigger = this.browserGamepad.buttons[7].value;
  66600. this.buttonBack = this.browserGamepad.buttons[8].value;
  66601. this.buttonStart = this.browserGamepad.buttons[9].value;
  66602. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  66603. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  66604. this.dPadUp = this.browserGamepad.buttons[12].value;
  66605. this.dPadDown = this.browserGamepad.buttons[13].value;
  66606. this.dPadLeft = this.browserGamepad.buttons[14].value;
  66607. this.dPadRight = this.browserGamepad.buttons[15].value;
  66608. }
  66609. };
  66610. Xbox360Pad.prototype.dispose = function () {
  66611. _super.prototype.dispose.call(this);
  66612. this.onButtonDownObservable.clear();
  66613. this.onButtonUpObservable.clear();
  66614. this.onPadDownObservable.clear();
  66615. this.onPadUpObservable.clear();
  66616. };
  66617. return Xbox360Pad;
  66618. }(BABYLON.Gamepad));
  66619. BABYLON.Xbox360Pad = Xbox360Pad;
  66620. })(BABYLON || (BABYLON = {}));
  66621. //# sourceMappingURL=babylon.xboxGamepad.js.map
  66622. "use strict";
  66623. var BABYLON;
  66624. (function (BABYLON) {
  66625. var PoseEnabledControllerType;
  66626. (function (PoseEnabledControllerType) {
  66627. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  66628. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  66629. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  66630. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  66631. /**
  66632. * Google Daydream
  66633. */
  66634. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  66635. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  66636. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  66637. var PoseEnabledControllerHelper = /** @class */ (function () {
  66638. function PoseEnabledControllerHelper() {
  66639. }
  66640. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  66641. // Oculus Touch
  66642. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  66643. return new BABYLON.OculusTouchController(vrGamepad);
  66644. }
  66645. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  66646. return new BABYLON.WindowsMotionController(vrGamepad);
  66647. }
  66648. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  66649. return new BABYLON.ViveController(vrGamepad);
  66650. }
  66651. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  66652. return new BABYLON.GearVRController(vrGamepad);
  66653. }
  66654. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  66655. return new BABYLON.DaydreamController(vrGamepad);
  66656. }
  66657. else {
  66658. return new BABYLON.GenericController(vrGamepad);
  66659. }
  66660. };
  66661. return PoseEnabledControllerHelper;
  66662. }());
  66663. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  66664. var PoseEnabledController = /** @class */ (function (_super) {
  66665. __extends(PoseEnabledController, _super);
  66666. function PoseEnabledController(browserGamepad) {
  66667. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  66668. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  66669. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  66670. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  66671. // Represents device position and rotation in babylon space
  66672. _this.devicePosition = BABYLON.Vector3.Zero();
  66673. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66674. _this.deviceScaleFactor = 1;
  66675. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  66676. _this._deviceToWorld = BABYLON.Matrix.Identity();
  66677. /**
  66678. * Node to be used when casting a ray from the controller
  66679. */
  66680. _this._pointingPoseNode = null;
  66681. _this._workingMatrix = BABYLON.Matrix.Identity();
  66682. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  66683. _this.controllerType = PoseEnabledControllerType.GENERIC;
  66684. _this.position = BABYLON.Vector3.Zero();
  66685. _this.rotationQuaternion = new BABYLON.Quaternion();
  66686. _this._calculatedPosition = BABYLON.Vector3.Zero();
  66687. _this._calculatedRotation = new BABYLON.Quaternion();
  66688. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  66689. return _this;
  66690. }
  66691. PoseEnabledController.prototype.update = function () {
  66692. _super.prototype.update.call(this);
  66693. var pose = this.browserGamepad.pose;
  66694. this.updateFromDevice(pose);
  66695. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  66696. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  66697. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  66698. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  66699. if (this._mesh) {
  66700. this._mesh.position.copyFrom(this.devicePosition);
  66701. if (this._mesh.rotationQuaternion) {
  66702. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66703. }
  66704. }
  66705. };
  66706. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  66707. if (poseData) {
  66708. this.rawPose = poseData;
  66709. if (poseData.position) {
  66710. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  66711. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  66712. this._deviceRoomPosition.z *= -1;
  66713. }
  66714. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  66715. this._calculatedPosition.addInPlace(this.position);
  66716. }
  66717. var pose = this.rawPose;
  66718. if (poseData.orientation && pose.orientation) {
  66719. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  66720. if (this._mesh) {
  66721. if (this._mesh.getScene().useRightHandedSystem) {
  66722. this._deviceRoomRotationQuaternion.z *= -1;
  66723. this._deviceRoomRotationQuaternion.w *= -1;
  66724. }
  66725. else {
  66726. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  66727. }
  66728. }
  66729. // if the camera is set, rotate to the camera's rotation
  66730. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  66731. }
  66732. }
  66733. };
  66734. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  66735. if (this._mesh) {
  66736. this._mesh.parent = null;
  66737. }
  66738. this._mesh = mesh;
  66739. if (this._poseControlledCamera) {
  66740. this._mesh.parent = this._poseControlledCamera;
  66741. }
  66742. if (!this._mesh.rotationQuaternion) {
  66743. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  66744. }
  66745. };
  66746. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  66747. this._poseControlledCamera = camera;
  66748. if (this._mesh) {
  66749. this._mesh.parent = this._poseControlledCamera;
  66750. }
  66751. };
  66752. PoseEnabledController.prototype.dispose = function () {
  66753. if (this._mesh) {
  66754. this._mesh.dispose();
  66755. }
  66756. this._mesh = null;
  66757. _super.prototype.dispose.call(this);
  66758. };
  66759. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  66760. get: function () {
  66761. return this._mesh;
  66762. },
  66763. enumerable: true,
  66764. configurable: true
  66765. });
  66766. PoseEnabledController.prototype.getForwardRay = function (length) {
  66767. if (length === void 0) { length = 100; }
  66768. if (!this.mesh) {
  66769. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  66770. }
  66771. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  66772. var origin = m.getTranslation();
  66773. var forward = new BABYLON.Vector3(0, 0, -1);
  66774. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66775. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66776. return new BABYLON.Ray(origin, direction, length);
  66777. };
  66778. /**
  66779. * Name of the child mesh that can be used to cast a ray from the controller
  66780. */
  66781. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  66782. return PoseEnabledController;
  66783. }(BABYLON.Gamepad));
  66784. BABYLON.PoseEnabledController = PoseEnabledController;
  66785. })(BABYLON || (BABYLON = {}));
  66786. //# sourceMappingURL=babylon.poseEnabledController.js.map
  66787. "use strict";
  66788. var BABYLON;
  66789. (function (BABYLON) {
  66790. var WebVRController = /** @class */ (function (_super) {
  66791. __extends(WebVRController, _super);
  66792. function WebVRController(vrGamepad) {
  66793. var _this = _super.call(this, vrGamepad) || this;
  66794. // Observables
  66795. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  66796. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  66797. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  66798. _this.onPadStateChangedObservable = new BABYLON.Observable();
  66799. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  66800. _this.pad = { x: 0, y: 0 };
  66801. // avoid GC, store state in a tmp object
  66802. _this._changes = {
  66803. pressChanged: false,
  66804. touchChanged: false,
  66805. valueChanged: false,
  66806. changed: false
  66807. };
  66808. _this._buttons = new Array(vrGamepad.buttons.length);
  66809. _this.hand = vrGamepad.hand;
  66810. return _this;
  66811. }
  66812. WebVRController.prototype.onButtonStateChange = function (callback) {
  66813. this._onButtonStateChange = callback;
  66814. };
  66815. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  66816. get: function () {
  66817. return this._defaultModel;
  66818. },
  66819. enumerable: true,
  66820. configurable: true
  66821. });
  66822. WebVRController.prototype.update = function () {
  66823. _super.prototype.update.call(this);
  66824. for (var index = 0; index < this._buttons.length; index++) {
  66825. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  66826. }
  66827. ;
  66828. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  66829. this.pad.x = this.leftStick.x;
  66830. this.pad.y = this.leftStick.y;
  66831. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  66832. }
  66833. };
  66834. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  66835. if (!newState) {
  66836. newState = {
  66837. pressed: false,
  66838. touched: false,
  66839. value: 0
  66840. };
  66841. }
  66842. if (!currentState) {
  66843. this._buttons[buttonIndex] = {
  66844. pressed: newState.pressed,
  66845. touched: newState.touched,
  66846. value: newState.value
  66847. };
  66848. return;
  66849. }
  66850. this._checkChanges(newState, currentState);
  66851. if (this._changes.changed) {
  66852. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  66853. this._handleButtonChange(buttonIndex, newState, this._changes);
  66854. }
  66855. this._buttons[buttonIndex].pressed = newState.pressed;
  66856. this._buttons[buttonIndex].touched = newState.touched;
  66857. // oculus triggers are never 0, thou not touched.
  66858. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  66859. };
  66860. WebVRController.prototype._checkChanges = function (newState, currentState) {
  66861. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  66862. this._changes.touchChanged = newState.touched !== currentState.touched;
  66863. this._changes.valueChanged = newState.value !== currentState.value;
  66864. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  66865. return this._changes;
  66866. };
  66867. WebVRController.prototype.dispose = function () {
  66868. _super.prototype.dispose.call(this);
  66869. this.onTriggerStateChangedObservable.clear();
  66870. this.onMainButtonStateChangedObservable.clear();
  66871. this.onSecondaryButtonStateChangedObservable.clear();
  66872. this.onPadStateChangedObservable.clear();
  66873. this.onPadValuesChangedObservable.clear();
  66874. };
  66875. return WebVRController;
  66876. }(BABYLON.PoseEnabledController));
  66877. BABYLON.WebVRController = WebVRController;
  66878. })(BABYLON || (BABYLON = {}));
  66879. //# sourceMappingURL=babylon.webVRController.js.map
  66880. "use strict";
  66881. var BABYLON;
  66882. (function (BABYLON) {
  66883. var OculusTouchController = /** @class */ (function (_super) {
  66884. __extends(OculusTouchController, _super);
  66885. function OculusTouchController(vrGamepad) {
  66886. var _this = _super.call(this, vrGamepad) || this;
  66887. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  66888. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  66889. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  66890. return _this;
  66891. }
  66892. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66893. var _this = this;
  66894. var meshName;
  66895. // Hand
  66896. if (this.hand === 'left') {
  66897. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  66898. }
  66899. else {
  66900. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  66901. }
  66902. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  66903. /*
  66904. Parent Mesh name: oculus_touch_left
  66905. - body
  66906. - trigger
  66907. - thumbstick
  66908. - grip
  66909. - button_y
  66910. - button_x
  66911. - button_enter
  66912. */
  66913. _this._defaultModel = newMeshes[1];
  66914. _this.attachToMesh(_this._defaultModel);
  66915. if (meshLoaded) {
  66916. meshLoaded(_this._defaultModel);
  66917. }
  66918. });
  66919. };
  66920. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  66921. // helper getters for left and right hand.
  66922. get: function () {
  66923. if (this.hand === 'right') {
  66924. return this.onMainButtonStateChangedObservable;
  66925. }
  66926. else {
  66927. throw new Error('No A button on left hand');
  66928. }
  66929. },
  66930. enumerable: true,
  66931. configurable: true
  66932. });
  66933. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  66934. get: function () {
  66935. if (this.hand === 'right') {
  66936. return this.onSecondaryButtonStateChangedObservable;
  66937. }
  66938. else {
  66939. throw new Error('No B button on left hand');
  66940. }
  66941. },
  66942. enumerable: true,
  66943. configurable: true
  66944. });
  66945. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  66946. get: function () {
  66947. if (this.hand === 'left') {
  66948. return this.onMainButtonStateChangedObservable;
  66949. }
  66950. else {
  66951. throw new Error('No X button on right hand');
  66952. }
  66953. },
  66954. enumerable: true,
  66955. configurable: true
  66956. });
  66957. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  66958. get: function () {
  66959. if (this.hand === 'left') {
  66960. return this.onSecondaryButtonStateChangedObservable;
  66961. }
  66962. else {
  66963. throw new Error('No Y button on right hand');
  66964. }
  66965. },
  66966. enumerable: true,
  66967. configurable: true
  66968. });
  66969. /*
  66970. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  66971. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  66972. 2) secondary trigger (same)
  66973. 3) A (right) X (left), touch, pressed = value
  66974. 4) B / Y
  66975. 5) thumb rest
  66976. */
  66977. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66978. var notifyObject = state; //{ state: state, changes: changes };
  66979. var triggerDirection = this.hand === 'right' ? -1 : 1;
  66980. switch (buttonIdx) {
  66981. case 0:
  66982. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66983. return;
  66984. case 1:// index trigger
  66985. if (this._defaultModel) {
  66986. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  66987. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  66988. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  66989. }
  66990. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66991. return;
  66992. case 2:// secondary trigger
  66993. if (this._defaultModel) {
  66994. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  66995. }
  66996. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  66997. return;
  66998. case 3:
  66999. if (this._defaultModel) {
  67000. if (notifyObject.pressed) {
  67001. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  67002. }
  67003. else {
  67004. (this._defaultModel.getChildren()[1]).position.y = 0;
  67005. }
  67006. }
  67007. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  67008. return;
  67009. case 4:
  67010. if (this._defaultModel) {
  67011. if (notifyObject.pressed) {
  67012. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  67013. }
  67014. else {
  67015. (this._defaultModel.getChildren()[2]).position.y = 0;
  67016. }
  67017. }
  67018. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  67019. return;
  67020. case 5:
  67021. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  67022. return;
  67023. }
  67024. };
  67025. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  67026. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  67027. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  67028. return OculusTouchController;
  67029. }(BABYLON.WebVRController));
  67030. BABYLON.OculusTouchController = OculusTouchController;
  67031. })(BABYLON || (BABYLON = {}));
  67032. //# sourceMappingURL=babylon.oculusTouchController.js.map
  67033. "use strict";
  67034. var BABYLON;
  67035. (function (BABYLON) {
  67036. var ViveController = /** @class */ (function (_super) {
  67037. __extends(ViveController, _super);
  67038. function ViveController(vrGamepad) {
  67039. var _this = _super.call(this, vrGamepad) || this;
  67040. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  67041. _this._invertLeftStickY = true;
  67042. return _this;
  67043. }
  67044. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67045. var _this = this;
  67046. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  67047. /*
  67048. Parent Mesh name: ViveWand
  67049. - body
  67050. - r_gripper
  67051. - l_gripper
  67052. - menu_button
  67053. - system_button
  67054. - trackpad
  67055. - trigger
  67056. - LED
  67057. */
  67058. _this._defaultModel = newMeshes[1];
  67059. _this.attachToMesh(_this._defaultModel);
  67060. if (meshLoaded) {
  67061. meshLoaded(_this._defaultModel);
  67062. }
  67063. });
  67064. };
  67065. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  67066. get: function () {
  67067. return this.onMainButtonStateChangedObservable;
  67068. },
  67069. enumerable: true,
  67070. configurable: true
  67071. });
  67072. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  67073. get: function () {
  67074. return this.onMainButtonStateChangedObservable;
  67075. },
  67076. enumerable: true,
  67077. configurable: true
  67078. });
  67079. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  67080. get: function () {
  67081. return this.onSecondaryButtonStateChangedObservable;
  67082. },
  67083. enumerable: true,
  67084. configurable: true
  67085. });
  67086. /**
  67087. * Vive mapping:
  67088. * 0: touchpad
  67089. * 1: trigger
  67090. * 2: left AND right buttons
  67091. * 3: menu button
  67092. */
  67093. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67094. var notifyObject = state; //{ state: state, changes: changes };
  67095. switch (buttonIdx) {
  67096. case 0:
  67097. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  67098. return;
  67099. case 1:// index trigger
  67100. if (this._defaultModel) {
  67101. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  67102. }
  67103. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  67104. return;
  67105. case 2:// left AND right button
  67106. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  67107. return;
  67108. case 3:
  67109. if (this._defaultModel) {
  67110. if (notifyObject.pressed) {
  67111. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  67112. }
  67113. else {
  67114. (this._defaultModel.getChildren()[2]).position.y = 0;
  67115. }
  67116. }
  67117. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  67118. return;
  67119. }
  67120. };
  67121. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  67122. ViveController.MODEL_FILENAME = 'wand.babylon';
  67123. return ViveController;
  67124. }(BABYLON.WebVRController));
  67125. BABYLON.ViveController = ViveController;
  67126. })(BABYLON || (BABYLON = {}));
  67127. //# sourceMappingURL=babylon.viveController.js.map
  67128. "use strict";
  67129. var BABYLON;
  67130. (function (BABYLON) {
  67131. var GenericController = /** @class */ (function (_super) {
  67132. __extends(GenericController, _super);
  67133. function GenericController(vrGamepad) {
  67134. return _super.call(this, vrGamepad) || this;
  67135. }
  67136. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67137. var _this = this;
  67138. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  67139. _this._defaultModel = newMeshes[1];
  67140. _this.attachToMesh(_this._defaultModel);
  67141. if (meshLoaded) {
  67142. meshLoaded(_this._defaultModel);
  67143. }
  67144. });
  67145. };
  67146. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67147. console.log("Button id: " + buttonIdx + "state: ");
  67148. console.dir(state);
  67149. };
  67150. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67151. GenericController.MODEL_FILENAME = 'generic.babylon';
  67152. return GenericController;
  67153. }(BABYLON.WebVRController));
  67154. BABYLON.GenericController = GenericController;
  67155. })(BABYLON || (BABYLON = {}));
  67156. //# sourceMappingURL=babylon.genericController.js.map
  67157. "use strict";
  67158. var BABYLON;
  67159. (function (BABYLON) {
  67160. var LoadedMeshInfo = /** @class */ (function () {
  67161. function LoadedMeshInfo() {
  67162. this.buttonMeshes = {};
  67163. this.axisMeshes = {};
  67164. }
  67165. return LoadedMeshInfo;
  67166. }());
  67167. var WindowsMotionController = /** @class */ (function (_super) {
  67168. __extends(WindowsMotionController, _super);
  67169. function WindowsMotionController(vrGamepad) {
  67170. var _this = _super.call(this, vrGamepad) || this;
  67171. _this._mapping = {
  67172. // Semantic button names
  67173. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  67174. // A mapping of the button name to glTF model node name
  67175. // that should be transformed by button value.
  67176. buttonMeshNames: {
  67177. 'trigger': 'SELECT',
  67178. 'menu': 'MENU',
  67179. 'grip': 'GRASP',
  67180. 'thumbstick': 'THUMBSTICK_PRESS',
  67181. 'trackpad': 'TOUCHPAD_PRESS'
  67182. },
  67183. // This mapping is used to translate from the Motion Controller to Babylon semantics
  67184. buttonObservableNames: {
  67185. 'trigger': 'onTriggerStateChangedObservable',
  67186. 'menu': 'onSecondaryButtonStateChangedObservable',
  67187. 'grip': 'onMainButtonStateChangedObservable',
  67188. 'thumbstick': 'onPadStateChangedObservable',
  67189. 'trackpad': 'onTrackpadChangedObservable'
  67190. },
  67191. // A mapping of the axis name to glTF model node name
  67192. // that should be transformed by axis value.
  67193. // This array mirrors the browserGamepad.axes array, such that
  67194. // the mesh corresponding to axis 0 is in this array index 0.
  67195. axisMeshNames: [
  67196. 'THUMBSTICK_X',
  67197. 'THUMBSTICK_Y',
  67198. 'TOUCHPAD_TOUCH_X',
  67199. 'TOUCHPAD_TOUCH_Y'
  67200. ],
  67201. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  67202. };
  67203. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  67204. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  67205. _this.trackpad = { x: 0, y: 0 };
  67206. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  67207. _this._loadedMeshInfo = null;
  67208. return _this;
  67209. }
  67210. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  67211. get: function () {
  67212. return this.onTriggerStateChangedObservable;
  67213. },
  67214. enumerable: true,
  67215. configurable: true
  67216. });
  67217. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  67218. get: function () {
  67219. return this.onSecondaryButtonStateChangedObservable;
  67220. },
  67221. enumerable: true,
  67222. configurable: true
  67223. });
  67224. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  67225. get: function () {
  67226. return this.onMainButtonStateChangedObservable;
  67227. },
  67228. enumerable: true,
  67229. configurable: true
  67230. });
  67231. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  67232. get: function () {
  67233. return this.onPadStateChangedObservable;
  67234. },
  67235. enumerable: true,
  67236. configurable: true
  67237. });
  67238. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  67239. get: function () {
  67240. return this.onTrackpadChangedObservable;
  67241. },
  67242. enumerable: true,
  67243. configurable: true
  67244. });
  67245. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  67246. get: function () {
  67247. return this.onTrackpadValuesChangedObservable;
  67248. },
  67249. enumerable: true,
  67250. configurable: true
  67251. });
  67252. /**
  67253. * Called once per frame by the engine.
  67254. */
  67255. WindowsMotionController.prototype.update = function () {
  67256. _super.prototype.update.call(this);
  67257. if (this.browserGamepad.axes) {
  67258. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  67259. this.trackpad.x = this.browserGamepad["axes"][2];
  67260. this.trackpad.y = this.browserGamepad["axes"][3];
  67261. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  67262. }
  67263. // Only need to animate axes if there is a loaded mesh
  67264. if (this._loadedMeshInfo) {
  67265. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  67266. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  67267. }
  67268. }
  67269. }
  67270. };
  67271. /**
  67272. * Called once for each button that changed state since the last frame
  67273. * @param buttonIdx Which button index changed
  67274. * @param state New state of the button
  67275. * @param changes Which properties on the state changed since last frame
  67276. */
  67277. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67278. var buttonName = this._mapping.buttons[buttonIdx];
  67279. if (!buttonName) {
  67280. return;
  67281. }
  67282. // Only emit events for buttons that we know how to map from index to name
  67283. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  67284. if (observable) {
  67285. observable.notifyObservers(state);
  67286. }
  67287. this.lerpButtonTransform(buttonName, state.value);
  67288. };
  67289. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  67290. // If there is no loaded mesh, there is nothing to transform.
  67291. if (!this._loadedMeshInfo) {
  67292. return;
  67293. }
  67294. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  67295. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  67296. return;
  67297. }
  67298. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  67299. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  67300. };
  67301. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  67302. if (!this._loadedMeshInfo) {
  67303. return;
  67304. }
  67305. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  67306. if (!meshInfo) {
  67307. return;
  67308. }
  67309. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  67310. return;
  67311. }
  67312. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  67313. var lerpValue = axisValue * 0.5 + 0.5;
  67314. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  67315. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  67316. };
  67317. /**
  67318. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  67319. * @param scene scene in which to add meshes
  67320. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  67321. */
  67322. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  67323. var _this = this;
  67324. if (forceDefault === void 0) { forceDefault = false; }
  67325. var path;
  67326. var filename;
  67327. // Checking if GLB loader is present
  67328. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  67329. // Determine the device specific folder based on the ID suffix
  67330. var device = 'default';
  67331. if (this.id && !forceDefault) {
  67332. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  67333. device = ((match && match[0]) || device);
  67334. }
  67335. // Hand
  67336. if (this.hand === 'left') {
  67337. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  67338. }
  67339. else {
  67340. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  67341. }
  67342. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  67343. }
  67344. else {
  67345. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  67346. path = BABYLON.GenericController.MODEL_BASE_URL;
  67347. filename = BABYLON.GenericController.MODEL_FILENAME;
  67348. }
  67349. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  67350. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  67351. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  67352. if (!_this._loadedMeshInfo) {
  67353. return;
  67354. }
  67355. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  67356. _this.attachToMesh(_this._defaultModel);
  67357. if (meshLoaded) {
  67358. meshLoaded(_this._defaultModel);
  67359. }
  67360. }, null, function (scene, message) {
  67361. BABYLON.Tools.Log(message);
  67362. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  67363. if (!forceDefault) {
  67364. _this.initControllerMesh(scene, meshLoaded, true);
  67365. }
  67366. });
  67367. };
  67368. /**
  67369. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  67370. * can be transformed by button presses and axes values, based on this._mapping.
  67371. *
  67372. * @param scene scene in which the meshes exist
  67373. * @param meshes list of meshes that make up the controller model to process
  67374. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  67375. */
  67376. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  67377. var loadedMeshInfo = null;
  67378. // Create a new mesh to contain the glTF hierarchy
  67379. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  67380. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  67381. var childMesh = null;
  67382. for (var i = 0; i < meshes.length; i++) {
  67383. var mesh = meshes[i];
  67384. if (!mesh.parent) {
  67385. // Exclude controller meshes from picking results
  67386. mesh.isPickable = false;
  67387. // Handle root node, attach to the new parentMesh
  67388. childMesh = mesh;
  67389. break;
  67390. }
  67391. }
  67392. if (childMesh) {
  67393. childMesh.setParent(parentMesh);
  67394. // Create our mesh info. Note that this method will always return non-null.
  67395. loadedMeshInfo = this.createMeshInfo(parentMesh);
  67396. }
  67397. else {
  67398. BABYLON.Tools.Warn('Could not find root node in model file.');
  67399. }
  67400. return loadedMeshInfo;
  67401. };
  67402. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  67403. var loadedMeshInfo = new LoadedMeshInfo();
  67404. var i;
  67405. loadedMeshInfo.rootNode = rootNode;
  67406. // Reset the caches
  67407. loadedMeshInfo.buttonMeshes = {};
  67408. loadedMeshInfo.axisMeshes = {};
  67409. // Button Meshes
  67410. for (i = 0; i < this._mapping.buttons.length; i++) {
  67411. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  67412. if (!buttonMeshName) {
  67413. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  67414. continue;
  67415. }
  67416. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  67417. if (!buttonMesh) {
  67418. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  67419. continue;
  67420. }
  67421. var buttonMeshInfo = {
  67422. index: i,
  67423. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  67424. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  67425. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  67426. };
  67427. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  67428. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  67429. }
  67430. else {
  67431. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  67432. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  67433. '(VALUE: ' + !!buttonMeshInfo.value +
  67434. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  67435. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  67436. ')');
  67437. }
  67438. }
  67439. // Axis Meshes
  67440. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  67441. var axisMeshName = this._mapping.axisMeshNames[i];
  67442. if (!axisMeshName) {
  67443. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  67444. continue;
  67445. }
  67446. var axisMesh = getChildByName(rootNode, axisMeshName);
  67447. if (!axisMesh) {
  67448. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  67449. continue;
  67450. }
  67451. var axisMeshInfo = {
  67452. index: i,
  67453. value: getImmediateChildByName(axisMesh, 'VALUE'),
  67454. min: getImmediateChildByName(axisMesh, 'MIN'),
  67455. max: getImmediateChildByName(axisMesh, 'MAX')
  67456. };
  67457. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  67458. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  67459. }
  67460. else {
  67461. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  67462. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  67463. '(VALUE: ' + !!axisMeshInfo.value +
  67464. ', MIN: ' + !!axisMeshInfo.min +
  67465. ', MAX:' + !!axisMeshInfo.max +
  67466. ')');
  67467. }
  67468. }
  67469. // Pointing Ray
  67470. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  67471. if (!loadedMeshInfo.pointingPoseNode) {
  67472. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  67473. }
  67474. return loadedMeshInfo;
  67475. // Look through all children recursively. This will return null if no mesh exists with the given name.
  67476. function getChildByName(node, name) {
  67477. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  67478. }
  67479. // Look through only immediate children. This will return null if no mesh exists with the given name.
  67480. function getImmediateChildByName(node, name) {
  67481. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  67482. }
  67483. };
  67484. WindowsMotionController.prototype.getForwardRay = function (length) {
  67485. if (length === void 0) { length = 100; }
  67486. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  67487. return _super.prototype.getForwardRay.call(this, length);
  67488. }
  67489. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  67490. var origin = m.getTranslation();
  67491. var forward = new BABYLON.Vector3(0, 0, -1);
  67492. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  67493. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  67494. return new BABYLON.Ray(origin, direction, length);
  67495. };
  67496. WindowsMotionController.prototype.dispose = function () {
  67497. _super.prototype.dispose.call(this);
  67498. this.onTrackpadChangedObservable.clear();
  67499. };
  67500. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  67501. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  67502. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  67503. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  67504. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  67505. return WindowsMotionController;
  67506. }(BABYLON.WebVRController));
  67507. BABYLON.WindowsMotionController = WindowsMotionController;
  67508. })(BABYLON || (BABYLON = {}));
  67509. //# sourceMappingURL=babylon.windowsMotionController.js.map
  67510. "use strict";
  67511. var BABYLON;
  67512. (function (BABYLON) {
  67513. var GearVRController = /** @class */ (function (_super) {
  67514. __extends(GearVRController, _super);
  67515. function GearVRController(vrGamepad) {
  67516. var _this = _super.call(this, vrGamepad) || this;
  67517. _this._buttonIndexToObservableNameMap = [
  67518. 'onTrackpadChangedObservable',
  67519. 'onTriggerStateChangedObservable' // Trigger
  67520. ];
  67521. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  67522. return _this;
  67523. }
  67524. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67525. var _this = this;
  67526. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  67527. _this._defaultModel = newMeshes[1];
  67528. _this.attachToMesh(_this._defaultModel);
  67529. if (meshLoaded) {
  67530. meshLoaded(_this._defaultModel);
  67531. }
  67532. });
  67533. };
  67534. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67535. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  67536. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  67537. // Only emit events for buttons that we know how to map from index to observable
  67538. var observable = this[observableName];
  67539. if (observable) {
  67540. observable.notifyObservers(state);
  67541. }
  67542. }
  67543. };
  67544. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67545. GearVRController.MODEL_FILENAME = 'generic.babylon';
  67546. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  67547. return GearVRController;
  67548. }(BABYLON.WebVRController));
  67549. BABYLON.GearVRController = GearVRController;
  67550. })(BABYLON || (BABYLON = {}));
  67551. //# sourceMappingURL=babylon.gearVRController.js.map
  67552. "use strict";
  67553. var BABYLON;
  67554. (function (BABYLON) {
  67555. /**
  67556. * Google Daydream controller
  67557. */
  67558. var DaydreamController = /** @class */ (function (_super) {
  67559. __extends(DaydreamController, _super);
  67560. function DaydreamController(vrGamepad) {
  67561. var _this = _super.call(this, vrGamepad) || this;
  67562. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  67563. return _this;
  67564. }
  67565. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67566. var _this = this;
  67567. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  67568. _this._defaultModel = newMeshes[1];
  67569. _this.attachToMesh(_this._defaultModel);
  67570. if (meshLoaded) {
  67571. meshLoaded(_this._defaultModel);
  67572. }
  67573. });
  67574. };
  67575. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67576. // Daydream controller only has 1 GamepadButton (on the trackpad).
  67577. if (buttonIdx === 0) {
  67578. var observable = this.onTriggerStateChangedObservable;
  67579. if (observable) {
  67580. observable.notifyObservers(state);
  67581. }
  67582. }
  67583. else {
  67584. // If the app or home buttons are ever made available
  67585. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  67586. }
  67587. };
  67588. /**
  67589. * Base Url for the controller model.
  67590. */
  67591. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67592. /**
  67593. * File name for the controller model.
  67594. */
  67595. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  67596. /**
  67597. * Gamepad Id prefix used to identify Daydream Controller.
  67598. */
  67599. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  67600. return DaydreamController;
  67601. }(BABYLON.WebVRController));
  67602. BABYLON.DaydreamController = DaydreamController;
  67603. })(BABYLON || (BABYLON = {}));
  67604. //# sourceMappingURL=babylon.daydreamController.js.map
  67605. "use strict";
  67606. var BABYLON;
  67607. (function (BABYLON) {
  67608. var FollowCamera = /** @class */ (function (_super) {
  67609. __extends(FollowCamera, _super);
  67610. function FollowCamera(name, position, scene, lockedTarget) {
  67611. if (lockedTarget === void 0) { lockedTarget = null; }
  67612. var _this = _super.call(this, name, position, scene) || this;
  67613. _this.radius = 12;
  67614. _this.rotationOffset = 0;
  67615. _this.heightOffset = 4;
  67616. _this.cameraAcceleration = 0.05;
  67617. _this.maxCameraSpeed = 20;
  67618. _this.lockedTarget = lockedTarget;
  67619. return _this;
  67620. }
  67621. FollowCamera.prototype.getRadians = function (degrees) {
  67622. return degrees * Math.PI / 180;
  67623. };
  67624. FollowCamera.prototype.follow = function (cameraTarget) {
  67625. if (!cameraTarget)
  67626. return;
  67627. var yRotation;
  67628. if (cameraTarget.rotationQuaternion) {
  67629. var rotMatrix = new BABYLON.Matrix();
  67630. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  67631. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  67632. }
  67633. else {
  67634. yRotation = cameraTarget.rotation.y;
  67635. }
  67636. var radians = this.getRadians(this.rotationOffset) + yRotation;
  67637. var targetPosition = cameraTarget.getAbsolutePosition();
  67638. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  67639. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  67640. var dx = targetX - this.position.x;
  67641. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  67642. var dz = (targetZ) - this.position.z;
  67643. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  67644. var vy = dy * this.cameraAcceleration;
  67645. var vz = dz * this.cameraAcceleration * 2;
  67646. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  67647. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67648. }
  67649. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  67650. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67651. }
  67652. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  67653. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67654. }
  67655. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  67656. this.setTarget(targetPosition);
  67657. };
  67658. FollowCamera.prototype._checkInputs = function () {
  67659. _super.prototype._checkInputs.call(this);
  67660. if (this.lockedTarget) {
  67661. this.follow(this.lockedTarget);
  67662. }
  67663. };
  67664. FollowCamera.prototype.getClassName = function () {
  67665. return "FollowCamera";
  67666. };
  67667. __decorate([
  67668. BABYLON.serialize()
  67669. ], FollowCamera.prototype, "radius", void 0);
  67670. __decorate([
  67671. BABYLON.serialize()
  67672. ], FollowCamera.prototype, "rotationOffset", void 0);
  67673. __decorate([
  67674. BABYLON.serialize()
  67675. ], FollowCamera.prototype, "heightOffset", void 0);
  67676. __decorate([
  67677. BABYLON.serialize()
  67678. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  67679. __decorate([
  67680. BABYLON.serialize()
  67681. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  67682. __decorate([
  67683. BABYLON.serializeAsMeshReference("lockedTargetId")
  67684. ], FollowCamera.prototype, "lockedTarget", void 0);
  67685. return FollowCamera;
  67686. }(BABYLON.TargetCamera));
  67687. BABYLON.FollowCamera = FollowCamera;
  67688. var ArcFollowCamera = /** @class */ (function (_super) {
  67689. __extends(ArcFollowCamera, _super);
  67690. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  67691. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  67692. _this.alpha = alpha;
  67693. _this.beta = beta;
  67694. _this.radius = radius;
  67695. _this.target = target;
  67696. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  67697. _this.follow();
  67698. return _this;
  67699. }
  67700. ArcFollowCamera.prototype.follow = function () {
  67701. if (!this.target) {
  67702. return;
  67703. }
  67704. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  67705. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  67706. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  67707. var targetPosition = this.target.getAbsolutePosition();
  67708. this.position = targetPosition.add(this._cartesianCoordinates);
  67709. this.setTarget(targetPosition);
  67710. };
  67711. ArcFollowCamera.prototype._checkInputs = function () {
  67712. _super.prototype._checkInputs.call(this);
  67713. this.follow();
  67714. };
  67715. ArcFollowCamera.prototype.getClassName = function () {
  67716. return "ArcFollowCamera";
  67717. };
  67718. return ArcFollowCamera;
  67719. }(BABYLON.TargetCamera));
  67720. BABYLON.ArcFollowCamera = ArcFollowCamera;
  67721. })(BABYLON || (BABYLON = {}));
  67722. //# sourceMappingURL=babylon.followCamera.js.map
  67723. "use strict";
  67724. var BABYLON;
  67725. (function (BABYLON) {
  67726. // We're mainly based on the logic defined into the FreeCamera code
  67727. var UniversalCamera = /** @class */ (function (_super) {
  67728. __extends(UniversalCamera, _super);
  67729. //-- end properties for backward compatibility for inputs
  67730. function UniversalCamera(name, position, scene) {
  67731. var _this = _super.call(this, name, position, scene) || this;
  67732. _this.inputs.addGamepad();
  67733. return _this;
  67734. }
  67735. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  67736. //-- Begin properties for backward compatibility for inputs
  67737. get: function () {
  67738. var gamepad = this.inputs.attached["gamepad"];
  67739. if (gamepad)
  67740. return gamepad.gamepadAngularSensibility;
  67741. return 0;
  67742. },
  67743. set: function (value) {
  67744. var gamepad = this.inputs.attached["gamepad"];
  67745. if (gamepad)
  67746. gamepad.gamepadAngularSensibility = value;
  67747. },
  67748. enumerable: true,
  67749. configurable: true
  67750. });
  67751. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  67752. get: function () {
  67753. var gamepad = this.inputs.attached["gamepad"];
  67754. if (gamepad)
  67755. return gamepad.gamepadMoveSensibility;
  67756. return 0;
  67757. },
  67758. set: function (value) {
  67759. var gamepad = this.inputs.attached["gamepad"];
  67760. if (gamepad)
  67761. gamepad.gamepadMoveSensibility = value;
  67762. },
  67763. enumerable: true,
  67764. configurable: true
  67765. });
  67766. UniversalCamera.prototype.getClassName = function () {
  67767. return "UniversalCamera";
  67768. };
  67769. return UniversalCamera;
  67770. }(BABYLON.TouchCamera));
  67771. BABYLON.UniversalCamera = UniversalCamera;
  67772. })(BABYLON || (BABYLON = {}));
  67773. //# sourceMappingURL=babylon.universalCamera.js.map
  67774. "use strict";
  67775. var BABYLON;
  67776. (function (BABYLON) {
  67777. // We're mainly based on the logic defined into the FreeCamera code
  67778. var GamepadCamera = /** @class */ (function (_super) {
  67779. __extends(GamepadCamera, _super);
  67780. //-- end properties for backward compatibility for inputs
  67781. function GamepadCamera(name, position, scene) {
  67782. return _super.call(this, name, position, scene) || this;
  67783. }
  67784. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  67785. //-- Begin properties for backward compatibility for inputs
  67786. get: function () {
  67787. var gamepad = this.inputs.attached["gamepad"];
  67788. if (gamepad)
  67789. return gamepad.gamepadAngularSensibility;
  67790. return 0;
  67791. },
  67792. set: function (value) {
  67793. var gamepad = this.inputs.attached["gamepad"];
  67794. if (gamepad)
  67795. gamepad.gamepadAngularSensibility = value;
  67796. },
  67797. enumerable: true,
  67798. configurable: true
  67799. });
  67800. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  67801. get: function () {
  67802. var gamepad = this.inputs.attached["gamepad"];
  67803. if (gamepad)
  67804. return gamepad.gamepadMoveSensibility;
  67805. return 0;
  67806. },
  67807. set: function (value) {
  67808. var gamepad = this.inputs.attached["gamepad"];
  67809. if (gamepad)
  67810. gamepad.gamepadMoveSensibility = value;
  67811. },
  67812. enumerable: true,
  67813. configurable: true
  67814. });
  67815. GamepadCamera.prototype.getClassName = function () {
  67816. return "GamepadCamera";
  67817. };
  67818. return GamepadCamera;
  67819. }(BABYLON.UniversalCamera));
  67820. BABYLON.GamepadCamera = GamepadCamera;
  67821. })(BABYLON || (BABYLON = {}));
  67822. //# sourceMappingURL=babylon.gamepadCamera.js.map
  67823. "use strict";
  67824. var BABYLON;
  67825. (function (BABYLON) {
  67826. var PostProcessRenderPipelineManager = /** @class */ (function () {
  67827. function PostProcessRenderPipelineManager() {
  67828. this._renderPipelines = {};
  67829. }
  67830. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  67831. this._renderPipelines[renderPipeline._name] = renderPipeline;
  67832. };
  67833. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  67834. if (unique === void 0) { unique = false; }
  67835. var renderPipeline = this._renderPipelines[renderPipelineName];
  67836. if (!renderPipeline) {
  67837. return;
  67838. }
  67839. renderPipeline._attachCameras(cameras, unique);
  67840. };
  67841. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  67842. var renderPipeline = this._renderPipelines[renderPipelineName];
  67843. if (!renderPipeline) {
  67844. return;
  67845. }
  67846. renderPipeline._detachCameras(cameras);
  67847. };
  67848. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67849. var renderPipeline = this._renderPipelines[renderPipelineName];
  67850. if (!renderPipeline) {
  67851. return;
  67852. }
  67853. renderPipeline._enableEffect(renderEffectName, cameras);
  67854. };
  67855. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67856. var renderPipeline = this._renderPipelines[renderPipelineName];
  67857. if (!renderPipeline) {
  67858. return;
  67859. }
  67860. renderPipeline._disableEffect(renderEffectName, cameras);
  67861. };
  67862. PostProcessRenderPipelineManager.prototype.update = function () {
  67863. for (var renderPipelineName in this._renderPipelines) {
  67864. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67865. var pipeline = this._renderPipelines[renderPipelineName];
  67866. if (!pipeline.isSupported) {
  67867. pipeline.dispose();
  67868. delete this._renderPipelines[renderPipelineName];
  67869. }
  67870. else {
  67871. pipeline._update();
  67872. }
  67873. }
  67874. }
  67875. };
  67876. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  67877. for (var renderPipelineName in this._renderPipelines) {
  67878. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67879. var pipeline = this._renderPipelines[renderPipelineName];
  67880. pipeline._rebuild();
  67881. }
  67882. }
  67883. };
  67884. PostProcessRenderPipelineManager.prototype.dispose = function () {
  67885. for (var renderPipelineName in this._renderPipelines) {
  67886. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67887. var pipeline = this._renderPipelines[renderPipelineName];
  67888. pipeline.dispose();
  67889. }
  67890. }
  67891. };
  67892. return PostProcessRenderPipelineManager;
  67893. }());
  67894. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  67895. })(BABYLON || (BABYLON = {}));
  67896. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  67897. "use strict";
  67898. var BABYLON;
  67899. (function (BABYLON) {
  67900. /**
  67901. * This represents a set of one or more post processes in Babylon.
  67902. * A post process can be used to apply a shader to a texture after it is rendered.
  67903. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  67904. */
  67905. var PostProcessRenderEffect = /** @class */ (function () {
  67906. /**
  67907. * Instantiates a post process render effect.
  67908. * A post process can be used to apply a shader to a texture after it is rendered.
  67909. * @param engine The engine the effect is tied to
  67910. * @param name The name of the effect
  67911. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  67912. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  67913. */
  67914. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  67915. this._name = name;
  67916. this._singleInstance = singleInstance || true;
  67917. this._getPostProcesses = getPostProcesses;
  67918. this._cameras = {};
  67919. this._indicesForCamera = {};
  67920. this._postProcesses = {};
  67921. }
  67922. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  67923. /**
  67924. * Checks if all the post processes in the effect are supported.
  67925. */
  67926. get: function () {
  67927. for (var index in this._postProcesses) {
  67928. for (var ppIndex in this._postProcesses[index]) {
  67929. if (!this._postProcesses[index][ppIndex].isSupported) {
  67930. return false;
  67931. }
  67932. }
  67933. }
  67934. return true;
  67935. },
  67936. enumerable: true,
  67937. configurable: true
  67938. });
  67939. /**
  67940. * Updates the current state of the effect
  67941. */
  67942. PostProcessRenderEffect.prototype._update = function () {
  67943. };
  67944. /**
  67945. * Attaches the effect on cameras
  67946. * @param cameras The camera to attach to.
  67947. */
  67948. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  67949. var _this = this;
  67950. var cameraKey;
  67951. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67952. if (!cams) {
  67953. return;
  67954. }
  67955. for (var i = 0; i < cams.length; i++) {
  67956. var camera = cams[i];
  67957. var cameraName = camera.name;
  67958. if (this._singleInstance) {
  67959. cameraKey = 0;
  67960. }
  67961. else {
  67962. cameraKey = cameraName;
  67963. }
  67964. if (!this._postProcesses[cameraKey]) {
  67965. var postProcess = this._getPostProcesses();
  67966. if (postProcess) {
  67967. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  67968. }
  67969. }
  67970. if (!this._indicesForCamera[cameraName]) {
  67971. this._indicesForCamera[cameraName] = [];
  67972. }
  67973. this._postProcesses[cameraKey].forEach(function (postProcess) {
  67974. var index = camera.attachPostProcess(postProcess);
  67975. _this._indicesForCamera[cameraName].push(index);
  67976. });
  67977. if (!this._cameras[cameraName]) {
  67978. this._cameras[cameraName] = camera;
  67979. }
  67980. }
  67981. };
  67982. /**
  67983. * Detatches the effect on cameras
  67984. * @param cameras The camera to detatch from.
  67985. */
  67986. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  67987. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67988. if (!cams) {
  67989. return;
  67990. }
  67991. for (var i = 0; i < cams.length; i++) {
  67992. var camera = cams[i];
  67993. var cameraName = camera.name;
  67994. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67995. camera.detachPostProcess(postProcess);
  67996. });
  67997. if (this._cameras[cameraName]) {
  67998. //this._indicesForCamera.splice(index, 1);
  67999. this._cameras[cameraName] = null;
  68000. }
  68001. }
  68002. };
  68003. /**
  68004. * Enables the effect on given cameras
  68005. * @param cameras The camera to enable.
  68006. */
  68007. PostProcessRenderEffect.prototype._enable = function (cameras) {
  68008. var _this = this;
  68009. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68010. if (!cams) {
  68011. return;
  68012. }
  68013. for (var i = 0; i < cams.length; i++) {
  68014. var camera = cams[i];
  68015. var cameraName = camera.name;
  68016. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  68017. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  68018. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  68019. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  68020. });
  68021. }
  68022. }
  68023. }
  68024. };
  68025. /**
  68026. * Disables the effect on the given cameras
  68027. * @param cameras The camera to disable.
  68028. */
  68029. PostProcessRenderEffect.prototype._disable = function (cameras) {
  68030. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68031. if (!cams) {
  68032. return;
  68033. }
  68034. for (var i = 0; i < cams.length; i++) {
  68035. var camera = cams[i];
  68036. var cameraName = camera.name;
  68037. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  68038. camera.detachPostProcess(postProcess);
  68039. });
  68040. }
  68041. };
  68042. /**
  68043. * Gets a list of the post processes contained in the effect.
  68044. * @param camera The camera to get the post processes on.
  68045. * @returns The list of the post processes in the effect.
  68046. */
  68047. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  68048. if (this._singleInstance) {
  68049. return this._postProcesses[0];
  68050. }
  68051. else {
  68052. if (!camera) {
  68053. return null;
  68054. }
  68055. return this._postProcesses[camera.name];
  68056. }
  68057. };
  68058. return PostProcessRenderEffect;
  68059. }());
  68060. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  68061. })(BABYLON || (BABYLON = {}));
  68062. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  68063. "use strict";
  68064. var BABYLON;
  68065. (function (BABYLON) {
  68066. var PostProcessRenderPipeline = /** @class */ (function () {
  68067. function PostProcessRenderPipeline(engine, name) {
  68068. this.engine = engine;
  68069. this._name = name;
  68070. this._renderEffects = {};
  68071. this._renderEffectsForIsolatedPass = new Array();
  68072. this._cameras = [];
  68073. }
  68074. PostProcessRenderPipeline.prototype.getClassName = function () {
  68075. return "PostProcessRenderPipeline";
  68076. };
  68077. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  68078. get: function () {
  68079. for (var renderEffectName in this._renderEffects) {
  68080. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68081. if (!this._renderEffects[renderEffectName].isSupported) {
  68082. return false;
  68083. }
  68084. }
  68085. }
  68086. return true;
  68087. },
  68088. enumerable: true,
  68089. configurable: true
  68090. });
  68091. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  68092. this._renderEffects[renderEffect._name] = renderEffect;
  68093. };
  68094. // private
  68095. PostProcessRenderPipeline.prototype._rebuild = function () {
  68096. };
  68097. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  68098. var renderEffects = this._renderEffects[renderEffectName];
  68099. if (!renderEffects) {
  68100. return;
  68101. }
  68102. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  68103. };
  68104. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  68105. var renderEffects = this._renderEffects[renderEffectName];
  68106. if (!renderEffects) {
  68107. return;
  68108. }
  68109. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  68110. };
  68111. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  68112. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68113. if (!cams) {
  68114. return;
  68115. }
  68116. var indicesToDelete = [];
  68117. var i;
  68118. for (i = 0; i < cams.length; i++) {
  68119. var camera = cams[i];
  68120. var cameraName = camera.name;
  68121. if (this._cameras.indexOf(camera) === -1) {
  68122. this._cameras[cameraName] = camera;
  68123. }
  68124. else if (unique) {
  68125. indicesToDelete.push(i);
  68126. }
  68127. }
  68128. for (i = 0; i < indicesToDelete.length; i++) {
  68129. cameras.splice(indicesToDelete[i], 1);
  68130. }
  68131. for (var renderEffectName in this._renderEffects) {
  68132. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68133. this._renderEffects[renderEffectName]._attachCameras(cams);
  68134. }
  68135. }
  68136. };
  68137. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  68138. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68139. if (!cams) {
  68140. return;
  68141. }
  68142. for (var renderEffectName in this._renderEffects) {
  68143. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68144. this._renderEffects[renderEffectName]._detachCameras(cams);
  68145. }
  68146. }
  68147. for (var i = 0; i < cams.length; i++) {
  68148. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  68149. }
  68150. };
  68151. PostProcessRenderPipeline.prototype._update = function () {
  68152. for (var renderEffectName in this._renderEffects) {
  68153. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68154. this._renderEffects[renderEffectName]._update();
  68155. }
  68156. }
  68157. for (var i = 0; i < this._cameras.length; i++) {
  68158. var cameraName = this._cameras[i].name;
  68159. if (this._renderEffectsForIsolatedPass[cameraName]) {
  68160. this._renderEffectsForIsolatedPass[cameraName]._update();
  68161. }
  68162. }
  68163. };
  68164. PostProcessRenderPipeline.prototype._reset = function () {
  68165. this._renderEffects = {};
  68166. this._renderEffectsForIsolatedPass = new Array();
  68167. };
  68168. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  68169. // 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)
  68170. var effectKeys = Object.keys(this._renderEffects);
  68171. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  68172. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  68173. if (postProcesses) {
  68174. postProcesses[0].samples = 4;
  68175. return true;
  68176. }
  68177. }
  68178. return false;
  68179. };
  68180. PostProcessRenderPipeline.prototype.dispose = function () {
  68181. // Must be implemented by children
  68182. };
  68183. __decorate([
  68184. BABYLON.serialize()
  68185. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  68186. return PostProcessRenderPipeline;
  68187. }());
  68188. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  68189. })(BABYLON || (BABYLON = {}));
  68190. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  68191. "use strict";
  68192. var BABYLON;
  68193. (function (BABYLON) {
  68194. /**
  68195. * This represents a depth renderer in Babylon.
  68196. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  68197. */
  68198. var DepthRenderer = /** @class */ (function () {
  68199. /**
  68200. * Instantiates a depth renderer
  68201. * @param scene The scene the renderer belongs to
  68202. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  68203. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  68204. */
  68205. function DepthRenderer(scene, type, camera) {
  68206. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  68207. if (camera === void 0) { camera = null; }
  68208. var _this = this;
  68209. this._scene = scene;
  68210. this._camera = camera;
  68211. var engine = scene.getEngine();
  68212. // Render target
  68213. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  68214. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68215. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68216. this._depthMap.refreshRate = 1;
  68217. this._depthMap.renderParticles = false;
  68218. this._depthMap.renderList = null;
  68219. // Camera to get depth map from to support multiple concurrent cameras
  68220. this._depthMap.activeCamera = this._camera;
  68221. this._depthMap.ignoreCameraViewport = true;
  68222. this._depthMap.useCameraPostProcesses = false;
  68223. // set default depth value to 1.0 (far away)
  68224. this._depthMap.onClearObservable.add(function (engine) {
  68225. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  68226. });
  68227. // Custom render function
  68228. var renderSubMesh = function (subMesh) {
  68229. var mesh = subMesh.getRenderingMesh();
  68230. var scene = _this._scene;
  68231. var engine = scene.getEngine();
  68232. var material = subMesh.getMaterial();
  68233. if (!material) {
  68234. return;
  68235. }
  68236. // Culling and reverse (right handed system)
  68237. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68238. // Managing instances
  68239. var batch = mesh._getInstancesRenderList(subMesh._id);
  68240. if (batch.mustReturn) {
  68241. return;
  68242. }
  68243. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68244. var camera = _this._camera || scene.activeCamera;
  68245. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  68246. engine.enableEffect(_this._effect);
  68247. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68248. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68249. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  68250. // Alpha test
  68251. if (material && material.needAlphaTesting()) {
  68252. var alphaTexture = material.getAlphaTestTexture();
  68253. if (alphaTexture) {
  68254. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68255. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68256. }
  68257. }
  68258. // Bones
  68259. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68260. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68261. }
  68262. // Draw
  68263. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68264. }
  68265. };
  68266. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68267. var index;
  68268. if (depthOnlySubMeshes.length) {
  68269. engine.setColorWrite(false);
  68270. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68271. renderSubMesh(depthOnlySubMeshes.data[index]);
  68272. }
  68273. engine.setColorWrite(true);
  68274. }
  68275. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68276. renderSubMesh(opaqueSubMeshes.data[index]);
  68277. }
  68278. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68279. renderSubMesh(alphaTestSubMeshes.data[index]);
  68280. }
  68281. };
  68282. }
  68283. /**
  68284. * Creates the depth rendering effect and checks if the effect is ready.
  68285. * @param subMesh The submesh to be used to render the depth map of
  68286. * @param useInstances If multiple world instances should be used
  68287. * @returns if the depth renderer is ready to render the depth map
  68288. */
  68289. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  68290. var material = subMesh.getMaterial();
  68291. if (material.disableDepthWrite) {
  68292. return false;
  68293. }
  68294. var defines = [];
  68295. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68296. var mesh = subMesh.getMesh();
  68297. // Alpha test
  68298. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  68299. defines.push("#define ALPHATEST");
  68300. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68301. attribs.push(BABYLON.VertexBuffer.UVKind);
  68302. defines.push("#define UV1");
  68303. }
  68304. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68305. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68306. defines.push("#define UV2");
  68307. }
  68308. }
  68309. // Bones
  68310. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68311. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68312. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68313. if (mesh.numBoneInfluencers > 4) {
  68314. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68315. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68316. }
  68317. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68318. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68319. }
  68320. else {
  68321. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68322. }
  68323. // Instances
  68324. if (useInstances) {
  68325. defines.push("#define INSTANCES");
  68326. attribs.push("world0");
  68327. attribs.push("world1");
  68328. attribs.push("world2");
  68329. attribs.push("world3");
  68330. }
  68331. // Get correct effect
  68332. var join = defines.join("\n");
  68333. if (this._cachedDefines !== join) {
  68334. this._cachedDefines = join;
  68335. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  68336. }
  68337. return this._effect.isReady();
  68338. };
  68339. /**
  68340. * Gets the texture which the depth map will be written to.
  68341. * @returns The depth map texture
  68342. */
  68343. DepthRenderer.prototype.getDepthMap = function () {
  68344. return this._depthMap;
  68345. };
  68346. /**
  68347. * Disposes of the depth renderer.
  68348. */
  68349. DepthRenderer.prototype.dispose = function () {
  68350. this._depthMap.dispose();
  68351. };
  68352. return DepthRenderer;
  68353. }());
  68354. BABYLON.DepthRenderer = DepthRenderer;
  68355. })(BABYLON || (BABYLON = {}));
  68356. //# sourceMappingURL=babylon.depthRenderer.js.map
  68357. "use strict";
  68358. var BABYLON;
  68359. (function (BABYLON) {
  68360. var SSAORenderingPipeline = /** @class */ (function (_super) {
  68361. __extends(SSAORenderingPipeline, _super);
  68362. /**
  68363. * @constructor
  68364. * @param {string} name - The rendering pipeline name
  68365. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68366. * @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 }
  68367. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68368. */
  68369. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  68370. var _this = _super.call(this, scene.getEngine(), name) || this;
  68371. // Members
  68372. /**
  68373. * The PassPostProcess id in the pipeline that contains the original scene color
  68374. * @type {string}
  68375. */
  68376. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68377. /**
  68378. * The SSAO PostProcess id in the pipeline
  68379. * @type {string}
  68380. */
  68381. _this.SSAORenderEffect = "SSAORenderEffect";
  68382. /**
  68383. * The horizontal blur PostProcess id in the pipeline
  68384. * @type {string}
  68385. */
  68386. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68387. /**
  68388. * The vertical blur PostProcess id in the pipeline
  68389. * @type {string}
  68390. */
  68391. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68392. /**
  68393. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68394. * @type {string}
  68395. */
  68396. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68397. /**
  68398. * The output strength of the SSAO post-process. Default value is 1.0.
  68399. * @type {number}
  68400. */
  68401. _this.totalStrength = 1.0;
  68402. /**
  68403. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  68404. * @type {number}
  68405. */
  68406. _this.radius = 0.0001;
  68407. /**
  68408. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  68409. * Must not be equal to fallOff and superior to fallOff.
  68410. * Default value is 0.975
  68411. * @type {number}
  68412. */
  68413. _this.area = 0.0075;
  68414. /**
  68415. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  68416. * Must not be equal to area and inferior to area.
  68417. * Default value is 0.0
  68418. * @type {number}
  68419. */
  68420. _this.fallOff = 0.000001;
  68421. /**
  68422. * The base color of the SSAO post-process
  68423. * The final result is "base + ssao" between [0, 1]
  68424. * @type {number}
  68425. */
  68426. _this.base = 0.5;
  68427. _this._firstUpdate = true;
  68428. _this._scene = scene;
  68429. // Set up assets
  68430. _this._createRandomTexture();
  68431. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68432. var ssaoRatio = ratio.ssaoRatio || ratio;
  68433. var combineRatio = ratio.combineRatio || ratio;
  68434. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68435. _this._createSSAOPostProcess(ssaoRatio);
  68436. _this._createBlurPostProcess(ssaoRatio);
  68437. _this._createSSAOCombinePostProcess(combineRatio);
  68438. // Set up pipeline
  68439. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68440. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68441. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68442. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68443. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68444. // Finish
  68445. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68446. if (cameras)
  68447. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68448. return _this;
  68449. }
  68450. // Public Methods
  68451. /**
  68452. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68453. */
  68454. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68455. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68456. for (var i = 0; i < this._scene.cameras.length; i++) {
  68457. var camera = this._scene.cameras[i];
  68458. this._originalColorPostProcess.dispose(camera);
  68459. this._ssaoPostProcess.dispose(camera);
  68460. this._blurHPostProcess.dispose(camera);
  68461. this._blurVPostProcess.dispose(camera);
  68462. this._ssaoCombinePostProcess.dispose(camera);
  68463. }
  68464. this._randomTexture.dispose();
  68465. if (disableDepthRender)
  68466. this._scene.disableDepthRenderer();
  68467. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68468. _super.prototype.dispose.call(this);
  68469. };
  68470. // Private Methods
  68471. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  68472. var _this = this;
  68473. var size = 16;
  68474. 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);
  68475. 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);
  68476. this._blurHPostProcess.onActivateObservable.add(function () {
  68477. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  68478. _this._blurHPostProcess.kernel = size * dw;
  68479. });
  68480. this._blurVPostProcess.onActivateObservable.add(function () {
  68481. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  68482. _this._blurVPostProcess.kernel = size * dw;
  68483. });
  68484. };
  68485. SSAORenderingPipeline.prototype._rebuild = function () {
  68486. this._firstUpdate = true;
  68487. _super.prototype._rebuild.call(this);
  68488. };
  68489. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68490. var _this = this;
  68491. var numSamples = 16;
  68492. var sampleSphere = [
  68493. 0.5381, 0.1856, -0.4319,
  68494. 0.1379, 0.2486, 0.4430,
  68495. 0.3371, 0.5679, -0.0057,
  68496. -0.6999, -0.0451, -0.0019,
  68497. 0.0689, -0.1598, -0.8547,
  68498. 0.0560, 0.0069, -0.1843,
  68499. -0.0146, 0.1402, 0.0762,
  68500. 0.0100, -0.1924, -0.0344,
  68501. -0.3577, -0.5301, -0.4358,
  68502. -0.3169, 0.1063, 0.0158,
  68503. 0.0103, -0.5869, 0.0046,
  68504. -0.0897, -0.4940, 0.3287,
  68505. 0.7119, -0.0154, -0.0918,
  68506. -0.0533, 0.0596, -0.5411,
  68507. 0.0352, -0.0631, 0.5460,
  68508. -0.4776, 0.2847, -0.0271
  68509. ];
  68510. var samplesFactor = 1.0 / numSamples;
  68511. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  68512. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68513. "area", "fallOff", "base", "range", "viewport"
  68514. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68515. this._ssaoPostProcess.onApply = function (effect) {
  68516. if (_this._firstUpdate) {
  68517. effect.setArray3("sampleSphere", sampleSphere);
  68518. effect.setFloat("samplesFactor", samplesFactor);
  68519. effect.setFloat("randTextureTiles", 4.0);
  68520. }
  68521. effect.setFloat("totalStrength", _this.totalStrength);
  68522. effect.setFloat("radius", _this.radius);
  68523. effect.setFloat("area", _this.area);
  68524. effect.setFloat("fallOff", _this.fallOff);
  68525. effect.setFloat("base", _this.base);
  68526. effect.setTexture("textureSampler", _this._depthTexture);
  68527. effect.setTexture("randomSampler", _this._randomTexture);
  68528. };
  68529. };
  68530. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68531. var _this = this;
  68532. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68533. this._ssaoCombinePostProcess.onApply = function (effect) {
  68534. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68535. };
  68536. };
  68537. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  68538. var size = 512;
  68539. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68540. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68541. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68542. var context = this._randomTexture.getContext();
  68543. var rand = function (min, max) {
  68544. return Math.random() * (max - min) + min;
  68545. };
  68546. var randVector = BABYLON.Vector3.Zero();
  68547. for (var x = 0; x < size; x++) {
  68548. for (var y = 0; y < size; y++) {
  68549. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  68550. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  68551. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  68552. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68553. context.fillRect(x, y, 1, 1);
  68554. }
  68555. }
  68556. this._randomTexture.update(false);
  68557. };
  68558. __decorate([
  68559. BABYLON.serialize()
  68560. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  68561. __decorate([
  68562. BABYLON.serialize()
  68563. ], SSAORenderingPipeline.prototype, "radius", void 0);
  68564. __decorate([
  68565. BABYLON.serialize()
  68566. ], SSAORenderingPipeline.prototype, "area", void 0);
  68567. __decorate([
  68568. BABYLON.serialize()
  68569. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  68570. __decorate([
  68571. BABYLON.serialize()
  68572. ], SSAORenderingPipeline.prototype, "base", void 0);
  68573. return SSAORenderingPipeline;
  68574. }(BABYLON.PostProcessRenderPipeline));
  68575. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  68576. })(BABYLON || (BABYLON = {}));
  68577. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  68578. "use strict";
  68579. var BABYLON;
  68580. (function (BABYLON) {
  68581. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  68582. __extends(SSAO2RenderingPipeline, _super);
  68583. /**
  68584. * @constructor
  68585. * @param {string} name - The rendering pipeline name
  68586. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68587. * @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 }
  68588. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68589. */
  68590. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  68591. var _this = _super.call(this, scene.getEngine(), name) || this;
  68592. // Members
  68593. /**
  68594. * The PassPostProcess id in the pipeline that contains the original scene color
  68595. * @type {string}
  68596. */
  68597. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68598. /**
  68599. * The SSAO PostProcess id in the pipeline
  68600. * @type {string}
  68601. */
  68602. _this.SSAORenderEffect = "SSAORenderEffect";
  68603. /**
  68604. * The horizontal blur PostProcess id in the pipeline
  68605. * @type {string}
  68606. */
  68607. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68608. /**
  68609. * The vertical blur PostProcess id in the pipeline
  68610. * @type {string}
  68611. */
  68612. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68613. /**
  68614. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68615. * @type {string}
  68616. */
  68617. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68618. /**
  68619. * The output strength of the SSAO post-process. Default value is 1.0.
  68620. * @type {number}
  68621. */
  68622. _this.totalStrength = 1.0;
  68623. /**
  68624. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  68625. * @type {number}
  68626. */
  68627. _this.maxZ = 100.0;
  68628. /**
  68629. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  68630. * @type {number}
  68631. */
  68632. _this.minZAspect = 0.2;
  68633. /**
  68634. * Number of samples used for the SSAO calculations. Default value is 8
  68635. * @type {number}
  68636. */
  68637. _this._samples = 8;
  68638. /**
  68639. * Are we using bilateral blur ?
  68640. * @type {boolean}
  68641. */
  68642. _this._expensiveBlur = true;
  68643. /**
  68644. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  68645. * @type {number}
  68646. */
  68647. _this.radius = 2.0;
  68648. /**
  68649. * The base color of the SSAO post-process
  68650. * The final result is "base + ssao" between [0, 1]
  68651. * @type {number}
  68652. */
  68653. _this.base = 0.1;
  68654. _this._firstUpdate = true;
  68655. _this._scene = scene;
  68656. if (!_this.isSupported) {
  68657. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  68658. return _this;
  68659. }
  68660. var ssaoRatio = ratio.ssaoRatio || ratio;
  68661. var blurRatio = ratio.blurRatio || ratio;
  68662. // Set up assets
  68663. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  68664. _this._createRandomTexture();
  68665. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  68666. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  68667. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68668. _this._createSSAOPostProcess(1.0);
  68669. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  68670. _this._createSSAOCombinePostProcess(blurRatio);
  68671. // Set up pipeline
  68672. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68673. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68674. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68675. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68676. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68677. // Finish
  68678. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68679. if (cameras)
  68680. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68681. return _this;
  68682. }
  68683. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  68684. get: function () {
  68685. return this._samples;
  68686. },
  68687. set: function (n) {
  68688. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  68689. this._samples = n;
  68690. this._sampleSphere = this._generateHemisphere();
  68691. this._firstUpdate = true;
  68692. },
  68693. enumerable: true,
  68694. configurable: true
  68695. });
  68696. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  68697. get: function () {
  68698. return this._expensiveBlur;
  68699. },
  68700. set: function (b) {
  68701. 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"]);
  68702. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  68703. this._expensiveBlur = b;
  68704. this._firstUpdate = true;
  68705. },
  68706. enumerable: true,
  68707. configurable: true
  68708. });
  68709. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  68710. /**
  68711. * Support test.
  68712. * @type {boolean}
  68713. */
  68714. get: function () {
  68715. var engine = BABYLON.Engine.LastCreatedEngine;
  68716. if (!engine) {
  68717. return false;
  68718. }
  68719. return engine.getCaps().drawBuffersExtension;
  68720. },
  68721. enumerable: true,
  68722. configurable: true
  68723. });
  68724. // Public Methods
  68725. /**
  68726. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68727. */
  68728. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  68729. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  68730. for (var i = 0; i < this._scene.cameras.length; i++) {
  68731. var camera = this._scene.cameras[i];
  68732. this._originalColorPostProcess.dispose(camera);
  68733. this._ssaoPostProcess.dispose(camera);
  68734. this._blurHPostProcess.dispose(camera);
  68735. this._blurVPostProcess.dispose(camera);
  68736. this._ssaoCombinePostProcess.dispose(camera);
  68737. }
  68738. this._randomTexture.dispose();
  68739. if (disableGeometryBufferRenderer)
  68740. this._scene.disableGeometryBufferRenderer();
  68741. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68742. _super.prototype.dispose.call(this);
  68743. };
  68744. // Private Methods
  68745. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  68746. var _this = this;
  68747. this._samplerOffsets = [];
  68748. var expensive = this.expensiveBlur;
  68749. for (var i = -8; i < 8; i++) {
  68750. this._samplerOffsets.push(i * 2 + 0.5);
  68751. }
  68752. 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");
  68753. this._blurHPostProcess.onApply = function (effect) {
  68754. if (!_this._scene.activeCamera) {
  68755. return;
  68756. }
  68757. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  68758. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68759. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68760. effect.setFloat("radius", _this.radius);
  68761. effect.setTexture("depthSampler", _this._depthTexture);
  68762. if (_this._firstUpdate) {
  68763. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68764. }
  68765. };
  68766. 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");
  68767. this._blurVPostProcess.onApply = function (effect) {
  68768. if (!_this._scene.activeCamera) {
  68769. return;
  68770. }
  68771. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  68772. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68773. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68774. effect.setFloat("radius", _this.radius);
  68775. effect.setTexture("depthSampler", _this._depthTexture);
  68776. if (_this._firstUpdate) {
  68777. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68778. _this._firstUpdate = false;
  68779. }
  68780. };
  68781. };
  68782. SSAO2RenderingPipeline.prototype._rebuild = function () {
  68783. this._firstUpdate = true;
  68784. _super.prototype._rebuild.call(this);
  68785. };
  68786. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  68787. var numSamples = this.samples;
  68788. var result = [];
  68789. var vector, scale;
  68790. var rand = function (min, max) {
  68791. return Math.random() * (max - min) + min;
  68792. };
  68793. var i = 0;
  68794. while (i < numSamples) {
  68795. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  68796. vector.normalize();
  68797. scale = i / numSamples;
  68798. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  68799. vector.scaleInPlace(scale);
  68800. result.push(vector.x, vector.y, vector.z);
  68801. i++;
  68802. }
  68803. return result;
  68804. };
  68805. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68806. var _this = this;
  68807. var numSamples = this.samples;
  68808. this._sampleSphere = this._generateHemisphere();
  68809. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  68810. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68811. "base", "range", "projection", "near", "far", "texelSize",
  68812. "xViewport", "yViewport", "maxZ", "minZAspect"
  68813. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68814. this._ssaoPostProcess.onApply = function (effect) {
  68815. if (_this._firstUpdate) {
  68816. effect.setArray3("sampleSphere", _this._sampleSphere);
  68817. effect.setFloat("randTextureTiles", 4.0);
  68818. }
  68819. if (!_this._scene.activeCamera) {
  68820. return;
  68821. }
  68822. effect.setFloat("samplesFactor", 1 / _this.samples);
  68823. effect.setFloat("totalStrength", _this.totalStrength);
  68824. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  68825. effect.setFloat("radius", _this.radius);
  68826. effect.setFloat("maxZ", _this.maxZ);
  68827. effect.setFloat("minZAspect", _this.minZAspect);
  68828. effect.setFloat("base", _this.base);
  68829. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68830. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68831. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  68832. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  68833. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  68834. effect.setTexture("textureSampler", _this._depthTexture);
  68835. effect.setTexture("normalSampler", _this._normalTexture);
  68836. effect.setTexture("randomSampler", _this._randomTexture);
  68837. };
  68838. };
  68839. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68840. var _this = this;
  68841. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68842. this._ssaoCombinePostProcess.onApply = function (effect) {
  68843. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68844. };
  68845. };
  68846. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  68847. var size = 512;
  68848. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68849. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68850. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68851. var context = this._randomTexture.getContext();
  68852. var rand = function (min, max) {
  68853. return Math.random() * (max - min) + min;
  68854. };
  68855. var randVector = BABYLON.Vector3.Zero();
  68856. for (var x = 0; x < size; x++) {
  68857. for (var y = 0; y < size; y++) {
  68858. randVector.x = rand(0.0, 1.0);
  68859. randVector.y = rand(0.0, 1.0);
  68860. randVector.z = 0.0;
  68861. randVector.normalize();
  68862. randVector.scaleInPlace(255);
  68863. randVector.x = Math.floor(randVector.x);
  68864. randVector.y = Math.floor(randVector.y);
  68865. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68866. context.fillRect(x, y, 1, 1);
  68867. }
  68868. }
  68869. this._randomTexture.update(false);
  68870. };
  68871. __decorate([
  68872. BABYLON.serialize()
  68873. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  68874. __decorate([
  68875. BABYLON.serialize()
  68876. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  68877. __decorate([
  68878. BABYLON.serialize()
  68879. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  68880. __decorate([
  68881. BABYLON.serialize("samples")
  68882. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  68883. __decorate([
  68884. BABYLON.serialize("expensiveBlur")
  68885. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  68886. __decorate([
  68887. BABYLON.serialize()
  68888. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  68889. __decorate([
  68890. BABYLON.serialize()
  68891. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  68892. return SSAO2RenderingPipeline;
  68893. }(BABYLON.PostProcessRenderPipeline));
  68894. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  68895. })(BABYLON || (BABYLON = {}));
  68896. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  68897. "use strict";
  68898. // BABYLON.JS Chromatic Aberration GLSL Shader
  68899. // Author: Olivier Guyot
  68900. // Separates very slightly R, G and B colors on the edges of the screen
  68901. // Inspired by Francois Tarlier & Martins Upitis
  68902. var BABYLON;
  68903. (function (BABYLON) {
  68904. var LensRenderingPipeline = /** @class */ (function (_super) {
  68905. __extends(LensRenderingPipeline, _super);
  68906. /**
  68907. * @constructor
  68908. *
  68909. * Effect parameters are as follow:
  68910. * {
  68911. * chromatic_aberration: number; // from 0 to x (1 for realism)
  68912. * edge_blur: number; // from 0 to x (1 for realism)
  68913. * distortion: number; // from 0 to x (1 for realism)
  68914. * grain_amount: number; // from 0 to 1
  68915. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  68916. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  68917. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  68918. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  68919. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  68920. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  68921. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  68922. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  68923. * }
  68924. * Note: if an effect parameter is unset, effect is disabled
  68925. *
  68926. * @param {string} name - The rendering pipeline name
  68927. * @param {object} parameters - An object containing all parameters (see above)
  68928. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68929. * @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)
  68930. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68931. */
  68932. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  68933. if (ratio === void 0) { ratio = 1.0; }
  68934. var _this = _super.call(this, scene.getEngine(), name) || this;
  68935. // Lens effects can be of the following:
  68936. // - chromatic aberration (slight shift of RGB colors)
  68937. // - blur on the edge of the lens
  68938. // - lens distortion
  68939. // - depth-of-field blur & highlights enhancing
  68940. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  68941. // - grain effect (noise or custom texture)
  68942. // Two additional texture samplers are needed:
  68943. // - depth map (for depth-of-field)
  68944. // - grain texture
  68945. /**
  68946. * The chromatic aberration PostProcess id in the pipeline
  68947. * @type {string}
  68948. */
  68949. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  68950. /**
  68951. * The highlights enhancing PostProcess id in the pipeline
  68952. * @type {string}
  68953. */
  68954. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  68955. /**
  68956. * The depth-of-field PostProcess id in the pipeline
  68957. * @type {string}
  68958. */
  68959. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  68960. _this._scene = scene;
  68961. // Fetch texture samplers
  68962. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68963. if (parameters.grain_texture) {
  68964. _this._grainTexture = parameters.grain_texture;
  68965. }
  68966. else {
  68967. _this._createGrainTexture();
  68968. }
  68969. // save parameters
  68970. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  68971. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  68972. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  68973. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  68974. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  68975. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  68976. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  68977. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  68978. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  68979. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  68980. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  68981. // Create effects
  68982. _this._createChromaticAberrationPostProcess(ratio);
  68983. _this._createHighlightsPostProcess(ratio);
  68984. _this._createDepthOfFieldPostProcess(ratio / 4);
  68985. // Set up pipeline
  68986. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  68987. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  68988. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  68989. if (_this._highlightsGain === -1) {
  68990. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  68991. }
  68992. // Finish
  68993. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68994. if (cameras) {
  68995. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68996. }
  68997. return _this;
  68998. }
  68999. // public methods (self explanatory)
  69000. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  69001. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  69002. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  69003. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  69004. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  69005. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  69006. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  69007. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  69008. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  69009. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  69010. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  69011. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  69012. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  69013. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  69014. };
  69015. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  69016. this._highlightsPostProcess.updateEffect();
  69017. };
  69018. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  69019. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  69020. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  69021. this._highlightsGain = amount;
  69022. };
  69023. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  69024. if (this._highlightsGain === -1) {
  69025. this._highlightsGain = 1.0;
  69026. }
  69027. this._highlightsThreshold = amount;
  69028. };
  69029. LensRenderingPipeline.prototype.disableHighlights = function () {
  69030. this._highlightsGain = -1;
  69031. };
  69032. /**
  69033. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  69034. */
  69035. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  69036. if (disableDepthRender === void 0) { disableDepthRender = false; }
  69037. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  69038. this._chromaticAberrationPostProcess = null;
  69039. this._highlightsPostProcess = null;
  69040. this._depthOfFieldPostProcess = null;
  69041. this._grainTexture.dispose();
  69042. if (disableDepthRender)
  69043. this._scene.disableDepthRenderer();
  69044. };
  69045. // colors shifting and distortion
  69046. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  69047. var _this = this;
  69048. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  69049. [], // samplers
  69050. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  69051. this._chromaticAberrationPostProcess.onApply = function (effect) {
  69052. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  69053. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69054. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69055. effect.setFloat('radialIntensity', 1);
  69056. effect.setFloat2('direction', 17, 17);
  69057. effect.setFloat2('centerPosition', 0.5, 0.5);
  69058. };
  69059. };
  69060. // highlights enhancing
  69061. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  69062. var _this = this;
  69063. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  69064. [], // samplers
  69065. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  69066. this._highlightsPostProcess.onApply = function (effect) {
  69067. effect.setFloat('gain', _this._highlightsGain);
  69068. effect.setFloat('threshold', _this._highlightsThreshold);
  69069. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  69070. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69071. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69072. };
  69073. };
  69074. // colors shifting and distortion
  69075. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  69076. var _this = this;
  69077. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  69078. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  69079. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  69080. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  69081. this._depthOfFieldPostProcess.onApply = function (effect) {
  69082. effect.setTexture("depthSampler", _this._depthTexture);
  69083. effect.setTexture("grainSampler", _this._grainTexture);
  69084. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  69085. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  69086. effect.setFloat('grain_amount', _this._grainAmount);
  69087. effect.setBool('blur_noise', _this._blurNoise);
  69088. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69089. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69090. effect.setFloat('distortion', _this._distortion);
  69091. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  69092. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  69093. effect.setFloat('aperture', _this._dofAperture);
  69094. effect.setFloat('darken', _this._dofDarken);
  69095. effect.setFloat('edge_blur', _this._edgeBlur);
  69096. effect.setBool('highlights', (_this._highlightsGain !== -1));
  69097. if (_this._scene.activeCamera) {
  69098. effect.setFloat('near', _this._scene.activeCamera.minZ);
  69099. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  69100. }
  69101. };
  69102. };
  69103. // creates a black and white random noise texture, 512x512
  69104. LensRenderingPipeline.prototype._createGrainTexture = function () {
  69105. var size = 512;
  69106. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69107. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  69108. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  69109. var context = this._grainTexture.getContext();
  69110. var rand = function (min, max) {
  69111. return Math.random() * (max - min) + min;
  69112. };
  69113. var value;
  69114. for (var x = 0; x < size; x++) {
  69115. for (var y = 0; y < size; y++) {
  69116. value = Math.floor(rand(0.42, 0.58) * 255);
  69117. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  69118. context.fillRect(x, y, 1, 1);
  69119. }
  69120. }
  69121. this._grainTexture.update(false);
  69122. };
  69123. return LensRenderingPipeline;
  69124. }(BABYLON.PostProcessRenderPipeline));
  69125. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  69126. })(BABYLON || (BABYLON = {}));
  69127. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  69128. "use strict";
  69129. var BABYLON;
  69130. (function (BABYLON) {
  69131. var StandardRenderingPipeline = /** @class */ (function (_super) {
  69132. __extends(StandardRenderingPipeline, _super);
  69133. /**
  69134. * @constructor
  69135. * @param {string} name - The rendering pipeline name
  69136. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69137. * @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)
  69138. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  69139. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69140. */
  69141. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  69142. if (originalPostProcess === void 0) { originalPostProcess = null; }
  69143. var _this = _super.call(this, scene.getEngine(), name) || this;
  69144. _this.downSampleX4PostProcess = null;
  69145. _this.brightPassPostProcess = null;
  69146. _this.blurHPostProcesses = [];
  69147. _this.blurVPostProcesses = [];
  69148. _this.textureAdderPostProcess = null;
  69149. _this.volumetricLightPostProcess = null;
  69150. _this.volumetricLightSmoothXPostProcess = null;
  69151. _this.volumetricLightSmoothYPostProcess = null;
  69152. _this.volumetricLightMergePostProces = null;
  69153. _this.volumetricLightFinalPostProcess = null;
  69154. _this.luminancePostProcess = null;
  69155. _this.luminanceDownSamplePostProcesses = [];
  69156. _this.hdrPostProcess = null;
  69157. _this.textureAdderFinalPostProcess = null;
  69158. _this.lensFlareFinalPostProcess = null;
  69159. _this.hdrFinalPostProcess = null;
  69160. _this.lensFlarePostProcess = null;
  69161. _this.lensFlareComposePostProcess = null;
  69162. _this.motionBlurPostProcess = null;
  69163. _this.depthOfFieldPostProcess = null;
  69164. // Values
  69165. _this.brightThreshold = 1.0;
  69166. _this.blurWidth = 512.0;
  69167. _this.horizontalBlur = false;
  69168. _this.exposure = 1.0;
  69169. _this.lensTexture = null;
  69170. _this.volumetricLightCoefficient = 0.2;
  69171. _this.volumetricLightPower = 4.0;
  69172. _this.volumetricLightBlurScale = 64.0;
  69173. _this.sourceLight = null;
  69174. _this.hdrMinimumLuminance = 1.0;
  69175. _this.hdrDecreaseRate = 0.5;
  69176. _this.hdrIncreaseRate = 0.5;
  69177. _this.lensColorTexture = null;
  69178. _this.lensFlareStrength = 20.0;
  69179. _this.lensFlareGhostDispersal = 1.4;
  69180. _this.lensFlareHaloWidth = 0.7;
  69181. _this.lensFlareDistortionStrength = 16.0;
  69182. _this.lensStarTexture = null;
  69183. _this.lensFlareDirtTexture = null;
  69184. _this.depthOfFieldDistance = 10.0;
  69185. _this.depthOfFieldBlurWidth = 64.0;
  69186. _this.motionStrength = 1.0;
  69187. // IAnimatable
  69188. _this.animations = [];
  69189. _this._currentDepthOfFieldSource = null;
  69190. _this._hdrCurrentLuminance = 1.0;
  69191. // Getters and setters
  69192. _this._bloomEnabled = true;
  69193. _this._depthOfFieldEnabled = false;
  69194. _this._vlsEnabled = false;
  69195. _this._lensFlareEnabled = false;
  69196. _this._hdrEnabled = false;
  69197. _this._motionBlurEnabled = false;
  69198. _this._motionBlurSamples = 64.0;
  69199. _this._volumetricLightStepsCount = 50.0;
  69200. _this._cameras = cameras || [];
  69201. // Initialize
  69202. _this._scene = scene;
  69203. _this._basePostProcess = originalPostProcess;
  69204. _this._ratio = ratio;
  69205. // Misc
  69206. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69207. // Finish
  69208. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69209. _this._buildPipeline();
  69210. return _this;
  69211. }
  69212. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  69213. get: function () {
  69214. return this._bloomEnabled;
  69215. },
  69216. set: function (enabled) {
  69217. if (this._bloomEnabled === enabled) {
  69218. return;
  69219. }
  69220. this._bloomEnabled = enabled;
  69221. this._buildPipeline();
  69222. },
  69223. enumerable: true,
  69224. configurable: true
  69225. });
  69226. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  69227. get: function () {
  69228. return this._depthOfFieldEnabled;
  69229. },
  69230. set: function (enabled) {
  69231. if (this._depthOfFieldEnabled === enabled) {
  69232. return;
  69233. }
  69234. this._depthOfFieldEnabled = enabled;
  69235. this._buildPipeline();
  69236. },
  69237. enumerable: true,
  69238. configurable: true
  69239. });
  69240. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  69241. get: function () {
  69242. return this._lensFlareEnabled;
  69243. },
  69244. set: function (enabled) {
  69245. if (this._lensFlareEnabled === enabled) {
  69246. return;
  69247. }
  69248. this._lensFlareEnabled = enabled;
  69249. this._buildPipeline();
  69250. },
  69251. enumerable: true,
  69252. configurable: true
  69253. });
  69254. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  69255. get: function () {
  69256. return this._hdrEnabled;
  69257. },
  69258. set: function (enabled) {
  69259. if (this._hdrEnabled === enabled) {
  69260. return;
  69261. }
  69262. this._hdrEnabled = enabled;
  69263. this._buildPipeline();
  69264. },
  69265. enumerable: true,
  69266. configurable: true
  69267. });
  69268. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  69269. get: function () {
  69270. return this._vlsEnabled;
  69271. },
  69272. set: function (enabled) {
  69273. if (this._vlsEnabled === enabled) {
  69274. return;
  69275. }
  69276. if (enabled) {
  69277. var geometry = this._scene.enableGeometryBufferRenderer();
  69278. if (!geometry) {
  69279. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  69280. return;
  69281. }
  69282. }
  69283. this._vlsEnabled = enabled;
  69284. this._buildPipeline();
  69285. },
  69286. enumerable: true,
  69287. configurable: true
  69288. });
  69289. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  69290. get: function () {
  69291. return this._motionBlurEnabled;
  69292. },
  69293. set: function (enabled) {
  69294. if (this._motionBlurEnabled === enabled) {
  69295. return;
  69296. }
  69297. this._motionBlurEnabled = enabled;
  69298. this._buildPipeline();
  69299. },
  69300. enumerable: true,
  69301. configurable: true
  69302. });
  69303. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  69304. get: function () {
  69305. return this._volumetricLightStepsCount;
  69306. },
  69307. set: function (count) {
  69308. if (this.volumetricLightPostProcess) {
  69309. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  69310. }
  69311. this._volumetricLightStepsCount = count;
  69312. },
  69313. enumerable: true,
  69314. configurable: true
  69315. });
  69316. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  69317. get: function () {
  69318. return this._motionBlurSamples;
  69319. },
  69320. set: function (samples) {
  69321. if (this.motionBlurPostProcess) {
  69322. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  69323. }
  69324. this._motionBlurSamples = samples;
  69325. },
  69326. enumerable: true,
  69327. configurable: true
  69328. });
  69329. StandardRenderingPipeline.prototype._buildPipeline = function () {
  69330. var _this = this;
  69331. var ratio = this._ratio;
  69332. var scene = this._scene;
  69333. this._disposePostProcesses();
  69334. this._reset();
  69335. // Create pass post-process
  69336. if (!this._basePostProcess) {
  69337. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  69338. this.originalPostProcess.onApply = function (effect) {
  69339. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  69340. };
  69341. }
  69342. else {
  69343. this.originalPostProcess = this._basePostProcess;
  69344. }
  69345. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  69346. this._currentDepthOfFieldSource = this.originalPostProcess;
  69347. if (this._vlsEnabled) {
  69348. // Create volumetric light
  69349. this._createVolumetricLightPostProcess(scene, ratio);
  69350. // Create volumetric light final post-process
  69351. 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);
  69352. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  69353. }
  69354. if (this._bloomEnabled) {
  69355. // Create down sample X4 post-process
  69356. this._createDownSampleX4PostProcess(scene, ratio / 2);
  69357. // Create bright pass post-process
  69358. this._createBrightPassPostProcess(scene, ratio / 2);
  69359. // Create gaussian blur post-processes (down sampling blurs)
  69360. this._createBlurPostProcesses(scene, ratio / 4, 1);
  69361. // Create texture adder post-process
  69362. this._createTextureAdderPostProcess(scene, ratio);
  69363. // Create depth-of-field source post-process
  69364. 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);
  69365. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  69366. }
  69367. if (this._lensFlareEnabled) {
  69368. // Create lens flare post-process
  69369. this._createLensFlarePostProcess(scene, ratio);
  69370. // Create depth-of-field source post-process post lens-flare and disable it now
  69371. 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);
  69372. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  69373. }
  69374. if (this._hdrEnabled) {
  69375. // Create luminance
  69376. this._createLuminancePostProcesses(scene, this._floatTextureType);
  69377. // Create HDR
  69378. this._createHdrPostProcess(scene, ratio);
  69379. // Create depth-of-field source post-process post hdr and disable it now
  69380. 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);
  69381. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  69382. }
  69383. if (this._depthOfFieldEnabled) {
  69384. // Create gaussian blur used by depth-of-field
  69385. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  69386. // Create depth-of-field post-process
  69387. this._createDepthOfFieldPostProcess(scene, ratio);
  69388. }
  69389. if (this._motionBlurEnabled) {
  69390. // Create motion blur post-process
  69391. this._createMotionBlurPostProcess(scene, ratio);
  69392. }
  69393. if (this._cameras !== null) {
  69394. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69395. }
  69396. };
  69397. // Down Sample X4 Post-Processs
  69398. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  69399. var _this = this;
  69400. var downSampleX4Offsets = new Array(32);
  69401. 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);
  69402. this.downSampleX4PostProcess.onApply = function (effect) {
  69403. var id = 0;
  69404. var width = _this.downSampleX4PostProcess.width;
  69405. var height = _this.downSampleX4PostProcess.height;
  69406. for (var i = -2; i < 2; i++) {
  69407. for (var j = -2; j < 2; j++) {
  69408. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  69409. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  69410. id += 2;
  69411. }
  69412. }
  69413. effect.setArray2("dsOffsets", downSampleX4Offsets);
  69414. };
  69415. // Add to pipeline
  69416. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  69417. };
  69418. // Brightpass Post-Process
  69419. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  69420. var _this = this;
  69421. var brightOffsets = new Array(8);
  69422. 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);
  69423. this.brightPassPostProcess.onApply = function (effect) {
  69424. var sU = (1.0 / _this.brightPassPostProcess.width);
  69425. var sV = (1.0 / _this.brightPassPostProcess.height);
  69426. brightOffsets[0] = -0.5 * sU;
  69427. brightOffsets[1] = 0.5 * sV;
  69428. brightOffsets[2] = 0.5 * sU;
  69429. brightOffsets[3] = 0.5 * sV;
  69430. brightOffsets[4] = -0.5 * sU;
  69431. brightOffsets[5] = -0.5 * sV;
  69432. brightOffsets[6] = 0.5 * sU;
  69433. brightOffsets[7] = -0.5 * sV;
  69434. effect.setArray2("dsOffsets", brightOffsets);
  69435. effect.setFloat("brightThreshold", _this.brightThreshold);
  69436. };
  69437. // Add to pipeline
  69438. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  69439. };
  69440. // Create blur H&V post-processes
  69441. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  69442. var _this = this;
  69443. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  69444. var engine = scene.getEngine();
  69445. 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);
  69446. 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);
  69447. blurX.onActivateObservable.add(function () {
  69448. var dw = blurX.width / engine.getRenderWidth();
  69449. blurX.kernel = _this[blurWidthKey] * dw;
  69450. });
  69451. blurY.onActivateObservable.add(function () {
  69452. var dw = blurY.height / engine.getRenderHeight();
  69453. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  69454. });
  69455. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  69456. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  69457. this.blurHPostProcesses.push(blurX);
  69458. this.blurVPostProcesses.push(blurY);
  69459. };
  69460. // Create texture adder post-process
  69461. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  69462. var _this = this;
  69463. 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);
  69464. this.textureAdderPostProcess.onApply = function (effect) {
  69465. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  69466. effect.setTexture("lensSampler", _this.lensTexture);
  69467. effect.setFloat("exposure", _this.exposure);
  69468. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  69469. };
  69470. // Add to pipeline
  69471. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  69472. };
  69473. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  69474. var _this = this;
  69475. var geometryRenderer = scene.enableGeometryBufferRenderer();
  69476. geometryRenderer.enablePosition = true;
  69477. var geometry = geometryRenderer.getGBuffer();
  69478. // Base post-process
  69479. 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));
  69480. var depthValues = BABYLON.Vector2.Zero();
  69481. this.volumetricLightPostProcess.onApply = function (effect) {
  69482. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  69483. var generator = _this.sourceLight.getShadowGenerator();
  69484. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  69485. effect.setTexture("positionSampler", geometry.textures[2]);
  69486. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  69487. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  69488. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  69489. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  69490. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  69491. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  69492. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  69493. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  69494. effect.setVector2("depthValues", depthValues);
  69495. }
  69496. };
  69497. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  69498. // Smooth
  69499. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  69500. // Merge
  69501. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  69502. this.volumetricLightMergePostProces.onApply = function (effect) {
  69503. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  69504. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  69505. };
  69506. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  69507. };
  69508. // Create luminance
  69509. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  69510. var _this = this;
  69511. // Create luminance
  69512. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  69513. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  69514. var offsets = [];
  69515. this.luminancePostProcess.onApply = function (effect) {
  69516. var sU = (1.0 / _this.luminancePostProcess.width);
  69517. var sV = (1.0 / _this.luminancePostProcess.height);
  69518. offsets[0] = -0.5 * sU;
  69519. offsets[1] = 0.5 * sV;
  69520. offsets[2] = 0.5 * sU;
  69521. offsets[3] = 0.5 * sV;
  69522. offsets[4] = -0.5 * sU;
  69523. offsets[5] = -0.5 * sV;
  69524. offsets[6] = 0.5 * sU;
  69525. offsets[7] = -0.5 * sV;
  69526. effect.setArray2("lumOffsets", offsets);
  69527. };
  69528. // Add to pipeline
  69529. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  69530. // Create down sample luminance
  69531. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  69532. var size = Math.pow(3, i);
  69533. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  69534. if (i === 0) {
  69535. defines += "#define FINAL_DOWN_SAMPLER";
  69536. }
  69537. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  69538. this.luminanceDownSamplePostProcesses.push(postProcess);
  69539. }
  69540. // Create callbacks and add effects
  69541. var lastLuminance = this.luminancePostProcess;
  69542. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  69543. var downSampleOffsets = new Array(18);
  69544. pp.onApply = function (effect) {
  69545. if (!lastLuminance) {
  69546. return;
  69547. }
  69548. var id = 0;
  69549. for (var x = -1; x < 2; x++) {
  69550. for (var y = -1; y < 2; y++) {
  69551. downSampleOffsets[id] = x / lastLuminance.width;
  69552. downSampleOffsets[id + 1] = y / lastLuminance.height;
  69553. id += 2;
  69554. }
  69555. }
  69556. effect.setArray2("dsOffsets", downSampleOffsets);
  69557. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  69558. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69559. lastLuminance = _this.luminancePostProcess;
  69560. }
  69561. else {
  69562. lastLuminance = pp;
  69563. }
  69564. };
  69565. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69566. pp.onAfterRender = function (effect) {
  69567. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  69568. 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);
  69569. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  69570. };
  69571. }
  69572. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  69573. });
  69574. };
  69575. // Create HDR post-process
  69576. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  69577. var _this = this;
  69578. 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);
  69579. var outputLiminance = 1;
  69580. var time = 0;
  69581. var lastTime = 0;
  69582. this.hdrPostProcess.onApply = function (effect) {
  69583. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  69584. time += scene.getEngine().getDeltaTime();
  69585. if (outputLiminance < 0) {
  69586. outputLiminance = _this._hdrCurrentLuminance;
  69587. }
  69588. else {
  69589. var dt = (lastTime - time) / 1000.0;
  69590. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  69591. outputLiminance += _this.hdrDecreaseRate * dt;
  69592. }
  69593. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  69594. outputLiminance -= _this.hdrIncreaseRate * dt;
  69595. }
  69596. else {
  69597. outputLiminance = _this._hdrCurrentLuminance;
  69598. }
  69599. }
  69600. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  69601. effect.setFloat("averageLuminance", outputLiminance);
  69602. lastTime = time;
  69603. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  69604. };
  69605. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  69606. };
  69607. // Create lens flare post-process
  69608. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  69609. var _this = this;
  69610. 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);
  69611. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  69612. this._createBlurPostProcesses(scene, ratio / 4, 2);
  69613. 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);
  69614. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  69615. var resolution = new BABYLON.Vector2(0, 0);
  69616. // Lens flare
  69617. this.lensFlarePostProcess.onApply = function (effect) {
  69618. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  69619. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  69620. effect.setFloat("strength", _this.lensFlareStrength);
  69621. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  69622. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  69623. // Shift
  69624. resolution.x = _this.lensFlarePostProcess.width;
  69625. resolution.y = _this.lensFlarePostProcess.height;
  69626. effect.setVector2("resolution", resolution);
  69627. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  69628. };
  69629. // Compose
  69630. 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);
  69631. 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);
  69632. this.lensFlareComposePostProcess.onApply = function (effect) {
  69633. if (!_this._scene.activeCamera) {
  69634. return;
  69635. }
  69636. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69637. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  69638. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  69639. // Lens start rotation matrix
  69640. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  69641. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  69642. 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));
  69643. camRot *= 4.0;
  69644. 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);
  69645. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  69646. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  69647. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  69648. };
  69649. };
  69650. // Create depth-of-field post-process
  69651. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  69652. var _this = this;
  69653. 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);
  69654. this.depthOfFieldPostProcess.onApply = function (effect) {
  69655. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69656. effect.setTexture("depthSampler", _this._getDepthTexture());
  69657. effect.setFloat("distance", _this.depthOfFieldDistance);
  69658. };
  69659. // Add to pipeline
  69660. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  69661. };
  69662. // Create motion blur post-process
  69663. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  69664. var _this = this;
  69665. 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);
  69666. var motionScale = 0;
  69667. var prevViewProjection = BABYLON.Matrix.Identity();
  69668. var invViewProjection = BABYLON.Matrix.Identity();
  69669. var viewProjection = BABYLON.Matrix.Identity();
  69670. var screenSize = BABYLON.Vector2.Zero();
  69671. this.motionBlurPostProcess.onApply = function (effect) {
  69672. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  69673. viewProjection.invertToRef(invViewProjection);
  69674. effect.setMatrix("inverseViewProjection", invViewProjection);
  69675. effect.setMatrix("prevViewProjection", prevViewProjection);
  69676. prevViewProjection = viewProjection;
  69677. screenSize.x = _this.motionBlurPostProcess.width;
  69678. screenSize.y = _this.motionBlurPostProcess.height;
  69679. effect.setVector2("screenSize", screenSize);
  69680. motionScale = scene.getEngine().getFps() / 60.0;
  69681. effect.setFloat("motionScale", motionScale);
  69682. effect.setFloat("motionStrength", _this.motionStrength);
  69683. effect.setTexture("depthSampler", _this._getDepthTexture());
  69684. };
  69685. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  69686. };
  69687. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  69688. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  69689. var renderer = this._scene.enableGeometryBufferRenderer();
  69690. return renderer.getGBuffer().textures[0];
  69691. }
  69692. return this._scene.enableDepthRenderer().getDepthMap();
  69693. };
  69694. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  69695. for (var i = 0; i < this._cameras.length; i++) {
  69696. var camera = this._cameras[i];
  69697. if (this.originalPostProcess) {
  69698. this.originalPostProcess.dispose(camera);
  69699. }
  69700. if (this.downSampleX4PostProcess) {
  69701. this.downSampleX4PostProcess.dispose(camera);
  69702. }
  69703. if (this.brightPassPostProcess) {
  69704. this.brightPassPostProcess.dispose(camera);
  69705. }
  69706. if (this.textureAdderPostProcess) {
  69707. this.textureAdderPostProcess.dispose(camera);
  69708. }
  69709. if (this.textureAdderFinalPostProcess) {
  69710. this.textureAdderFinalPostProcess.dispose(camera);
  69711. }
  69712. if (this.volumetricLightPostProcess) {
  69713. this.volumetricLightPostProcess.dispose(camera);
  69714. }
  69715. if (this.volumetricLightSmoothXPostProcess) {
  69716. this.volumetricLightSmoothXPostProcess.dispose(camera);
  69717. }
  69718. if (this.volumetricLightSmoothYPostProcess) {
  69719. this.volumetricLightSmoothYPostProcess.dispose(camera);
  69720. }
  69721. if (this.volumetricLightMergePostProces) {
  69722. this.volumetricLightMergePostProces.dispose(camera);
  69723. }
  69724. if (this.volumetricLightFinalPostProcess) {
  69725. this.volumetricLightFinalPostProcess.dispose(camera);
  69726. }
  69727. if (this.lensFlarePostProcess) {
  69728. this.lensFlarePostProcess.dispose(camera);
  69729. }
  69730. if (this.lensFlareComposePostProcess) {
  69731. this.lensFlareComposePostProcess.dispose(camera);
  69732. }
  69733. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  69734. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  69735. }
  69736. if (this.luminancePostProcess) {
  69737. this.luminancePostProcess.dispose(camera);
  69738. }
  69739. if (this.hdrPostProcess) {
  69740. this.hdrPostProcess.dispose(camera);
  69741. }
  69742. if (this.hdrFinalPostProcess) {
  69743. this.hdrFinalPostProcess.dispose(camera);
  69744. }
  69745. if (this.depthOfFieldPostProcess) {
  69746. this.depthOfFieldPostProcess.dispose(camera);
  69747. }
  69748. if (this.motionBlurPostProcess) {
  69749. this.motionBlurPostProcess.dispose(camera);
  69750. }
  69751. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  69752. this.blurHPostProcesses[j].dispose(camera);
  69753. }
  69754. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  69755. this.blurVPostProcesses[j].dispose(camera);
  69756. }
  69757. }
  69758. this.originalPostProcess = null;
  69759. this.downSampleX4PostProcess = null;
  69760. this.brightPassPostProcess = null;
  69761. this.textureAdderPostProcess = null;
  69762. this.textureAdderFinalPostProcess = null;
  69763. this.volumetricLightPostProcess = null;
  69764. this.volumetricLightSmoothXPostProcess = null;
  69765. this.volumetricLightSmoothYPostProcess = null;
  69766. this.volumetricLightMergePostProces = null;
  69767. this.volumetricLightFinalPostProcess = null;
  69768. this.lensFlarePostProcess = null;
  69769. this.lensFlareComposePostProcess = null;
  69770. this.luminancePostProcess = null;
  69771. this.hdrPostProcess = null;
  69772. this.hdrFinalPostProcess = null;
  69773. this.depthOfFieldPostProcess = null;
  69774. this.motionBlurPostProcess = null;
  69775. this.luminanceDownSamplePostProcesses = [];
  69776. this.blurHPostProcesses = [];
  69777. this.blurVPostProcesses = [];
  69778. };
  69779. // Dispose
  69780. StandardRenderingPipeline.prototype.dispose = function () {
  69781. this._disposePostProcesses();
  69782. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69783. _super.prototype.dispose.call(this);
  69784. };
  69785. // Serialize rendering pipeline
  69786. StandardRenderingPipeline.prototype.serialize = function () {
  69787. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69788. serializationObject.customType = "StandardRenderingPipeline";
  69789. return serializationObject;
  69790. };
  69791. /**
  69792. * Static members
  69793. */
  69794. // Parse serialized pipeline
  69795. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69796. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  69797. };
  69798. // Luminance steps
  69799. StandardRenderingPipeline.LuminanceSteps = 6;
  69800. __decorate([
  69801. BABYLON.serialize()
  69802. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  69803. __decorate([
  69804. BABYLON.serialize()
  69805. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  69806. __decorate([
  69807. BABYLON.serialize()
  69808. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  69809. __decorate([
  69810. BABYLON.serialize()
  69811. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  69812. __decorate([
  69813. BABYLON.serializeAsTexture("lensTexture")
  69814. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  69815. __decorate([
  69816. BABYLON.serialize()
  69817. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  69818. __decorate([
  69819. BABYLON.serialize()
  69820. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  69821. __decorate([
  69822. BABYLON.serialize()
  69823. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  69824. __decorate([
  69825. BABYLON.serialize()
  69826. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  69827. __decorate([
  69828. BABYLON.serialize()
  69829. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  69830. __decorate([
  69831. BABYLON.serialize()
  69832. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  69833. __decorate([
  69834. BABYLON.serializeAsTexture("lensColorTexture")
  69835. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  69836. __decorate([
  69837. BABYLON.serialize()
  69838. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  69839. __decorate([
  69840. BABYLON.serialize()
  69841. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  69842. __decorate([
  69843. BABYLON.serialize()
  69844. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  69845. __decorate([
  69846. BABYLON.serialize()
  69847. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  69848. __decorate([
  69849. BABYLON.serializeAsTexture("lensStarTexture")
  69850. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  69851. __decorate([
  69852. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  69853. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  69854. __decorate([
  69855. BABYLON.serialize()
  69856. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  69857. __decorate([
  69858. BABYLON.serialize()
  69859. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  69860. __decorate([
  69861. BABYLON.serialize()
  69862. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  69863. __decorate([
  69864. BABYLON.serialize()
  69865. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  69866. __decorate([
  69867. BABYLON.serialize()
  69868. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  69869. __decorate([
  69870. BABYLON.serialize()
  69871. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  69872. __decorate([
  69873. BABYLON.serialize()
  69874. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  69875. __decorate([
  69876. BABYLON.serialize()
  69877. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  69878. __decorate([
  69879. BABYLON.serialize()
  69880. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  69881. __decorate([
  69882. BABYLON.serialize()
  69883. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  69884. __decorate([
  69885. BABYLON.serialize()
  69886. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  69887. __decorate([
  69888. BABYLON.serialize()
  69889. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  69890. return StandardRenderingPipeline;
  69891. }(BABYLON.PostProcessRenderPipeline));
  69892. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  69893. })(BABYLON || (BABYLON = {}));
  69894. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  69895. "use strict";
  69896. var BABYLON;
  69897. (function (BABYLON) {
  69898. var FxaaPostProcess = /** @class */ (function (_super) {
  69899. __extends(FxaaPostProcess, _super);
  69900. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69901. if (camera === void 0) { camera = null; }
  69902. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69903. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  69904. _this.onApplyObservable.add(function (effect) {
  69905. var texelSize = _this.texelSize;
  69906. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  69907. });
  69908. return _this;
  69909. }
  69910. return FxaaPostProcess;
  69911. }(BABYLON.PostProcess));
  69912. BABYLON.FxaaPostProcess = FxaaPostProcess;
  69913. })(BABYLON || (BABYLON = {}));
  69914. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  69915. "use strict";
  69916. var BABYLON;
  69917. (function (BABYLON) {
  69918. /**
  69919. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  69920. */
  69921. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  69922. __extends(ChromaticAberrationPostProcess, _super);
  69923. /**
  69924. * Creates a new instance of @see ChromaticAberrationPostProcess
  69925. * @param name The name of the effect.
  69926. * @param screenWidth The width of the screen to apply the effect on.
  69927. * @param screenHeight The height of the screen to apply the effect on.
  69928. * @param options The required width/height ratio to downsize to before computing the render pass.
  69929. * @param camera The camera to apply the render pass to.
  69930. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69931. * @param engine The engine which the post process will be applied. (default: current engine)
  69932. * @param reusable If the post process can be reused on the same frame. (default: false)
  69933. * @param textureType Type of textures used when performing the post process. (default: 0)
  69934. * @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)
  69935. */
  69936. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69937. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69938. if (blockCompilation === void 0) { blockCompilation = false; }
  69939. 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;
  69940. /**
  69941. * The amount of seperation of rgb channels (default: 30)
  69942. */
  69943. _this.aberrationAmount = 30;
  69944. /**
  69945. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  69946. */
  69947. _this.radialIntensity = 0;
  69948. /**
  69949. * 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))
  69950. */
  69951. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  69952. /**
  69953. * 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))
  69954. */
  69955. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  69956. _this.onApplyObservable.add(function (effect) {
  69957. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  69958. effect.setFloat('screen_width', screenWidth);
  69959. effect.setFloat('screen_height', screenHeight);
  69960. effect.setFloat('radialIntensity', _this.radialIntensity);
  69961. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  69962. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  69963. });
  69964. return _this;
  69965. }
  69966. return ChromaticAberrationPostProcess;
  69967. }(BABYLON.PostProcess));
  69968. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  69969. })(BABYLON || (BABYLON = {}));
  69970. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  69971. "use strict";
  69972. var BABYLON;
  69973. (function (BABYLON) {
  69974. /**
  69975. * The SharpenPostProcess applies a sharpen kernel to every pixel
  69976. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69977. */
  69978. var SharpenPostProcess = /** @class */ (function (_super) {
  69979. __extends(SharpenPostProcess, _super);
  69980. /**
  69981. * Creates a new instance of @see ConvolutionPostProcess
  69982. * @param name The name of the effect.
  69983. * @param options The required width/height ratio to downsize to before computing the render pass.
  69984. * @param camera The camera to apply the render pass to.
  69985. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69986. * @param engine The engine which the post process will be applied. (default: current engine)
  69987. * @param reusable If the post process can be reused on the same frame. (default: false)
  69988. * @param textureType Type of textures used when performing the post process. (default: 0)
  69989. * @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)
  69990. */
  69991. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69992. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69993. if (blockCompilation === void 0) { blockCompilation = false; }
  69994. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69995. /**
  69996. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  69997. */
  69998. _this.colorAmount = 1.0;
  69999. /**
  70000. * How much sharpness should be applied (default: 0.3)
  70001. */
  70002. _this.edgeAmount = 0.3;
  70003. _this.onApply = function (effect) {
  70004. effect.setFloat2("screenSize", _this.width, _this.height);
  70005. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  70006. };
  70007. return _this;
  70008. }
  70009. return SharpenPostProcess;
  70010. }(BABYLON.PostProcess));
  70011. BABYLON.SharpenPostProcess = SharpenPostProcess;
  70012. })(BABYLON || (BABYLON = {}));
  70013. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  70014. "use strict";
  70015. var BABYLON;
  70016. (function (BABYLON) {
  70017. /**
  70018. * The Blur Post Process which blurs an image based on a kernel and direction.
  70019. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  70020. */
  70021. var BlurPostProcess = /** @class */ (function (_super) {
  70022. __extends(BlurPostProcess, _super);
  70023. /**
  70024. * Creates a new instance of @see BlurPostProcess
  70025. * @param name The name of the effect.
  70026. * @param direction The direction in which to blur the image.
  70027. * @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.
  70028. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  70029. * @param camera The camera to apply the render pass to.
  70030. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70031. * @param engine The engine which the post process will be applied. (default: current engine)
  70032. * @param reusable If the post process can be reused on the same frame. (default: false)
  70033. * @param textureType Type of textures used when performing the post process. (default: 0)
  70034. * @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)
  70035. */
  70036. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  70037. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70038. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70039. if (defines === void 0) { defines = ""; }
  70040. if (blockCompilation === void 0) { blockCompilation = false; }
  70041. 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;
  70042. _this.direction = direction;
  70043. _this.blockCompilation = blockCompilation;
  70044. _this._packedFloat = false;
  70045. _this._staticDefines = "";
  70046. _this._staticDefines = defines;
  70047. _this.onApplyObservable.add(function (effect) {
  70048. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  70049. });
  70050. _this.kernel = kernel;
  70051. return _this;
  70052. }
  70053. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  70054. /**
  70055. * Gets the length in pixels of the blur sample region
  70056. */
  70057. get: function () {
  70058. return this._idealKernel;
  70059. },
  70060. /**
  70061. * Sets the length in pixels of the blur sample region
  70062. */
  70063. set: function (v) {
  70064. if (this._idealKernel === v) {
  70065. return;
  70066. }
  70067. v = Math.max(v, 1);
  70068. this._idealKernel = v;
  70069. this._kernel = this._nearestBestKernel(v);
  70070. if (!this.blockCompilation) {
  70071. this._updateParameters();
  70072. }
  70073. },
  70074. enumerable: true,
  70075. configurable: true
  70076. });
  70077. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  70078. /**
  70079. * Gets wether or not the blur is unpacking/repacking floats
  70080. */
  70081. get: function () {
  70082. return this._packedFloat;
  70083. },
  70084. /**
  70085. * Sets wether or not the blur needs to unpack/repack floats
  70086. */
  70087. set: function (v) {
  70088. if (this._packedFloat === v) {
  70089. return;
  70090. }
  70091. this._packedFloat = v;
  70092. if (!this.blockCompilation) {
  70093. this._updateParameters();
  70094. }
  70095. },
  70096. enumerable: true,
  70097. configurable: true
  70098. });
  70099. /**
  70100. * Updates the effect with the current post process compile time values and recompiles the shader.
  70101. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70102. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70103. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70104. * @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
  70105. * @param onCompiled Called when the shader has been compiled.
  70106. * @param onError Called if there is an error when compiling a shader.
  70107. */
  70108. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70109. if (defines === void 0) { defines = null; }
  70110. if (uniforms === void 0) { uniforms = null; }
  70111. if (samplers === void 0) { samplers = null; }
  70112. this._updateParameters(onCompiled, onError);
  70113. };
  70114. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  70115. // Generate sampling offsets and weights
  70116. var N = this._kernel;
  70117. var centerIndex = (N - 1) / 2;
  70118. // Generate Gaussian sampling weights over kernel
  70119. var offsets = [];
  70120. var weights = [];
  70121. var totalWeight = 0;
  70122. for (var i = 0; i < N; i++) {
  70123. var u = i / (N - 1);
  70124. var w = this._gaussianWeight(u * 2.0 - 1);
  70125. offsets[i] = (i - centerIndex);
  70126. weights[i] = w;
  70127. totalWeight += w;
  70128. }
  70129. // Normalize weights
  70130. for (var i = 0; i < weights.length; i++) {
  70131. weights[i] /= totalWeight;
  70132. }
  70133. // Optimize: combine samples to take advantage of hardware linear sampling
  70134. // Walk from left to center, combining pairs (symmetrically)
  70135. var linearSamplingWeights = [];
  70136. var linearSamplingOffsets = [];
  70137. var linearSamplingMap = [];
  70138. for (var i = 0; i <= centerIndex; i += 2) {
  70139. var j = Math.min(i + 1, Math.floor(centerIndex));
  70140. var singleCenterSample = i === j;
  70141. if (singleCenterSample) {
  70142. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70143. }
  70144. else {
  70145. var sharedCell = j === centerIndex;
  70146. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  70147. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  70148. if (offsetLinear === 0) {
  70149. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70150. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  70151. }
  70152. else {
  70153. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  70154. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  70155. }
  70156. }
  70157. }
  70158. for (var i = 0; i < linearSamplingMap.length; i++) {
  70159. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  70160. linearSamplingWeights[i] = linearSamplingMap[i].w;
  70161. }
  70162. // Replace with optimized
  70163. offsets = linearSamplingOffsets;
  70164. weights = linearSamplingWeights;
  70165. // Generate shaders
  70166. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  70167. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  70168. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  70169. var defines = "";
  70170. defines += this._staticDefines;
  70171. for (var i = 0; i < varyingCount; i++) {
  70172. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  70173. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  70174. }
  70175. var depCount = 0;
  70176. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  70177. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  70178. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  70179. depCount++;
  70180. }
  70181. if (this.packedFloat) {
  70182. defines += "#define PACKEDFLOAT 1";
  70183. }
  70184. _super.prototype.updateEffect.call(this, defines, null, null, {
  70185. varyingCount: varyingCount,
  70186. depCount: depCount
  70187. }, onCompiled, onError);
  70188. };
  70189. /**
  70190. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  70191. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  70192. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  70193. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  70194. * The gaps between physical kernels are compensated for in the weighting of the samples
  70195. * @param idealKernel Ideal blur kernel.
  70196. * @return Nearest best kernel.
  70197. */
  70198. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  70199. var v = Math.round(idealKernel);
  70200. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  70201. var k = _a[_i];
  70202. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  70203. return Math.max(k, 3);
  70204. }
  70205. }
  70206. return Math.max(v, 3);
  70207. };
  70208. /**
  70209. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  70210. * @param x The point on the Gaussian distribution to sample.
  70211. * @return the value of the Gaussian function at x.
  70212. */
  70213. BlurPostProcess.prototype._gaussianWeight = function (x) {
  70214. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  70215. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  70216. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  70217. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  70218. // truncated at around 1.3% of peak strength.
  70219. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  70220. var sigma = (1 / 3);
  70221. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  70222. var exponent = -((x * x) / (2.0 * sigma * sigma));
  70223. var weight = (1.0 / denominator) * Math.exp(exponent);
  70224. return weight;
  70225. };
  70226. /**
  70227. * Generates a string that can be used as a floating point number in GLSL.
  70228. * @param x Value to print.
  70229. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  70230. * @return GLSL float string.
  70231. */
  70232. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  70233. if (decimalFigures === void 0) { decimalFigures = 8; }
  70234. return x.toFixed(decimalFigures).replace(/0+$/, '');
  70235. };
  70236. return BlurPostProcess;
  70237. }(BABYLON.PostProcess));
  70238. BABYLON.BlurPostProcess = BlurPostProcess;
  70239. })(BABYLON || (BABYLON = {}));
  70240. //# sourceMappingURL=babylon.blurPostProcess.js.map
  70241. "use strict";
  70242. var BABYLON;
  70243. (function (BABYLON) {
  70244. /**
  70245. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  70246. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  70247. * based on samples that have a large difference in distance than the center pixel.
  70248. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70249. */
  70250. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  70251. __extends(DepthOfFieldBlurPostProcess, _super);
  70252. /**
  70253. * Creates a new instance of @see CircleOfConfusionPostProcess
  70254. * @param name The name of the effect.
  70255. * @param scene The scene the effect belongs to.
  70256. * @param direction The direction the blur should be applied.
  70257. * @param kernel The size of the kernel used to blur.
  70258. * @param options The required width/height ratio to downsize to before computing the render pass.
  70259. * @param camera The camera to apply the render pass to.
  70260. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  70261. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  70262. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70263. * @param engine The engine which the post process will be applied. (default: current engine)
  70264. * @param reusable If the post process can be reused on the same frame. (default: false)
  70265. * @param textureType Type of textures used when performing the post process. (default: 0)
  70266. * @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)
  70267. */
  70268. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  70269. if (imageToBlur === void 0) { imageToBlur = null; }
  70270. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70271. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70272. if (blockCompilation === void 0) { blockCompilation = false; }
  70273. 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;
  70274. _this.direction = direction;
  70275. _this.onApplyObservable.add(function (effect) {
  70276. if (imageToBlur != null) {
  70277. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  70278. }
  70279. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70280. if (scene.activeCamera) {
  70281. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  70282. }
  70283. });
  70284. return _this;
  70285. }
  70286. return DepthOfFieldBlurPostProcess;
  70287. }(BABYLON.BlurPostProcess));
  70288. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  70289. })(BABYLON || (BABYLON = {}));
  70290. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  70291. "use strict";
  70292. var BABYLON;
  70293. (function (BABYLON) {
  70294. /**
  70295. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  70296. */
  70297. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  70298. __extends(DepthOfFieldMergePostProcess, _super);
  70299. /**
  70300. * Creates a new instance of @see CircleOfConfusionPostProcess
  70301. * @param name The name of the effect.
  70302. * @param original The non-blurred image to be modified
  70303. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  70304. * @param blurSteps Incrimental bluring post processes.
  70305. * @param options The required width/height ratio to downsize to before computing the render pass.
  70306. * @param camera The camera to apply the render pass to.
  70307. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70308. * @param engine The engine which the post process will be applied. (default: current engine)
  70309. * @param reusable If the post process can be reused on the same frame. (default: false)
  70310. * @param textureType Type of textures used when performing the post process. (default: 0)
  70311. * @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)
  70312. */
  70313. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70314. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70315. if (blockCompilation === void 0) { blockCompilation = false; }
  70316. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  70317. _this.blurSteps = blurSteps;
  70318. _this.onApplyObservable.add(function (effect) {
  70319. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70320. effect.setTextureFromPostProcess("textureSampler", original);
  70321. blurSteps.forEach(function (step, index) {
  70322. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  70323. });
  70324. });
  70325. if (!blockCompilation) {
  70326. _this.updateEffect();
  70327. }
  70328. return _this;
  70329. }
  70330. /**
  70331. * Updates the effect with the current post process compile time values and recompiles the shader.
  70332. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70333. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70334. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70335. * @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
  70336. * @param onCompiled Called when the shader has been compiled.
  70337. * @param onError Called if there is an error when compiling a shader.
  70338. */
  70339. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70340. if (defines === void 0) { defines = null; }
  70341. if (uniforms === void 0) { uniforms = null; }
  70342. if (samplers === void 0) { samplers = null; }
  70343. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  70344. };
  70345. return DepthOfFieldMergePostProcess;
  70346. }(BABYLON.PostProcess));
  70347. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  70348. })(BABYLON || (BABYLON = {}));
  70349. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  70350. "use strict";
  70351. var BABYLON;
  70352. (function (BABYLON) {
  70353. /**
  70354. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  70355. */
  70356. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  70357. __extends(CircleOfConfusionPostProcess, _super);
  70358. /**
  70359. * Creates a new instance of @see CircleOfConfusionPostProcess
  70360. * @param name The name of the effect.
  70361. * @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.
  70362. * @param options The required width/height ratio to downsize to before computing the render pass.
  70363. * @param camera The camera to apply the render pass to.
  70364. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70365. * @param engine The engine which the post process will be applied. (default: current engine)
  70366. * @param reusable If the post process can be reused on the same frame. (default: false)
  70367. * @param textureType Type of textures used when performing the post process. (default: 0)
  70368. * @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)
  70369. */
  70370. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70371. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70372. if (blockCompilation === void 0) { blockCompilation = false; }
  70373. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70374. /**
  70375. * 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.
  70376. */
  70377. _this.lensSize = 50;
  70378. /**
  70379. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70380. */
  70381. _this.fStop = 1.4;
  70382. /**
  70383. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70384. */
  70385. _this.focusDistance = 2000;
  70386. /**
  70387. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  70388. */
  70389. _this.focalLength = 50;
  70390. _this._depthTexture = null;
  70391. _this._depthTexture = depthTexture;
  70392. _this.onApplyObservable.add(function (effect) {
  70393. if (!_this._depthTexture) {
  70394. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  70395. return;
  70396. }
  70397. effect.setTexture("depthSampler", _this._depthTexture);
  70398. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  70399. var aperture = _this.lensSize / _this.fStop;
  70400. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  70401. effect.setFloat('focusDistance', _this.focusDistance);
  70402. effect.setFloat('cocPrecalculation', cocPrecalculation);
  70403. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  70404. });
  70405. return _this;
  70406. }
  70407. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  70408. /**
  70409. * 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.
  70410. */
  70411. set: function (value) {
  70412. this._depthTexture = value;
  70413. },
  70414. enumerable: true,
  70415. configurable: true
  70416. });
  70417. return CircleOfConfusionPostProcess;
  70418. }(BABYLON.PostProcess));
  70419. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  70420. })(BABYLON || (BABYLON = {}));
  70421. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  70422. "use strict";
  70423. var BABYLON;
  70424. (function (BABYLON) {
  70425. /**
  70426. * Specifies the level of max blur that should be applied when using the depth of field effect
  70427. */
  70428. var DepthOfFieldEffectBlurLevel;
  70429. (function (DepthOfFieldEffectBlurLevel) {
  70430. /**
  70431. * Subtle blur
  70432. */
  70433. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  70434. /**
  70435. * Medium blur
  70436. */
  70437. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  70438. /**
  70439. * Large blur
  70440. */
  70441. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  70442. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  70443. ;
  70444. /**
  70445. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  70446. */
  70447. var DepthOfFieldEffect = /** @class */ (function (_super) {
  70448. __extends(DepthOfFieldEffect, _super);
  70449. /**
  70450. * Creates a new instance of @see DepthOfFieldEffect
  70451. * @param scene The scene the effect belongs to.
  70452. * @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.
  70453. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  70454. * @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)
  70455. */
  70456. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  70457. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  70458. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  70459. if (blockCompilation === void 0) { blockCompilation = false; }
  70460. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  70461. return _this._effects;
  70462. }, true) || this;
  70463. _this._effects = [];
  70464. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  70465. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70466. // 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)
  70467. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  70468. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70469. _this._depthOfFieldBlurY = [];
  70470. _this._depthOfFieldBlurX = [];
  70471. var blurCount = 1;
  70472. var kernelSize = 15;
  70473. switch (blurLevel) {
  70474. case DepthOfFieldEffectBlurLevel.High: {
  70475. blurCount = 3;
  70476. kernelSize = 51;
  70477. break;
  70478. }
  70479. case DepthOfFieldEffectBlurLevel.Medium: {
  70480. blurCount = 2;
  70481. kernelSize = 31;
  70482. break;
  70483. }
  70484. default: {
  70485. kernelSize = 15;
  70486. blurCount = 1;
  70487. break;
  70488. }
  70489. }
  70490. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  70491. for (var i = 0; i < blurCount; i++) {
  70492. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70493. blurY.autoClear = false;
  70494. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70495. blurX.autoClear = false;
  70496. _this._depthOfFieldBlurY.push(blurY);
  70497. _this._depthOfFieldBlurX.push(blurX);
  70498. }
  70499. // Merge blurred images with original image based on circleOfConfusion
  70500. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70501. _this._depthOfFieldMerge.autoClear = false;
  70502. // Set all post processes on the effect.
  70503. _this._effects = [_this._circleOfConfusion];
  70504. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  70505. _this._effects.push(_this._depthOfFieldBlurY[i]);
  70506. _this._effects.push(_this._depthOfFieldBlurX[i]);
  70507. }
  70508. _this._effects.push(_this._depthOfFieldMerge);
  70509. return _this;
  70510. }
  70511. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  70512. get: function () {
  70513. return this._circleOfConfusion.focalLength;
  70514. },
  70515. /**
  70516. * The focal the length of the camera used in the effect
  70517. */
  70518. set: function (value) {
  70519. this._circleOfConfusion.focalLength = value;
  70520. },
  70521. enumerable: true,
  70522. configurable: true
  70523. });
  70524. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  70525. get: function () {
  70526. return this._circleOfConfusion.fStop;
  70527. },
  70528. /**
  70529. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70530. */
  70531. set: function (value) {
  70532. this._circleOfConfusion.fStop = value;
  70533. },
  70534. enumerable: true,
  70535. configurable: true
  70536. });
  70537. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  70538. get: function () {
  70539. return this._circleOfConfusion.focusDistance;
  70540. },
  70541. /**
  70542. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70543. */
  70544. set: function (value) {
  70545. this._circleOfConfusion.focusDistance = value;
  70546. },
  70547. enumerable: true,
  70548. configurable: true
  70549. });
  70550. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  70551. get: function () {
  70552. return this._circleOfConfusion.lensSize;
  70553. },
  70554. /**
  70555. * 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.
  70556. */
  70557. set: function (value) {
  70558. this._circleOfConfusion.lensSize = value;
  70559. },
  70560. enumerable: true,
  70561. configurable: true
  70562. });
  70563. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  70564. /**
  70565. * 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.
  70566. */
  70567. set: function (value) {
  70568. this._circleOfConfusion.depthTexture = value;
  70569. },
  70570. enumerable: true,
  70571. configurable: true
  70572. });
  70573. /**
  70574. * Disposes each of the internal effects for a given camera.
  70575. * @param camera The camera to dispose the effect on.
  70576. */
  70577. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  70578. this._circleOfConfusion.dispose(camera);
  70579. this._depthOfFieldBlurX.forEach(function (element) {
  70580. element.dispose(camera);
  70581. });
  70582. this._depthOfFieldBlurY.forEach(function (element) {
  70583. element.dispose(camera);
  70584. });
  70585. this._depthOfFieldMerge.dispose(camera);
  70586. };
  70587. /**
  70588. * Internal
  70589. */
  70590. DepthOfFieldEffect.prototype._updateEffects = function () {
  70591. for (var effect in this._effects) {
  70592. this._effects[effect].updateEffect();
  70593. }
  70594. };
  70595. /**
  70596. * Internal
  70597. * @returns if all the contained post processes are ready.
  70598. */
  70599. DepthOfFieldEffect.prototype._isReady = function () {
  70600. for (var effect in this._effects) {
  70601. if (!this._effects[effect].isReady()) {
  70602. return false;
  70603. }
  70604. }
  70605. return true;
  70606. };
  70607. return DepthOfFieldEffect;
  70608. }(BABYLON.PostProcessRenderEffect));
  70609. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  70610. })(BABYLON || (BABYLON = {}));
  70611. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  70612. "use strict";
  70613. var BABYLON;
  70614. (function (BABYLON) {
  70615. /**
  70616. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  70617. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  70618. */
  70619. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  70620. __extends(DefaultRenderingPipeline, _super);
  70621. /**
  70622. * @constructor
  70623. * @param {string} name - The rendering pipeline name
  70624. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70625. * @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)
  70626. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70627. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  70628. */
  70629. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  70630. if (automaticBuild === void 0) { automaticBuild = true; }
  70631. var _this = _super.call(this, scene.getEngine(), name) || this;
  70632. _this._originalCameras = [];
  70633. /**
  70634. * ID of the sharpen post process,
  70635. */
  70636. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  70637. /**
  70638. * ID of the pass post process used for bloom,
  70639. */
  70640. _this.PassPostProcessId = "PassPostProcessEffect";
  70641. /**
  70642. * ID of the highlight post process used for bloom,
  70643. */
  70644. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  70645. /**
  70646. * ID of the blurX post process used for bloom,
  70647. */
  70648. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  70649. /**
  70650. * ID of the blurY post process used for bloom,
  70651. */
  70652. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  70653. /**
  70654. * ID of the copy back post process used for bloom,
  70655. */
  70656. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  70657. /**
  70658. * ID of the image processing post process;
  70659. */
  70660. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  70661. /**
  70662. * ID of the Fast Approximate Anti-Aliasing post process;
  70663. */
  70664. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  70665. /**
  70666. * ID of the final merge post process;
  70667. */
  70668. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  70669. /**
  70670. * ID of the chromatic aberration post process,
  70671. */
  70672. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  70673. /**
  70674. * Animations which can be used to tweak settings over a period of time
  70675. */
  70676. _this.animations = [];
  70677. // Values
  70678. _this._sharpenEnabled = false;
  70679. _this._bloomEnabled = false;
  70680. _this._depthOfFieldEnabled = false;
  70681. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  70682. _this._fxaaEnabled = false;
  70683. _this._msaaEnabled = false;
  70684. _this._imageProcessingEnabled = true;
  70685. _this._bloomScale = 0.6;
  70686. _this._chromaticAberrationEnabled = false;
  70687. _this._buildAllowed = true;
  70688. /**
  70689. * Specifies the size of the bloom blur kernel, relative to the final output size
  70690. */
  70691. _this.bloomKernel = 64;
  70692. /**
  70693. * Specifies the weight of the bloom in the final rendering
  70694. */
  70695. _this._bloomWeight = 0.15;
  70696. _this._prevPostProcess = null;
  70697. _this._prevPrevPostProcess = null;
  70698. _this._cameras = cameras || [];
  70699. _this._originalCameras = _this._cameras.slice();
  70700. _this._buildAllowed = automaticBuild;
  70701. // Initialize
  70702. _this._scene = scene;
  70703. var caps = _this._scene.getEngine().getCaps();
  70704. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  70705. // Misc
  70706. if (_this._hdr) {
  70707. if (caps.textureHalfFloatRender) {
  70708. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70709. }
  70710. else if (caps.textureFloatRender) {
  70711. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70712. }
  70713. }
  70714. else {
  70715. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70716. }
  70717. // Attach
  70718. scene.postProcessRenderPipelineManager.addPipeline(_this);
  70719. var engine = _this._scene.getEngine();
  70720. // Create post processes before hand so they can be modified before enabled.
  70721. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  70722. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70723. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  70724. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  70725. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70726. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  70727. _this._buildPipeline();
  70728. return _this;
  70729. }
  70730. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  70731. get: function () {
  70732. return this._sharpenEnabled;
  70733. },
  70734. /**
  70735. * Enable or disable the sharpen process from the pipeline
  70736. */
  70737. set: function (enabled) {
  70738. if (this._sharpenEnabled === enabled) {
  70739. return;
  70740. }
  70741. this._sharpenEnabled = enabled;
  70742. this._buildPipeline();
  70743. },
  70744. enumerable: true,
  70745. configurable: true
  70746. });
  70747. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  70748. get: function () {
  70749. return this._bloomWeight;
  70750. },
  70751. /**
  70752. * The strength of the bloom.
  70753. */
  70754. set: function (value) {
  70755. if (this._bloomWeight === value) {
  70756. return;
  70757. }
  70758. this._bloomWeight = value;
  70759. if (this._hdr && this.copyBack) {
  70760. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  70761. }
  70762. },
  70763. enumerable: true,
  70764. configurable: true
  70765. });
  70766. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  70767. get: function () {
  70768. return this._bloomScale;
  70769. },
  70770. /**
  70771. * The scale of the bloom, lower value will provide better performance.
  70772. */
  70773. set: function (value) {
  70774. if (this._bloomScale === value) {
  70775. return;
  70776. }
  70777. this._bloomScale = value;
  70778. this._buildPipeline();
  70779. },
  70780. enumerable: true,
  70781. configurable: true
  70782. });
  70783. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  70784. get: function () {
  70785. return this._bloomEnabled;
  70786. },
  70787. /**
  70788. * Enable or disable the bloom from the pipeline
  70789. */
  70790. set: function (enabled) {
  70791. if (this._bloomEnabled === enabled) {
  70792. return;
  70793. }
  70794. this._bloomEnabled = enabled;
  70795. this._buildPipeline();
  70796. },
  70797. enumerable: true,
  70798. configurable: true
  70799. });
  70800. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  70801. /**
  70802. * If the depth of field is enabled.
  70803. */
  70804. get: function () {
  70805. return this._depthOfFieldEnabled;
  70806. },
  70807. set: function (enabled) {
  70808. if (this._depthOfFieldEnabled === enabled) {
  70809. return;
  70810. }
  70811. this._depthOfFieldEnabled = enabled;
  70812. this._buildPipeline();
  70813. },
  70814. enumerable: true,
  70815. configurable: true
  70816. });
  70817. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  70818. /**
  70819. * Blur level of the depth of field effect. (Higher blur will effect performance)
  70820. */
  70821. get: function () {
  70822. return this._depthOfFieldBlurLevel;
  70823. },
  70824. set: function (value) {
  70825. if (this._depthOfFieldBlurLevel === value) {
  70826. return;
  70827. }
  70828. this._depthOfFieldBlurLevel = value;
  70829. // recreate dof and dispose old as this setting is not dynamic
  70830. var oldDof = this.depthOfField;
  70831. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  70832. this.depthOfField.focalLength = oldDof.focalLength;
  70833. this.depthOfField.focusDistance = oldDof.focusDistance;
  70834. this.depthOfField.fStop = oldDof.fStop;
  70835. this.depthOfField.lensSize = oldDof.lensSize;
  70836. for (var i = 0; i < this._cameras.length; i++) {
  70837. oldDof.disposeEffects(this._cameras[i]);
  70838. }
  70839. this._buildPipeline();
  70840. },
  70841. enumerable: true,
  70842. configurable: true
  70843. });
  70844. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  70845. get: function () {
  70846. return this._fxaaEnabled;
  70847. },
  70848. /**
  70849. * If the anti aliasing is enabled.
  70850. */
  70851. set: function (enabled) {
  70852. if (this._fxaaEnabled === enabled) {
  70853. return;
  70854. }
  70855. this._fxaaEnabled = enabled;
  70856. this._buildPipeline();
  70857. },
  70858. enumerable: true,
  70859. configurable: true
  70860. });
  70861. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  70862. get: function () {
  70863. return this._msaaEnabled;
  70864. },
  70865. /**
  70866. * If the multisample anti-aliasing is enabled.
  70867. */
  70868. set: function (enabled) {
  70869. if (this._msaaEnabled === enabled) {
  70870. return;
  70871. }
  70872. this._msaaEnabled = enabled;
  70873. this._buildPipeline();
  70874. },
  70875. enumerable: true,
  70876. configurable: true
  70877. });
  70878. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  70879. get: function () {
  70880. return this._imageProcessingEnabled;
  70881. },
  70882. /**
  70883. * If image processing is enabled.
  70884. */
  70885. set: function (enabled) {
  70886. if (this._imageProcessingEnabled === enabled) {
  70887. return;
  70888. }
  70889. this._imageProcessingEnabled = enabled;
  70890. this._buildPipeline();
  70891. },
  70892. enumerable: true,
  70893. configurable: true
  70894. });
  70895. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  70896. get: function () {
  70897. return this._chromaticAberrationEnabled;
  70898. },
  70899. /**
  70900. * Enable or disable the chromaticAberration process from the pipeline
  70901. */
  70902. set: function (enabled) {
  70903. if (this._chromaticAberrationEnabled === enabled) {
  70904. return;
  70905. }
  70906. this._chromaticAberrationEnabled = enabled;
  70907. this._buildPipeline();
  70908. },
  70909. enumerable: true,
  70910. configurable: true
  70911. });
  70912. /**
  70913. * Force the compilation of the entire pipeline.
  70914. */
  70915. DefaultRenderingPipeline.prototype.prepare = function () {
  70916. var previousState = this._buildAllowed;
  70917. this._buildAllowed = true;
  70918. this._buildPipeline();
  70919. this._buildAllowed = previousState;
  70920. };
  70921. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  70922. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  70923. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  70924. postProcess.autoClear = false;
  70925. }
  70926. else {
  70927. postProcess.autoClear = true;
  70928. }
  70929. if (!skipTextureSharing) {
  70930. if (this._prevPrevPostProcess) {
  70931. postProcess.shareOutputWith(this._prevPrevPostProcess);
  70932. }
  70933. else {
  70934. postProcess.useOwnOutput();
  70935. }
  70936. if (this._prevPostProcess) {
  70937. this._prevPrevPostProcess = this._prevPostProcess;
  70938. }
  70939. this._prevPostProcess = postProcess;
  70940. }
  70941. };
  70942. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  70943. var _this = this;
  70944. if (!this._buildAllowed) {
  70945. return;
  70946. }
  70947. var engine = this._scene.getEngine();
  70948. this._disposePostProcesses();
  70949. if (this._cameras !== null) {
  70950. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70951. // get back cameras to be used to reattach pipeline
  70952. this._cameras = this._originalCameras.slice();
  70953. }
  70954. this._reset();
  70955. this._prevPostProcess = null;
  70956. this._prevPrevPostProcess = null;
  70957. if (this.sharpenEnabled) {
  70958. if (!this.sharpen.isReady()) {
  70959. this.sharpen.updateEffect();
  70960. }
  70961. this.addEffect(this._sharpenEffect);
  70962. this._setAutoClearAndTextureSharing(this.sharpen);
  70963. }
  70964. if (this.depthOfFieldEnabled) {
  70965. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  70966. this.depthOfField.depthTexture = depthTexture;
  70967. if (!this.depthOfField._isReady()) {
  70968. this.depthOfField._updateEffects();
  70969. }
  70970. this.addEffect(this.depthOfField);
  70971. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  70972. }
  70973. if (this.bloomEnabled) {
  70974. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70975. this._setAutoClearAndTextureSharing(this.pass, true);
  70976. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  70977. if (!this._hdr) {
  70978. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70979. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  70980. this.highlights.autoClear = false;
  70981. this.highlights.alwaysForcePOT = true;
  70982. }
  70983. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70984. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  70985. this.blurX.alwaysForcePOT = true;
  70986. this.blurX.autoClear = false;
  70987. this.blurX.onActivateObservable.add(function () {
  70988. var dw = _this.blurX.width / engine.getRenderWidth(true);
  70989. _this.blurX.kernel = _this.bloomKernel * dw;
  70990. });
  70991. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70992. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  70993. this.blurY.alwaysForcePOT = true;
  70994. this.blurY.autoClear = false;
  70995. this.blurY.onActivateObservable.add(function () {
  70996. var dh = _this.blurY.height / engine.getRenderHeight(true);
  70997. _this.blurY.kernel = _this.bloomKernel * dh;
  70998. });
  70999. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  71000. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  71001. this.copyBack.alwaysForcePOT = true;
  71002. if (this._hdr) {
  71003. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  71004. var w = this.bloomWeight;
  71005. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  71006. }
  71007. else {
  71008. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  71009. }
  71010. this.copyBack.autoClear = false;
  71011. }
  71012. if (this._imageProcessingEnabled) {
  71013. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  71014. if (this._hdr) {
  71015. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  71016. }
  71017. else {
  71018. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  71019. }
  71020. }
  71021. if (this._hdr && this.imageProcessing) {
  71022. this.finalMerge = this.imageProcessing;
  71023. }
  71024. else {
  71025. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  71026. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  71027. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  71028. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  71029. }
  71030. if (this.bloomEnabled) {
  71031. if (this._hdr) {
  71032. this.copyBack.shareOutputWith(this.blurX);
  71033. if (this.imageProcessing) {
  71034. this.imageProcessing.shareOutputWith(this.pass);
  71035. this.imageProcessing.autoClear = false;
  71036. }
  71037. else {
  71038. this.finalMerge.shareOutputWith(this.pass);
  71039. }
  71040. }
  71041. else {
  71042. this.finalMerge.shareOutputWith(this.pass);
  71043. }
  71044. }
  71045. if (this.fxaaEnabled) {
  71046. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  71047. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  71048. this._setAutoClearAndTextureSharing(this.fxaa);
  71049. }
  71050. if (this.chromaticAberrationEnabled) {
  71051. if (!this.chromaticAberration.isReady()) {
  71052. this.chromaticAberration.updateEffect();
  71053. }
  71054. this.addEffect(this._chromaticAberrationEffect);
  71055. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  71056. }
  71057. if (this._cameras !== null) {
  71058. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  71059. }
  71060. if (this.msaaEnabled) {
  71061. if (!this._enableMSAAOnFirstPostProcess()) {
  71062. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  71063. }
  71064. }
  71065. };
  71066. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  71067. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  71068. for (var i = 0; i < this._cameras.length; i++) {
  71069. var camera = this._cameras[i];
  71070. if (this.pass) {
  71071. this.pass.dispose(camera);
  71072. }
  71073. if (this.highlights) {
  71074. this.highlights.dispose(camera);
  71075. }
  71076. if (this.blurX) {
  71077. this.blurX.dispose(camera);
  71078. }
  71079. if (this.blurY) {
  71080. this.blurY.dispose(camera);
  71081. }
  71082. if (this.copyBack) {
  71083. this.copyBack.dispose(camera);
  71084. }
  71085. if (this.imageProcessing) {
  71086. this.imageProcessing.dispose(camera);
  71087. }
  71088. if (this.fxaa) {
  71089. this.fxaa.dispose(camera);
  71090. }
  71091. if (this.finalMerge) {
  71092. this.finalMerge.dispose(camera);
  71093. }
  71094. // These are created in the constructor and should not be disposed on every pipeline change
  71095. if (disposeNonRecreated) {
  71096. if (this.sharpen) {
  71097. this.sharpen.dispose(camera);
  71098. }
  71099. if (this.depthOfField) {
  71100. this.depthOfField.disposeEffects(camera);
  71101. }
  71102. if (this.chromaticAberration) {
  71103. this.chromaticAberration.dispose(camera);
  71104. }
  71105. }
  71106. }
  71107. this.pass = null;
  71108. this.highlights = null;
  71109. this.blurX = null;
  71110. this.blurY = null;
  71111. this.copyBack = null;
  71112. this.imageProcessing = null;
  71113. this.fxaa = null;
  71114. this.finalMerge = null;
  71115. if (disposeNonRecreated) {
  71116. this.sharpen = null;
  71117. this.depthOfField = null;
  71118. this.chromaticAberration = null;
  71119. }
  71120. };
  71121. /**
  71122. * Dispose of the pipeline and stop all post processes
  71123. */
  71124. DefaultRenderingPipeline.prototype.dispose = function () {
  71125. this._disposePostProcesses(true);
  71126. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  71127. _super.prototype.dispose.call(this);
  71128. };
  71129. /**
  71130. * Serialize the rendering pipeline (Used when exporting)
  71131. * @returns the serialized object
  71132. */
  71133. DefaultRenderingPipeline.prototype.serialize = function () {
  71134. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  71135. serializationObject.customType = "DefaultRenderingPipeline";
  71136. return serializationObject;
  71137. };
  71138. /**
  71139. * Parse the serialized pipeline
  71140. * @param source Source pipeline.
  71141. * @param scene The scene to load the pipeline to.
  71142. * @param rootUrl The URL of the serialized pipeline.
  71143. * @returns An instantiated pipeline from the serialized object.
  71144. */
  71145. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  71146. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  71147. };
  71148. __decorate([
  71149. BABYLON.serialize()
  71150. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  71151. __decorate([
  71152. BABYLON.serialize()
  71153. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  71154. __decorate([
  71155. BABYLON.serialize()
  71156. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  71157. __decorate([
  71158. BABYLON.serialize()
  71159. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  71160. __decorate([
  71161. BABYLON.serialize()
  71162. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  71163. __decorate([
  71164. BABYLON.serialize()
  71165. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  71166. __decorate([
  71167. BABYLON.serialize()
  71168. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  71169. __decorate([
  71170. BABYLON.serialize()
  71171. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  71172. __decorate([
  71173. BABYLON.serialize()
  71174. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  71175. __decorate([
  71176. BABYLON.serialize()
  71177. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  71178. __decorate([
  71179. BABYLON.serialize()
  71180. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  71181. __decorate([
  71182. BABYLON.serialize()
  71183. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  71184. __decorate([
  71185. BABYLON.serialize()
  71186. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  71187. return DefaultRenderingPipeline;
  71188. }(BABYLON.PostProcessRenderPipeline));
  71189. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  71190. })(BABYLON || (BABYLON = {}));
  71191. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  71192. "use strict";
  71193. var BABYLON;
  71194. (function (BABYLON) {
  71195. /**
  71196. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  71197. */
  71198. var GeometryBufferRenderer = /** @class */ (function () {
  71199. /**
  71200. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  71201. * @param scene The scene the buffer belongs to
  71202. * @param ratio How big is the buffer related to the main canvas.
  71203. */
  71204. function GeometryBufferRenderer(scene, ratio) {
  71205. if (ratio === void 0) { ratio = 1; }
  71206. this._enablePosition = false;
  71207. this._scene = scene;
  71208. this._ratio = ratio;
  71209. // Render target
  71210. this._createRenderTargets();
  71211. }
  71212. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  71213. /**
  71214. * Set the render list (meshes to be rendered) used in the G buffer.
  71215. */
  71216. set: function (meshes) {
  71217. this._multiRenderTarget.renderList = meshes;
  71218. },
  71219. enumerable: true,
  71220. configurable: true
  71221. });
  71222. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  71223. /**
  71224. * Gets wether or not G buffer are supported by the running hardware.
  71225. * This requires draw buffer supports
  71226. */
  71227. get: function () {
  71228. return this._multiRenderTarget.isSupported;
  71229. },
  71230. enumerable: true,
  71231. configurable: true
  71232. });
  71233. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  71234. /**
  71235. * Gets wether or not position are enabled for the G buffer.
  71236. */
  71237. get: function () {
  71238. return this._enablePosition;
  71239. },
  71240. /**
  71241. * Sets wether or not position are enabled for the G buffer.
  71242. */
  71243. set: function (enable) {
  71244. this._enablePosition = enable;
  71245. this.dispose();
  71246. this._createRenderTargets();
  71247. },
  71248. enumerable: true,
  71249. configurable: true
  71250. });
  71251. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  71252. /**
  71253. * Gets the scene associated with the buffer.
  71254. */
  71255. get: function () {
  71256. return this._scene;
  71257. },
  71258. enumerable: true,
  71259. configurable: true
  71260. });
  71261. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  71262. /**
  71263. * Gets the ratio used by the buffer during its creation.
  71264. * How big is the buffer related to the main canvas.
  71265. */
  71266. get: function () {
  71267. return this._ratio;
  71268. },
  71269. enumerable: true,
  71270. configurable: true
  71271. });
  71272. /**
  71273. * Checks wether everything is ready to render a submesh to the G buffer.
  71274. * @param subMesh the submesh to check readiness for
  71275. * @param useInstances is the mesh drawn using instance or not
  71276. * @returns true if ready otherwise false
  71277. */
  71278. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  71279. var material = subMesh.getMaterial();
  71280. if (material && material.disableDepthWrite) {
  71281. return false;
  71282. }
  71283. var defines = [];
  71284. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71285. var mesh = subMesh.getMesh();
  71286. // Alpha test
  71287. if (material && material.needAlphaTesting()) {
  71288. defines.push("#define ALPHATEST");
  71289. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71290. attribs.push(BABYLON.VertexBuffer.UVKind);
  71291. defines.push("#define UV1");
  71292. }
  71293. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71294. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71295. defines.push("#define UV2");
  71296. }
  71297. }
  71298. // Buffers
  71299. if (this._enablePosition) {
  71300. defines.push("#define POSITION");
  71301. }
  71302. // Bones
  71303. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71304. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71305. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71306. if (mesh.numBoneInfluencers > 4) {
  71307. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71308. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71309. }
  71310. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71311. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71312. }
  71313. else {
  71314. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71315. }
  71316. // Instances
  71317. if (useInstances) {
  71318. defines.push("#define INSTANCES");
  71319. attribs.push("world0");
  71320. attribs.push("world1");
  71321. attribs.push("world2");
  71322. attribs.push("world3");
  71323. }
  71324. // Get correct effect
  71325. var join = defines.join("\n");
  71326. if (this._cachedDefines !== join) {
  71327. this._cachedDefines = join;
  71328. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  71329. }
  71330. return this._effect.isReady();
  71331. };
  71332. /**
  71333. * Gets the current underlying G Buffer.
  71334. * @returns the buffer
  71335. */
  71336. GeometryBufferRenderer.prototype.getGBuffer = function () {
  71337. return this._multiRenderTarget;
  71338. };
  71339. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  71340. /**
  71341. * Gets the number of samples used to render the buffer (anti aliasing).
  71342. */
  71343. get: function () {
  71344. return this._multiRenderTarget.samples;
  71345. },
  71346. /**
  71347. * Sets the number of samples used to render the buffer (anti aliasing).
  71348. */
  71349. set: function (value) {
  71350. this._multiRenderTarget.samples = value;
  71351. },
  71352. enumerable: true,
  71353. configurable: true
  71354. });
  71355. /**
  71356. * Disposes the renderer and frees up associated resources.
  71357. */
  71358. GeometryBufferRenderer.prototype.dispose = function () {
  71359. this.getGBuffer().dispose();
  71360. };
  71361. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  71362. var _this = this;
  71363. var engine = this._scene.getEngine();
  71364. var count = this._enablePosition ? 3 : 2;
  71365. 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 });
  71366. if (!this.isSupported) {
  71367. return;
  71368. }
  71369. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71370. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71371. this._multiRenderTarget.refreshRate = 1;
  71372. this._multiRenderTarget.renderParticles = false;
  71373. this._multiRenderTarget.renderList = null;
  71374. // set default depth value to 1.0 (far away)
  71375. this._multiRenderTarget.onClearObservable.add(function (engine) {
  71376. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  71377. });
  71378. // Custom render function
  71379. var renderSubMesh = function (subMesh) {
  71380. var mesh = subMesh.getRenderingMesh();
  71381. var scene = _this._scene;
  71382. var engine = scene.getEngine();
  71383. var material = subMesh.getMaterial();
  71384. if (!material) {
  71385. return;
  71386. }
  71387. // Culling
  71388. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  71389. // Managing instances
  71390. var batch = mesh._getInstancesRenderList(subMesh._id);
  71391. if (batch.mustReturn) {
  71392. return;
  71393. }
  71394. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71395. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  71396. engine.enableEffect(_this._effect);
  71397. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  71398. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71399. _this._effect.setMatrix("view", scene.getViewMatrix());
  71400. // Alpha test
  71401. if (material && material.needAlphaTesting()) {
  71402. var alphaTexture = material.getAlphaTestTexture();
  71403. if (alphaTexture) {
  71404. _this._effect.setTexture("diffuseSampler", alphaTexture);
  71405. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71406. }
  71407. }
  71408. // Bones
  71409. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71410. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71411. }
  71412. // Draw
  71413. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71414. }
  71415. };
  71416. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71417. var index;
  71418. if (depthOnlySubMeshes.length) {
  71419. engine.setColorWrite(false);
  71420. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71421. renderSubMesh(depthOnlySubMeshes.data[index]);
  71422. }
  71423. engine.setColorWrite(true);
  71424. }
  71425. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71426. renderSubMesh(opaqueSubMeshes.data[index]);
  71427. }
  71428. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71429. renderSubMesh(alphaTestSubMeshes.data[index]);
  71430. }
  71431. };
  71432. };
  71433. return GeometryBufferRenderer;
  71434. }());
  71435. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  71436. })(BABYLON || (BABYLON = {}));
  71437. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  71438. "use strict";
  71439. var BABYLON;
  71440. (function (BABYLON) {
  71441. var RefractionPostProcess = /** @class */ (function (_super) {
  71442. __extends(RefractionPostProcess, _super);
  71443. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  71444. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  71445. _this.color = color;
  71446. _this.depth = depth;
  71447. _this.colorLevel = colorLevel;
  71448. _this._ownRefractionTexture = true;
  71449. _this.onActivateObservable.add(function (cam) {
  71450. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  71451. });
  71452. _this.onApplyObservable.add(function (effect) {
  71453. effect.setColor3("baseColor", _this.color);
  71454. effect.setFloat("depth", _this.depth);
  71455. effect.setFloat("colorLevel", _this.colorLevel);
  71456. effect.setTexture("refractionSampler", _this._refTexture);
  71457. });
  71458. return _this;
  71459. }
  71460. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  71461. /**
  71462. * Gets or sets the refraction texture
  71463. * Please note that you are responsible for disposing the texture if you set it manually
  71464. */
  71465. get: function () {
  71466. return this._refTexture;
  71467. },
  71468. set: function (value) {
  71469. if (this._refTexture && this._ownRefractionTexture) {
  71470. this._refTexture.dispose();
  71471. }
  71472. this._refTexture = value;
  71473. this._ownRefractionTexture = false;
  71474. },
  71475. enumerable: true,
  71476. configurable: true
  71477. });
  71478. // Methods
  71479. RefractionPostProcess.prototype.dispose = function (camera) {
  71480. if (this._refTexture && this._ownRefractionTexture) {
  71481. this._refTexture.dispose();
  71482. this._refTexture = null;
  71483. }
  71484. _super.prototype.dispose.call(this, camera);
  71485. };
  71486. return RefractionPostProcess;
  71487. }(BABYLON.PostProcess));
  71488. BABYLON.RefractionPostProcess = RefractionPostProcess;
  71489. })(BABYLON || (BABYLON = {}));
  71490. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  71491. "use strict";
  71492. var BABYLON;
  71493. (function (BABYLON) {
  71494. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  71495. __extends(BlackAndWhitePostProcess, _super);
  71496. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  71497. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  71498. _this.degree = 1;
  71499. _this.onApplyObservable.add(function (effect) {
  71500. effect.setFloat("degree", _this.degree);
  71501. });
  71502. return _this;
  71503. }
  71504. return BlackAndWhitePostProcess;
  71505. }(BABYLON.PostProcess));
  71506. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  71507. })(BABYLON || (BABYLON = {}));
  71508. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  71509. "use strict";
  71510. var BABYLON;
  71511. (function (BABYLON) {
  71512. /**
  71513. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  71514. * input texture to perform effects such as edge detection or sharpening
  71515. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  71516. */
  71517. var ConvolutionPostProcess = /** @class */ (function (_super) {
  71518. __extends(ConvolutionPostProcess, _super);
  71519. /**
  71520. * Creates a new instance of @see ConvolutionPostProcess
  71521. * @param name The name of the effect.
  71522. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  71523. * @param options The required width/height ratio to downsize to before computing the render pass.
  71524. * @param camera The camera to apply the render pass to.
  71525. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71526. * @param engine The engine which the post process will be applied. (default: current engine)
  71527. * @param reusable If the post process can be reused on the same frame. (default: false)
  71528. * @param textureType Type of textures used when performing the post process. (default: 0)
  71529. */
  71530. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  71531. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71532. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71533. _this.kernel = kernel;
  71534. _this.onApply = function (effect) {
  71535. effect.setFloat2("screenSize", _this.width, _this.height);
  71536. effect.setArray("kernel", _this.kernel);
  71537. };
  71538. return _this;
  71539. }
  71540. // Statics
  71541. /**
  71542. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71543. */
  71544. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  71545. /**
  71546. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71547. */
  71548. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  71549. /**
  71550. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71551. */
  71552. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  71553. /**
  71554. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71555. */
  71556. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  71557. /**
  71558. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71559. */
  71560. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  71561. /**
  71562. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71563. */
  71564. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  71565. return ConvolutionPostProcess;
  71566. }(BABYLON.PostProcess));
  71567. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  71568. })(BABYLON || (BABYLON = {}));
  71569. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  71570. "use strict";
  71571. var BABYLON;
  71572. (function (BABYLON) {
  71573. var FilterPostProcess = /** @class */ (function (_super) {
  71574. __extends(FilterPostProcess, _super);
  71575. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  71576. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  71577. _this.kernelMatrix = kernelMatrix;
  71578. _this.onApply = function (effect) {
  71579. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  71580. };
  71581. return _this;
  71582. }
  71583. return FilterPostProcess;
  71584. }(BABYLON.PostProcess));
  71585. BABYLON.FilterPostProcess = FilterPostProcess;
  71586. })(BABYLON || (BABYLON = {}));
  71587. //# sourceMappingURL=babylon.filterPostProcess.js.map
  71588. "use strict";
  71589. var BABYLON;
  71590. (function (BABYLON) {
  71591. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  71592. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  71593. __extends(VolumetricLightScatteringPostProcess, _super);
  71594. /**
  71595. * @constructor
  71596. * @param {string} name - The post-process name
  71597. * @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)
  71598. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  71599. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  71600. * @param {number} samples - The post-process quality, default 100
  71601. * @param {number} samplingMode - The post-process filtering mode
  71602. * @param {BABYLON.Engine} engine - The babylon engine
  71603. * @param {boolean} reusable - If the post-process is reusable
  71604. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  71605. */
  71606. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  71607. if (samples === void 0) { samples = 100; }
  71608. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71609. 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;
  71610. _this._screenCoordinates = BABYLON.Vector2.Zero();
  71611. /**
  71612. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  71613. * @type {Vector3}
  71614. */
  71615. _this.customMeshPosition = BABYLON.Vector3.Zero();
  71616. /**
  71617. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  71618. * @type {boolean}
  71619. */
  71620. _this.useCustomMeshPosition = false;
  71621. /**
  71622. * If the post-process should inverse the light scattering direction
  71623. * @type {boolean}
  71624. */
  71625. _this.invert = true;
  71626. /**
  71627. * Array containing the excluded meshes not rendered in the internal pass
  71628. */
  71629. _this.excludedMeshes = new Array();
  71630. /**
  71631. * Controls the overall intensity of the post-process
  71632. * @type {number}
  71633. */
  71634. _this.exposure = 0.3;
  71635. /**
  71636. * Dissipates each sample's contribution in range [0, 1]
  71637. * @type {number}
  71638. */
  71639. _this.decay = 0.96815;
  71640. /**
  71641. * Controls the overall intensity of each sample
  71642. * @type {number}
  71643. */
  71644. _this.weight = 0.58767;
  71645. /**
  71646. * Controls the density of each sample
  71647. * @type {number}
  71648. */
  71649. _this.density = 0.926;
  71650. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  71651. engine = scene.getEngine();
  71652. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  71653. // Configure mesh
  71654. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  71655. // Configure
  71656. _this._createPass(scene, ratio.passRatio || ratio);
  71657. _this.onActivate = function (camera) {
  71658. if (!_this.isSupported) {
  71659. _this.dispose(camera);
  71660. }
  71661. _this.onActivate = null;
  71662. };
  71663. _this.onApplyObservable.add(function (effect) {
  71664. _this._updateMeshScreenCoordinates(scene);
  71665. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  71666. effect.setFloat("exposure", _this.exposure);
  71667. effect.setFloat("decay", _this.decay);
  71668. effect.setFloat("weight", _this.weight);
  71669. effect.setFloat("density", _this.density);
  71670. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  71671. });
  71672. return _this;
  71673. }
  71674. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  71675. get: function () {
  71676. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71677. return false;
  71678. },
  71679. set: function (useDiffuseColor) {
  71680. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71681. },
  71682. enumerable: true,
  71683. configurable: true
  71684. });
  71685. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  71686. return "VolumetricLightScatteringPostProcess";
  71687. };
  71688. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  71689. var mesh = subMesh.getMesh();
  71690. // Render this.mesh as default
  71691. if (mesh === this.mesh && mesh.material) {
  71692. return mesh.material.isReady(mesh);
  71693. }
  71694. var defines = [];
  71695. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71696. var material = subMesh.getMaterial();
  71697. // Alpha test
  71698. if (material) {
  71699. if (material.needAlphaTesting()) {
  71700. defines.push("#define ALPHATEST");
  71701. }
  71702. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71703. attribs.push(BABYLON.VertexBuffer.UVKind);
  71704. defines.push("#define UV1");
  71705. }
  71706. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71707. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71708. defines.push("#define UV2");
  71709. }
  71710. }
  71711. // Bones
  71712. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71713. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71714. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71715. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71716. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  71717. }
  71718. else {
  71719. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71720. }
  71721. // Instances
  71722. if (useInstances) {
  71723. defines.push("#define INSTANCES");
  71724. attribs.push("world0");
  71725. attribs.push("world1");
  71726. attribs.push("world2");
  71727. attribs.push("world3");
  71728. }
  71729. // Get correct effect
  71730. var join = defines.join("\n");
  71731. if (this._cachedDefines !== join) {
  71732. this._cachedDefines = join;
  71733. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  71734. }
  71735. return this._volumetricLightScatteringPass.isReady();
  71736. };
  71737. /**
  71738. * Sets the new light position for light scattering effect
  71739. * @param {BABYLON.Vector3} The new custom light position
  71740. */
  71741. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  71742. this.customMeshPosition = position;
  71743. };
  71744. /**
  71745. * Returns the light position for light scattering effect
  71746. * @return {BABYLON.Vector3} The custom light position
  71747. */
  71748. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  71749. return this.customMeshPosition;
  71750. };
  71751. /**
  71752. * Disposes the internal assets and detaches the post-process from the camera
  71753. */
  71754. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  71755. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  71756. if (rttIndex !== -1) {
  71757. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  71758. }
  71759. this._volumetricLightScatteringRTT.dispose();
  71760. _super.prototype.dispose.call(this, camera);
  71761. };
  71762. /**
  71763. * Returns the render target texture used by the post-process
  71764. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  71765. */
  71766. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  71767. return this._volumetricLightScatteringRTT;
  71768. };
  71769. // Private methods
  71770. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  71771. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  71772. return true;
  71773. }
  71774. return false;
  71775. };
  71776. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  71777. var _this = this;
  71778. var engine = scene.getEngine();
  71779. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71780. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71781. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71782. this._volumetricLightScatteringRTT.renderList = null;
  71783. this._volumetricLightScatteringRTT.renderParticles = false;
  71784. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  71785. var camera = this.getCamera();
  71786. if (camera) {
  71787. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71788. }
  71789. else {
  71790. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71791. }
  71792. // Custom render function for submeshes
  71793. var renderSubMesh = function (subMesh) {
  71794. var mesh = subMesh.getRenderingMesh();
  71795. if (_this._meshExcluded(mesh)) {
  71796. return;
  71797. }
  71798. var material = subMesh.getMaterial();
  71799. if (!material) {
  71800. return;
  71801. }
  71802. var scene = mesh.getScene();
  71803. var engine = scene.getEngine();
  71804. // Culling
  71805. engine.setState(material.backFaceCulling);
  71806. // Managing instances
  71807. var batch = mesh._getInstancesRenderList(subMesh._id);
  71808. if (batch.mustReturn) {
  71809. return;
  71810. }
  71811. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71812. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  71813. var effect = _this._volumetricLightScatteringPass;
  71814. if (mesh === _this.mesh) {
  71815. if (subMesh.effect) {
  71816. effect = subMesh.effect;
  71817. }
  71818. else {
  71819. effect = material.getEffect();
  71820. }
  71821. }
  71822. engine.enableEffect(effect);
  71823. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  71824. if (mesh === _this.mesh) {
  71825. material.bind(mesh.getWorldMatrix(), mesh);
  71826. }
  71827. else {
  71828. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  71829. // Alpha test
  71830. if (material && material.needAlphaTesting()) {
  71831. var alphaTexture = material.getAlphaTestTexture();
  71832. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  71833. if (alphaTexture) {
  71834. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71835. }
  71836. }
  71837. // Bones
  71838. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71839. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71840. }
  71841. }
  71842. // Draw
  71843. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  71844. }
  71845. };
  71846. // Render target texture callbacks
  71847. var savedSceneClearColor;
  71848. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  71849. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  71850. savedSceneClearColor = scene.clearColor;
  71851. scene.clearColor = sceneClearColor;
  71852. });
  71853. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  71854. scene.clearColor = savedSceneClearColor;
  71855. });
  71856. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71857. var engine = scene.getEngine();
  71858. var index;
  71859. if (depthOnlySubMeshes.length) {
  71860. engine.setColorWrite(false);
  71861. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71862. renderSubMesh(depthOnlySubMeshes.data[index]);
  71863. }
  71864. engine.setColorWrite(true);
  71865. }
  71866. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71867. renderSubMesh(opaqueSubMeshes.data[index]);
  71868. }
  71869. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71870. renderSubMesh(alphaTestSubMeshes.data[index]);
  71871. }
  71872. if (transparentSubMeshes.length) {
  71873. // Sort sub meshes
  71874. for (index = 0; index < transparentSubMeshes.length; index++) {
  71875. var submesh = transparentSubMeshes.data[index];
  71876. var boundingInfo = submesh.getBoundingInfo();
  71877. if (boundingInfo && scene.activeCamera) {
  71878. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  71879. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  71880. }
  71881. }
  71882. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  71883. sortedArray.sort(function (a, b) {
  71884. // Alpha index first
  71885. if (a._alphaIndex > b._alphaIndex) {
  71886. return 1;
  71887. }
  71888. if (a._alphaIndex < b._alphaIndex) {
  71889. return -1;
  71890. }
  71891. // Then distance to camera
  71892. if (a._distanceToCamera < b._distanceToCamera) {
  71893. return 1;
  71894. }
  71895. if (a._distanceToCamera > b._distanceToCamera) {
  71896. return -1;
  71897. }
  71898. return 0;
  71899. });
  71900. // Render sub meshes
  71901. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  71902. for (index = 0; index < sortedArray.length; index++) {
  71903. renderSubMesh(sortedArray[index]);
  71904. }
  71905. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71906. }
  71907. };
  71908. };
  71909. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  71910. var transform = scene.getTransformMatrix();
  71911. var meshPosition;
  71912. if (this.useCustomMeshPosition) {
  71913. meshPosition = this.customMeshPosition;
  71914. }
  71915. else if (this.attachedNode) {
  71916. meshPosition = this.attachedNode.position;
  71917. }
  71918. else {
  71919. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  71920. }
  71921. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  71922. this._screenCoordinates.x = pos.x / this._viewPort.width;
  71923. this._screenCoordinates.y = pos.y / this._viewPort.height;
  71924. if (this.invert)
  71925. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  71926. };
  71927. // Static methods
  71928. /**
  71929. * Creates a default mesh for the Volumeric Light Scattering post-process
  71930. * @param {string} The mesh name
  71931. * @param {BABYLON.Scene} The scene where to create the mesh
  71932. * @return {BABYLON.Mesh} the default mesh
  71933. */
  71934. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  71935. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  71936. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  71937. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  71938. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  71939. mesh.material = material;
  71940. return mesh;
  71941. };
  71942. __decorate([
  71943. BABYLON.serializeAsVector3()
  71944. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  71945. __decorate([
  71946. BABYLON.serialize()
  71947. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  71948. __decorate([
  71949. BABYLON.serialize()
  71950. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  71951. __decorate([
  71952. BABYLON.serializeAsMeshReference()
  71953. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  71954. __decorate([
  71955. BABYLON.serialize()
  71956. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  71957. __decorate([
  71958. BABYLON.serialize()
  71959. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  71960. __decorate([
  71961. BABYLON.serialize()
  71962. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  71963. __decorate([
  71964. BABYLON.serialize()
  71965. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  71966. __decorate([
  71967. BABYLON.serialize()
  71968. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  71969. return VolumetricLightScatteringPostProcess;
  71970. }(BABYLON.PostProcess));
  71971. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  71972. })(BABYLON || (BABYLON = {}));
  71973. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  71974. "use strict";
  71975. //
  71976. // This post-process allows the modification of rendered colors by using
  71977. // a 'look-up table' (LUT). This effect is also called Color Grading.
  71978. //
  71979. // The object needs to be provided an url to a texture containing the color
  71980. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  71981. // Use an image editing software to tweak the LUT to match your needs.
  71982. //
  71983. // For an example of a color LUT, see here:
  71984. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  71985. // For explanations on color grading, see here:
  71986. // http://udn.epicgames.com/Three/ColorGrading.html
  71987. //
  71988. var BABYLON;
  71989. (function (BABYLON) {
  71990. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  71991. __extends(ColorCorrectionPostProcess, _super);
  71992. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  71993. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  71994. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71995. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  71996. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71997. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71998. _this.onApply = function (effect) {
  71999. effect.setTexture("colorTable", _this._colorTableTexture);
  72000. };
  72001. return _this;
  72002. }
  72003. return ColorCorrectionPostProcess;
  72004. }(BABYLON.PostProcess));
  72005. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  72006. })(BABYLON || (BABYLON = {}));
  72007. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  72008. "use strict";
  72009. var BABYLON;
  72010. (function (BABYLON) {
  72011. var TonemappingOperator;
  72012. (function (TonemappingOperator) {
  72013. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  72014. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  72015. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  72016. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  72017. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  72018. ;
  72019. var TonemapPostProcess = /** @class */ (function (_super) {
  72020. __extends(TonemapPostProcess, _super);
  72021. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  72022. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72023. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72024. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  72025. _this._operator = _operator;
  72026. _this.exposureAdjustment = exposureAdjustment;
  72027. var defines = "#define ";
  72028. if (_this._operator === TonemappingOperator.Hable)
  72029. defines += "HABLE_TONEMAPPING";
  72030. else if (_this._operator === TonemappingOperator.Reinhard)
  72031. defines += "REINHARD_TONEMAPPING";
  72032. else if (_this._operator === TonemappingOperator.HejiDawson)
  72033. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  72034. else if (_this._operator === TonemappingOperator.Photographic)
  72035. defines += "PHOTOGRAPHIC_TONEMAPPING";
  72036. //sadly a second call to create the effect.
  72037. _this.updateEffect(defines);
  72038. _this.onApply = function (effect) {
  72039. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  72040. };
  72041. return _this;
  72042. }
  72043. return TonemapPostProcess;
  72044. }(BABYLON.PostProcess));
  72045. BABYLON.TonemapPostProcess = TonemapPostProcess;
  72046. })(BABYLON || (BABYLON = {}));
  72047. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  72048. "use strict";
  72049. var BABYLON;
  72050. (function (BABYLON) {
  72051. var DisplayPassPostProcess = /** @class */ (function (_super) {
  72052. __extends(DisplayPassPostProcess, _super);
  72053. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  72054. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  72055. }
  72056. return DisplayPassPostProcess;
  72057. }(BABYLON.PostProcess));
  72058. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  72059. })(BABYLON || (BABYLON = {}));
  72060. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  72061. "use strict";
  72062. var BABYLON;
  72063. (function (BABYLON) {
  72064. var HighlightsPostProcess = /** @class */ (function (_super) {
  72065. __extends(HighlightsPostProcess, _super);
  72066. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  72067. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72068. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  72069. }
  72070. return HighlightsPostProcess;
  72071. }(BABYLON.PostProcess));
  72072. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  72073. })(BABYLON || (BABYLON = {}));
  72074. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  72075. "use strict";
  72076. var BABYLON;
  72077. (function (BABYLON) {
  72078. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  72079. __extends(ImageProcessingPostProcess, _super);
  72080. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  72081. if (camera === void 0) { camera = null; }
  72082. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72083. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  72084. _this._fromLinearSpace = true;
  72085. /**
  72086. * Defines cache preventing GC.
  72087. */
  72088. _this._defines = {
  72089. IMAGEPROCESSING: false,
  72090. VIGNETTE: false,
  72091. VIGNETTEBLENDMODEMULTIPLY: false,
  72092. VIGNETTEBLENDMODEOPAQUE: false,
  72093. TONEMAPPING: false,
  72094. CONTRAST: false,
  72095. COLORCURVES: false,
  72096. COLORGRADING: false,
  72097. COLORGRADING3D: false,
  72098. FROMLINEARSPACE: false,
  72099. SAMPLER3DGREENDEPTH: false,
  72100. SAMPLER3DBGRMAP: false,
  72101. IMAGEPROCESSINGPOSTPROCESS: false,
  72102. EXPOSURE: false,
  72103. GRAIN: false,
  72104. };
  72105. // Setup the configuration as forced by the constructor. This would then not force the
  72106. // scene materials output in linear space and let untouched the default forward pass.
  72107. if (imageProcessingConfiguration) {
  72108. imageProcessingConfiguration.applyByPostProcess = true;
  72109. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  72110. // This will cause the shader to be compiled
  72111. _this.fromLinearSpace = false;
  72112. }
  72113. else {
  72114. _this._attachImageProcessingConfiguration(null, true);
  72115. _this.imageProcessingConfiguration.applyByPostProcess = true;
  72116. }
  72117. _this.onApply = function (effect) {
  72118. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  72119. };
  72120. return _this;
  72121. }
  72122. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  72123. /**
  72124. * Gets the image processing configuration used either in this material.
  72125. */
  72126. get: function () {
  72127. return this._imageProcessingConfiguration;
  72128. },
  72129. /**
  72130. * Sets the Default image processing configuration used either in the this material.
  72131. *
  72132. * If sets to null, the scene one is in use.
  72133. */
  72134. set: function (value) {
  72135. this._attachImageProcessingConfiguration(value);
  72136. },
  72137. enumerable: true,
  72138. configurable: true
  72139. });
  72140. /**
  72141. * Attaches a new image processing configuration to the PBR Material.
  72142. * @param configuration
  72143. */
  72144. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  72145. var _this = this;
  72146. if (doNotBuild === void 0) { doNotBuild = false; }
  72147. if (configuration === this._imageProcessingConfiguration) {
  72148. return;
  72149. }
  72150. // Detaches observer.
  72151. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72152. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72153. }
  72154. // Pick the scene configuration if needed.
  72155. if (!configuration) {
  72156. var scene = null;
  72157. var engine = this.getEngine();
  72158. var camera = this.getCamera();
  72159. if (camera) {
  72160. scene = camera.getScene();
  72161. }
  72162. else if (engine && engine.scenes) {
  72163. var scenes = engine.scenes;
  72164. scene = scenes[scenes.length - 1];
  72165. }
  72166. else {
  72167. scene = BABYLON.Engine.LastCreatedScene;
  72168. }
  72169. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  72170. }
  72171. else {
  72172. this._imageProcessingConfiguration = configuration;
  72173. }
  72174. // Attaches observer.
  72175. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  72176. _this._updateParameters();
  72177. });
  72178. // Ensure the effect will be rebuilt.
  72179. if (!doNotBuild) {
  72180. this._updateParameters();
  72181. }
  72182. };
  72183. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  72184. /**
  72185. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  72186. */
  72187. get: function () {
  72188. return this.imageProcessingConfiguration.colorCurves;
  72189. },
  72190. /**
  72191. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  72192. */
  72193. set: function (value) {
  72194. this.imageProcessingConfiguration.colorCurves = value;
  72195. },
  72196. enumerable: true,
  72197. configurable: true
  72198. });
  72199. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  72200. /**
  72201. * Gets wether the color curves effect is enabled.
  72202. */
  72203. get: function () {
  72204. return this.imageProcessingConfiguration.colorCurvesEnabled;
  72205. },
  72206. /**
  72207. * Sets wether the color curves effect is enabled.
  72208. */
  72209. set: function (value) {
  72210. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  72211. },
  72212. enumerable: true,
  72213. configurable: true
  72214. });
  72215. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  72216. /**
  72217. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  72218. */
  72219. get: function () {
  72220. return this.imageProcessingConfiguration.colorGradingTexture;
  72221. },
  72222. /**
  72223. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  72224. */
  72225. set: function (value) {
  72226. this.imageProcessingConfiguration.colorGradingTexture = value;
  72227. },
  72228. enumerable: true,
  72229. configurable: true
  72230. });
  72231. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  72232. /**
  72233. * Gets wether the color grading effect is enabled.
  72234. */
  72235. get: function () {
  72236. return this.imageProcessingConfiguration.colorGradingEnabled;
  72237. },
  72238. /**
  72239. * Gets wether the color grading effect is enabled.
  72240. */
  72241. set: function (value) {
  72242. this.imageProcessingConfiguration.colorGradingEnabled = value;
  72243. },
  72244. enumerable: true,
  72245. configurable: true
  72246. });
  72247. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  72248. /**
  72249. * Gets exposure used in the effect.
  72250. */
  72251. get: function () {
  72252. return this.imageProcessingConfiguration.exposure;
  72253. },
  72254. /**
  72255. * Sets exposure used in the effect.
  72256. */
  72257. set: function (value) {
  72258. this.imageProcessingConfiguration.exposure = value;
  72259. },
  72260. enumerable: true,
  72261. configurable: true
  72262. });
  72263. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  72264. /**
  72265. * Gets wether tonemapping is enabled or not.
  72266. */
  72267. get: function () {
  72268. return this._imageProcessingConfiguration.toneMappingEnabled;
  72269. },
  72270. /**
  72271. * Sets wether tonemapping is enabled or not
  72272. */
  72273. set: function (value) {
  72274. this._imageProcessingConfiguration.toneMappingEnabled = value;
  72275. },
  72276. enumerable: true,
  72277. configurable: true
  72278. });
  72279. ;
  72280. ;
  72281. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  72282. /**
  72283. * Gets contrast used in the effect.
  72284. */
  72285. get: function () {
  72286. return this.imageProcessingConfiguration.contrast;
  72287. },
  72288. /**
  72289. * Sets contrast used in the effect.
  72290. */
  72291. set: function (value) {
  72292. this.imageProcessingConfiguration.contrast = value;
  72293. },
  72294. enumerable: true,
  72295. configurable: true
  72296. });
  72297. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  72298. /**
  72299. * Gets Vignette stretch size.
  72300. */
  72301. get: function () {
  72302. return this.imageProcessingConfiguration.vignetteStretch;
  72303. },
  72304. /**
  72305. * Sets Vignette stretch size.
  72306. */
  72307. set: function (value) {
  72308. this.imageProcessingConfiguration.vignetteStretch = value;
  72309. },
  72310. enumerable: true,
  72311. configurable: true
  72312. });
  72313. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  72314. /**
  72315. * Gets Vignette centre X Offset.
  72316. */
  72317. get: function () {
  72318. return this.imageProcessingConfiguration.vignetteCentreX;
  72319. },
  72320. /**
  72321. * Sets Vignette centre X Offset.
  72322. */
  72323. set: function (value) {
  72324. this.imageProcessingConfiguration.vignetteCentreX = value;
  72325. },
  72326. enumerable: true,
  72327. configurable: true
  72328. });
  72329. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  72330. /**
  72331. * Gets Vignette centre Y Offset.
  72332. */
  72333. get: function () {
  72334. return this.imageProcessingConfiguration.vignetteCentreY;
  72335. },
  72336. /**
  72337. * Sets Vignette centre Y Offset.
  72338. */
  72339. set: function (value) {
  72340. this.imageProcessingConfiguration.vignetteCentreY = value;
  72341. },
  72342. enumerable: true,
  72343. configurable: true
  72344. });
  72345. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  72346. /**
  72347. * Gets Vignette weight or intensity of the vignette effect.
  72348. */
  72349. get: function () {
  72350. return this.imageProcessingConfiguration.vignetteWeight;
  72351. },
  72352. /**
  72353. * Sets Vignette weight or intensity of the vignette effect.
  72354. */
  72355. set: function (value) {
  72356. this.imageProcessingConfiguration.vignetteWeight = value;
  72357. },
  72358. enumerable: true,
  72359. configurable: true
  72360. });
  72361. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  72362. /**
  72363. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72364. * if vignetteEnabled is set to true.
  72365. */
  72366. get: function () {
  72367. return this.imageProcessingConfiguration.vignetteColor;
  72368. },
  72369. /**
  72370. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72371. * if vignetteEnabled is set to true.
  72372. */
  72373. set: function (value) {
  72374. this.imageProcessingConfiguration.vignetteColor = value;
  72375. },
  72376. enumerable: true,
  72377. configurable: true
  72378. });
  72379. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  72380. /**
  72381. * Gets Camera field of view used by the Vignette effect.
  72382. */
  72383. get: function () {
  72384. return this.imageProcessingConfiguration.vignetteCameraFov;
  72385. },
  72386. /**
  72387. * Sets Camera field of view used by the Vignette effect.
  72388. */
  72389. set: function (value) {
  72390. this.imageProcessingConfiguration.vignetteCameraFov = value;
  72391. },
  72392. enumerable: true,
  72393. configurable: true
  72394. });
  72395. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  72396. /**
  72397. * Gets the vignette blend mode allowing different kind of effect.
  72398. */
  72399. get: function () {
  72400. return this.imageProcessingConfiguration.vignetteBlendMode;
  72401. },
  72402. /**
  72403. * Sets the vignette blend mode allowing different kind of effect.
  72404. */
  72405. set: function (value) {
  72406. this.imageProcessingConfiguration.vignetteBlendMode = value;
  72407. },
  72408. enumerable: true,
  72409. configurable: true
  72410. });
  72411. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  72412. /**
  72413. * Gets wether the vignette effect is enabled.
  72414. */
  72415. get: function () {
  72416. return this.imageProcessingConfiguration.vignetteEnabled;
  72417. },
  72418. /**
  72419. * Sets wether the vignette effect is enabled.
  72420. */
  72421. set: function (value) {
  72422. this.imageProcessingConfiguration.vignetteEnabled = value;
  72423. },
  72424. enumerable: true,
  72425. configurable: true
  72426. });
  72427. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  72428. /**
  72429. * Gets wether the grain effect is enabled.
  72430. */
  72431. get: function () {
  72432. return this.imageProcessingConfiguration.grainEnabled;
  72433. },
  72434. /**
  72435. * Sets wether the grain effect is enabled.
  72436. */
  72437. set: function (value) {
  72438. this.imageProcessingConfiguration.grainEnabled = value;
  72439. },
  72440. enumerable: true,
  72441. configurable: true
  72442. });
  72443. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  72444. /**
  72445. * Gets the grain effect's intensity.
  72446. */
  72447. get: function () {
  72448. return this.imageProcessingConfiguration.grainIntensity;
  72449. },
  72450. /**
  72451. * Sets the grain effect's intensity.
  72452. */
  72453. set: function (value) {
  72454. this.imageProcessingConfiguration.grainIntensity = value;
  72455. },
  72456. enumerable: true,
  72457. configurable: true
  72458. });
  72459. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  72460. /**
  72461. * Gets wether the grain effect is animated.
  72462. */
  72463. get: function () {
  72464. return this.imageProcessingConfiguration.grainAnimated;
  72465. },
  72466. /**
  72467. * Sets wether the grain effect is animated.
  72468. */
  72469. set: function (value) {
  72470. this.imageProcessingConfiguration.grainAnimated = value;
  72471. },
  72472. enumerable: true,
  72473. configurable: true
  72474. });
  72475. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  72476. /**
  72477. * Gets wether the input of the processing is in Gamma or Linear Space.
  72478. */
  72479. get: function () {
  72480. return this._fromLinearSpace;
  72481. },
  72482. /**
  72483. * Sets wether the input of the processing is in Gamma or Linear Space.
  72484. */
  72485. set: function (value) {
  72486. if (this._fromLinearSpace === value) {
  72487. return;
  72488. }
  72489. this._fromLinearSpace = value;
  72490. this._updateParameters();
  72491. },
  72492. enumerable: true,
  72493. configurable: true
  72494. });
  72495. ImageProcessingPostProcess.prototype.getClassName = function () {
  72496. return "ImageProcessingPostProcess";
  72497. };
  72498. ImageProcessingPostProcess.prototype._updateParameters = function () {
  72499. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  72500. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  72501. var defines = "";
  72502. for (var define in this._defines) {
  72503. if (this._defines[define]) {
  72504. defines += "#define " + define + ";\r\n";
  72505. }
  72506. }
  72507. var samplers = ["textureSampler"];
  72508. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  72509. var uniforms = ["scale"];
  72510. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  72511. this.updateEffect(defines, uniforms, samplers);
  72512. };
  72513. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  72514. _super.prototype.dispose.call(this, camera);
  72515. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72516. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72517. }
  72518. this.imageProcessingConfiguration.applyByPostProcess = false;
  72519. };
  72520. __decorate([
  72521. BABYLON.serialize()
  72522. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  72523. return ImageProcessingPostProcess;
  72524. }(BABYLON.PostProcess));
  72525. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  72526. })(BABYLON || (BABYLON = {}));
  72527. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  72528. "use strict";
  72529. var BABYLON;
  72530. (function (BABYLON) {
  72531. var Bone = /** @class */ (function (_super) {
  72532. __extends(Bone, _super);
  72533. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  72534. if (parentBone === void 0) { parentBone = null; }
  72535. if (localMatrix === void 0) { localMatrix = null; }
  72536. if (restPose === void 0) { restPose = null; }
  72537. if (baseMatrix === void 0) { baseMatrix = null; }
  72538. if (index === void 0) { index = null; }
  72539. var _this = _super.call(this, name, skeleton.getScene()) || this;
  72540. _this.name = name;
  72541. _this.children = new Array();
  72542. _this.animations = new Array();
  72543. // Set this value to map this bone to a different index in the transform matrices.
  72544. // Set this value to -1 to exclude the bone from the transform matrices.
  72545. _this._index = null;
  72546. _this._worldTransform = new BABYLON.Matrix();
  72547. _this._absoluteTransform = new BABYLON.Matrix();
  72548. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  72549. _this._scaleMatrix = BABYLON.Matrix.Identity();
  72550. _this._scaleVector = BABYLON.Vector3.One();
  72551. _this._negateScaleChildren = BABYLON.Vector3.One();
  72552. _this._scalingDeterminant = 1;
  72553. _this._skeleton = skeleton;
  72554. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  72555. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  72556. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  72557. _this._index = index;
  72558. skeleton.bones.push(_this);
  72559. _this.setParent(parentBone, false);
  72560. _this._updateDifferenceMatrix();
  72561. return _this;
  72562. }
  72563. Object.defineProperty(Bone.prototype, "_matrix", {
  72564. get: function () {
  72565. return this._localMatrix;
  72566. },
  72567. set: function (val) {
  72568. if (this._localMatrix) {
  72569. this._localMatrix.copyFrom(val);
  72570. }
  72571. else {
  72572. this._localMatrix = val;
  72573. }
  72574. },
  72575. enumerable: true,
  72576. configurable: true
  72577. });
  72578. // Members
  72579. Bone.prototype.getSkeleton = function () {
  72580. return this._skeleton;
  72581. };
  72582. Bone.prototype.getParent = function () {
  72583. return this._parent;
  72584. };
  72585. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  72586. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72587. if (this._parent === parent) {
  72588. return;
  72589. }
  72590. if (this._parent) {
  72591. var index = this._parent.children.indexOf(this);
  72592. if (index !== -1) {
  72593. this._parent.children.splice(index, 1);
  72594. }
  72595. }
  72596. this._parent = parent;
  72597. if (this._parent) {
  72598. this._parent.children.push(this);
  72599. }
  72600. if (updateDifferenceMatrix) {
  72601. this._updateDifferenceMatrix();
  72602. }
  72603. };
  72604. Bone.prototype.getLocalMatrix = function () {
  72605. return this._localMatrix;
  72606. };
  72607. Bone.prototype.getBaseMatrix = function () {
  72608. return this._baseMatrix;
  72609. };
  72610. Bone.prototype.getRestPose = function () {
  72611. return this._restPose;
  72612. };
  72613. Bone.prototype.returnToRest = function () {
  72614. this.updateMatrix(this._restPose.clone());
  72615. };
  72616. Bone.prototype.getWorldMatrix = function () {
  72617. return this._worldTransform;
  72618. };
  72619. Bone.prototype.getInvertedAbsoluteTransform = function () {
  72620. return this._invertedAbsoluteTransform;
  72621. };
  72622. Bone.prototype.getAbsoluteTransform = function () {
  72623. return this._absoluteTransform;
  72624. };
  72625. Object.defineProperty(Bone.prototype, "position", {
  72626. // Properties (matches AbstractMesh properties)
  72627. get: function () {
  72628. return this.getPosition();
  72629. },
  72630. set: function (newPosition) {
  72631. this.setPosition(newPosition);
  72632. },
  72633. enumerable: true,
  72634. configurable: true
  72635. });
  72636. Object.defineProperty(Bone.prototype, "rotation", {
  72637. get: function () {
  72638. return this.getRotation();
  72639. },
  72640. set: function (newRotation) {
  72641. this.setRotation(newRotation);
  72642. },
  72643. enumerable: true,
  72644. configurable: true
  72645. });
  72646. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  72647. get: function () {
  72648. return this.getRotationQuaternion();
  72649. },
  72650. set: function (newRotation) {
  72651. this.setRotationQuaternion(newRotation);
  72652. },
  72653. enumerable: true,
  72654. configurable: true
  72655. });
  72656. Object.defineProperty(Bone.prototype, "scaling", {
  72657. get: function () {
  72658. return this.getScale();
  72659. },
  72660. set: function (newScaling) {
  72661. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  72662. },
  72663. enumerable: true,
  72664. configurable: true
  72665. });
  72666. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  72667. /**
  72668. * Gets the animation properties override
  72669. */
  72670. get: function () {
  72671. return this._skeleton.animationPropertiesOverride;
  72672. },
  72673. enumerable: true,
  72674. configurable: true
  72675. });
  72676. // Methods
  72677. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  72678. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72679. this._baseMatrix = matrix.clone();
  72680. this._localMatrix = matrix.clone();
  72681. this._skeleton._markAsDirty();
  72682. if (updateDifferenceMatrix) {
  72683. this._updateDifferenceMatrix();
  72684. }
  72685. };
  72686. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  72687. if (!rootMatrix) {
  72688. rootMatrix = this._baseMatrix;
  72689. }
  72690. if (this._parent) {
  72691. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72692. }
  72693. else {
  72694. this._absoluteTransform.copyFrom(rootMatrix);
  72695. }
  72696. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  72697. for (var index = 0; index < this.children.length; index++) {
  72698. this.children[index]._updateDifferenceMatrix();
  72699. }
  72700. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  72701. };
  72702. Bone.prototype.markAsDirty = function () {
  72703. this._currentRenderId++;
  72704. this._childRenderId++;
  72705. this._skeleton._markAsDirty();
  72706. };
  72707. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  72708. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72709. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  72710. // all animation may be coming from a library skeleton, so may need to create animation
  72711. if (this.animations.length === 0) {
  72712. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  72713. this.animations[0].setKeys([]);
  72714. }
  72715. // get animation info / verify there is such a range from the source bone
  72716. var sourceRange = source.animations[0].getRange(rangeName);
  72717. if (!sourceRange) {
  72718. return false;
  72719. }
  72720. var from = sourceRange.from;
  72721. var to = sourceRange.to;
  72722. var sourceKeys = source.animations[0].getKeys();
  72723. // rescaling prep
  72724. var sourceBoneLength = source.length;
  72725. var sourceParent = source.getParent();
  72726. var parent = this.getParent();
  72727. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  72728. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  72729. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  72730. var destKeys = this.animations[0].getKeys();
  72731. // loop vars declaration
  72732. var orig;
  72733. var origTranslation;
  72734. var mat;
  72735. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  72736. orig = sourceKeys[key];
  72737. if (orig.frame >= from && orig.frame <= to) {
  72738. if (rescaleAsRequired) {
  72739. mat = orig.value.clone();
  72740. // scale based on parent ratio, when bone has parent
  72741. if (parentScalingReqd) {
  72742. origTranslation = mat.getTranslation();
  72743. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  72744. // scale based on skeleton dimension ratio when root bone, and value is passed
  72745. }
  72746. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  72747. origTranslation = mat.getTranslation();
  72748. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  72749. // use original when root bone, and no data for skelDimensionsRatio
  72750. }
  72751. else {
  72752. mat = orig.value;
  72753. }
  72754. }
  72755. else {
  72756. mat = orig.value;
  72757. }
  72758. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  72759. }
  72760. }
  72761. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  72762. return true;
  72763. };
  72764. /**
  72765. * Translate the bone in local or world space.
  72766. * @param vec The amount to translate the bone.
  72767. * @param space The space that the translation is in.
  72768. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72769. */
  72770. Bone.prototype.translate = function (vec, space, mesh) {
  72771. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72772. var lm = this.getLocalMatrix();
  72773. if (space == BABYLON.Space.LOCAL) {
  72774. lm.m[12] += vec.x;
  72775. lm.m[13] += vec.y;
  72776. lm.m[14] += vec.z;
  72777. }
  72778. else {
  72779. var wm = null;
  72780. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72781. if (mesh) {
  72782. wm = mesh.getWorldMatrix();
  72783. }
  72784. this._skeleton.computeAbsoluteTransforms();
  72785. var tmat = Bone._tmpMats[0];
  72786. var tvec = Bone._tmpVecs[0];
  72787. if (this._parent) {
  72788. if (mesh && wm) {
  72789. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72790. tmat.multiplyToRef(wm, tmat);
  72791. }
  72792. else {
  72793. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72794. }
  72795. }
  72796. tmat.m[12] = 0;
  72797. tmat.m[13] = 0;
  72798. tmat.m[14] = 0;
  72799. tmat.invert();
  72800. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  72801. lm.m[12] += tvec.x;
  72802. lm.m[13] += tvec.y;
  72803. lm.m[14] += tvec.z;
  72804. }
  72805. this.markAsDirty();
  72806. };
  72807. /**
  72808. * Set the postion of the bone in local or world space.
  72809. * @param position The position to set the bone.
  72810. * @param space The space that the position is in.
  72811. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72812. */
  72813. Bone.prototype.setPosition = function (position, space, mesh) {
  72814. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72815. var lm = this.getLocalMatrix();
  72816. if (space == BABYLON.Space.LOCAL) {
  72817. lm.m[12] = position.x;
  72818. lm.m[13] = position.y;
  72819. lm.m[14] = position.z;
  72820. }
  72821. else {
  72822. var wm = null;
  72823. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72824. if (mesh) {
  72825. wm = mesh.getWorldMatrix();
  72826. }
  72827. this._skeleton.computeAbsoluteTransforms();
  72828. var tmat = Bone._tmpMats[0];
  72829. var vec = Bone._tmpVecs[0];
  72830. if (this._parent) {
  72831. if (mesh && wm) {
  72832. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72833. tmat.multiplyToRef(wm, tmat);
  72834. }
  72835. else {
  72836. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72837. }
  72838. }
  72839. tmat.invert();
  72840. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  72841. lm.m[12] = vec.x;
  72842. lm.m[13] = vec.y;
  72843. lm.m[14] = vec.z;
  72844. }
  72845. this.markAsDirty();
  72846. };
  72847. /**
  72848. * Set the absolute postion of the bone (world space).
  72849. * @param position The position to set the bone.
  72850. * @param mesh The mesh that this bone is attached to.
  72851. */
  72852. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  72853. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  72854. };
  72855. /**
  72856. * Set the scale of the bone on the x, y and z axes.
  72857. * @param x The scale of the bone on the x axis.
  72858. * @param x The scale of the bone on the y axis.
  72859. * @param z The scale of the bone on the z axis.
  72860. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72861. */
  72862. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  72863. if (scaleChildren === void 0) { scaleChildren = false; }
  72864. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  72865. if (!scaleChildren) {
  72866. this._negateScaleChildren.x = 1 / x;
  72867. this._negateScaleChildren.y = 1 / y;
  72868. this._negateScaleChildren.z = 1 / z;
  72869. }
  72870. this._syncScaleVector();
  72871. }
  72872. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  72873. };
  72874. /**
  72875. * Scale the bone on the x, y and z axes.
  72876. * @param x The amount to scale the bone on the x axis.
  72877. * @param x The amount to scale the bone on the y axis.
  72878. * @param z The amount to scale the bone on the z axis.
  72879. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72880. */
  72881. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  72882. if (scaleChildren === void 0) { scaleChildren = false; }
  72883. var locMat = this.getLocalMatrix();
  72884. var origLocMat = Bone._tmpMats[0];
  72885. origLocMat.copyFrom(locMat);
  72886. var origLocMatInv = Bone._tmpMats[1];
  72887. origLocMatInv.copyFrom(origLocMat);
  72888. origLocMatInv.invert();
  72889. var scaleMat = Bone._tmpMats[2];
  72890. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  72891. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  72892. this._scaleVector.x *= x;
  72893. this._scaleVector.y *= y;
  72894. this._scaleVector.z *= z;
  72895. locMat.multiplyToRef(origLocMatInv, locMat);
  72896. locMat.multiplyToRef(scaleMat, locMat);
  72897. locMat.multiplyToRef(origLocMat, locMat);
  72898. var parent = this.getParent();
  72899. if (parent) {
  72900. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  72901. }
  72902. else {
  72903. this.getAbsoluteTransform().copyFrom(locMat);
  72904. }
  72905. var len = this.children.length;
  72906. scaleMat.invert();
  72907. for (var i = 0; i < len; i++) {
  72908. var child = this.children[i];
  72909. var cm = child.getLocalMatrix();
  72910. cm.multiplyToRef(scaleMat, cm);
  72911. var lm = child.getLocalMatrix();
  72912. lm.m[12] *= x;
  72913. lm.m[13] *= y;
  72914. lm.m[14] *= z;
  72915. }
  72916. this.computeAbsoluteTransforms();
  72917. if (scaleChildren) {
  72918. for (var i = 0; i < len; i++) {
  72919. this.children[i].scale(x, y, z, scaleChildren);
  72920. }
  72921. }
  72922. this.markAsDirty();
  72923. };
  72924. /**
  72925. * Set the yaw, pitch, and roll of the bone in local or world space.
  72926. * @param yaw The rotation of the bone on the y axis.
  72927. * @param pitch The rotation of the bone on the x axis.
  72928. * @param roll The rotation of the bone on the z axis.
  72929. * @param space The space that the axes of rotation are in.
  72930. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72931. */
  72932. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  72933. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72934. var rotMat = Bone._tmpMats[0];
  72935. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  72936. var rotMatInv = Bone._tmpMats[1];
  72937. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72938. rotMatInv.multiplyToRef(rotMat, rotMat);
  72939. this._rotateWithMatrix(rotMat, space, mesh);
  72940. };
  72941. /**
  72942. * Rotate the bone on an axis in local or world space.
  72943. * @param axis The axis to rotate the bone on.
  72944. * @param amount The amount to rotate the bone.
  72945. * @param space The space that the axis is in.
  72946. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72947. */
  72948. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  72949. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72950. var rmat = Bone._tmpMats[0];
  72951. rmat.m[12] = 0;
  72952. rmat.m[13] = 0;
  72953. rmat.m[14] = 0;
  72954. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  72955. this._rotateWithMatrix(rmat, space, mesh);
  72956. };
  72957. /**
  72958. * Set the rotation of the bone to a particular axis angle in local or world space.
  72959. * @param axis The axis to rotate the bone on.
  72960. * @param angle The angle that the bone should be rotated to.
  72961. * @param space The space that the axis is in.
  72962. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72963. */
  72964. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  72965. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72966. var rotMat = Bone._tmpMats[0];
  72967. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  72968. var rotMatInv = Bone._tmpMats[1];
  72969. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72970. rotMatInv.multiplyToRef(rotMat, rotMat);
  72971. this._rotateWithMatrix(rotMat, space, mesh);
  72972. };
  72973. /**
  72974. * Set the euler rotation of the bone in local of world space.
  72975. * @param rotation The euler rotation that the bone should be set to.
  72976. * @param space The space that the rotation is in.
  72977. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72978. */
  72979. Bone.prototype.setRotation = function (rotation, space, mesh) {
  72980. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72981. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  72982. };
  72983. /**
  72984. * Set the quaternion rotation of the bone in local of world space.
  72985. * @param quat The quaternion rotation that the bone should be set to.
  72986. * @param space The space that the rotation is in.
  72987. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72988. */
  72989. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  72990. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72991. var rotMatInv = Bone._tmpMats[0];
  72992. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72993. var rotMat = Bone._tmpMats[1];
  72994. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  72995. rotMatInv.multiplyToRef(rotMat, rotMat);
  72996. this._rotateWithMatrix(rotMat, space, mesh);
  72997. };
  72998. /**
  72999. * Set the rotation matrix of the bone in local of world space.
  73000. * @param rotMat The rotation matrix that the bone should be set to.
  73001. * @param space The space that the rotation is in.
  73002. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73003. */
  73004. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  73005. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73006. var rotMatInv = Bone._tmpMats[0];
  73007. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73008. var rotMat2 = Bone._tmpMats[1];
  73009. rotMat2.copyFrom(rotMat);
  73010. rotMatInv.multiplyToRef(rotMat, rotMat2);
  73011. this._rotateWithMatrix(rotMat2, space, mesh);
  73012. };
  73013. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  73014. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73015. var lmat = this.getLocalMatrix();
  73016. var lx = lmat.m[12];
  73017. var ly = lmat.m[13];
  73018. var lz = lmat.m[14];
  73019. var parent = this.getParent();
  73020. var parentScale = Bone._tmpMats[3];
  73021. var parentScaleInv = Bone._tmpMats[4];
  73022. if (parent) {
  73023. if (space == BABYLON.Space.WORLD) {
  73024. if (mesh) {
  73025. parentScale.copyFrom(mesh.getWorldMatrix());
  73026. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  73027. }
  73028. else {
  73029. parentScale.copyFrom(parent.getAbsoluteTransform());
  73030. }
  73031. }
  73032. else {
  73033. parentScale = parent._scaleMatrix;
  73034. }
  73035. parentScaleInv.copyFrom(parentScale);
  73036. parentScaleInv.invert();
  73037. lmat.multiplyToRef(parentScale, lmat);
  73038. lmat.multiplyToRef(rmat, lmat);
  73039. lmat.multiplyToRef(parentScaleInv, lmat);
  73040. }
  73041. else {
  73042. if (space == BABYLON.Space.WORLD && mesh) {
  73043. parentScale.copyFrom(mesh.getWorldMatrix());
  73044. parentScaleInv.copyFrom(parentScale);
  73045. parentScaleInv.invert();
  73046. lmat.multiplyToRef(parentScale, lmat);
  73047. lmat.multiplyToRef(rmat, lmat);
  73048. lmat.multiplyToRef(parentScaleInv, lmat);
  73049. }
  73050. else {
  73051. lmat.multiplyToRef(rmat, lmat);
  73052. }
  73053. }
  73054. lmat.m[12] = lx;
  73055. lmat.m[13] = ly;
  73056. lmat.m[14] = lz;
  73057. this.computeAbsoluteTransforms();
  73058. this.markAsDirty();
  73059. };
  73060. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  73061. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73062. if (space == BABYLON.Space.WORLD) {
  73063. var scaleMatrix = Bone._tmpMats[2];
  73064. scaleMatrix.copyFrom(this._scaleMatrix);
  73065. rotMatInv.copyFrom(this.getAbsoluteTransform());
  73066. if (mesh) {
  73067. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  73068. var meshScale = Bone._tmpMats[3];
  73069. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  73070. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  73071. }
  73072. rotMatInv.invert();
  73073. scaleMatrix.m[0] *= this._scalingDeterminant;
  73074. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  73075. }
  73076. else {
  73077. rotMatInv.copyFrom(this.getLocalMatrix());
  73078. rotMatInv.invert();
  73079. var scaleMatrix = Bone._tmpMats[2];
  73080. scaleMatrix.copyFrom(this._scaleMatrix);
  73081. if (this._parent) {
  73082. var pscaleMatrix = Bone._tmpMats[3];
  73083. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  73084. pscaleMatrix.invert();
  73085. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  73086. }
  73087. else {
  73088. scaleMatrix.m[0] *= this._scalingDeterminant;
  73089. }
  73090. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  73091. }
  73092. };
  73093. /**
  73094. * Get the scale of the bone
  73095. * @returns the scale of the bone
  73096. */
  73097. Bone.prototype.getScale = function () {
  73098. return this._scaleVector.clone();
  73099. };
  73100. /**
  73101. * Copy the scale of the bone to a vector3.
  73102. * @param result The vector3 to copy the scale to
  73103. */
  73104. Bone.prototype.getScaleToRef = function (result) {
  73105. result.copyFrom(this._scaleVector);
  73106. };
  73107. /**
  73108. * Get the position of the bone in local or world space.
  73109. * @param space The space that the returned position is in.
  73110. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73111. * @returns The position of the bone
  73112. */
  73113. Bone.prototype.getPosition = function (space, mesh) {
  73114. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73115. if (mesh === void 0) { mesh = null; }
  73116. var pos = BABYLON.Vector3.Zero();
  73117. this.getPositionToRef(space, mesh, pos);
  73118. return pos;
  73119. };
  73120. /**
  73121. * Copy the position of the bone to a vector3 in local or world space.
  73122. * @param space The space that the returned position is in.
  73123. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73124. * @param result The vector3 to copy the position to.
  73125. */
  73126. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  73127. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73128. if (space == BABYLON.Space.LOCAL) {
  73129. var lm = this.getLocalMatrix();
  73130. result.x = lm.m[12];
  73131. result.y = lm.m[13];
  73132. result.z = lm.m[14];
  73133. }
  73134. else {
  73135. var wm = null;
  73136. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73137. if (mesh) {
  73138. wm = mesh.getWorldMatrix();
  73139. }
  73140. this._skeleton.computeAbsoluteTransforms();
  73141. var tmat = Bone._tmpMats[0];
  73142. if (mesh && wm) {
  73143. tmat.copyFrom(this.getAbsoluteTransform());
  73144. tmat.multiplyToRef(wm, tmat);
  73145. }
  73146. else {
  73147. tmat = this.getAbsoluteTransform();
  73148. }
  73149. result.x = tmat.m[12];
  73150. result.y = tmat.m[13];
  73151. result.z = tmat.m[14];
  73152. }
  73153. };
  73154. /**
  73155. * Get the absolute position of the bone (world space).
  73156. * @param mesh The mesh that this bone is attached to.
  73157. * @returns The absolute position of the bone
  73158. */
  73159. Bone.prototype.getAbsolutePosition = function (mesh) {
  73160. if (mesh === void 0) { mesh = null; }
  73161. var pos = BABYLON.Vector3.Zero();
  73162. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  73163. return pos;
  73164. };
  73165. /**
  73166. * Copy the absolute position of the bone (world space) to the result param.
  73167. * @param mesh The mesh that this bone is attached to.
  73168. * @param result The vector3 to copy the absolute position to.
  73169. */
  73170. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  73171. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  73172. };
  73173. /**
  73174. * Compute the absolute transforms of this bone and its children.
  73175. */
  73176. Bone.prototype.computeAbsoluteTransforms = function () {
  73177. if (this._parent) {
  73178. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  73179. }
  73180. else {
  73181. this._absoluteTransform.copyFrom(this._localMatrix);
  73182. var poseMatrix = this._skeleton.getPoseMatrix();
  73183. if (poseMatrix) {
  73184. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  73185. }
  73186. }
  73187. var children = this.children;
  73188. var len = children.length;
  73189. for (var i = 0; i < len; i++) {
  73190. children[i].computeAbsoluteTransforms();
  73191. }
  73192. };
  73193. Bone.prototype._syncScaleVector = function () {
  73194. var lm = this.getLocalMatrix();
  73195. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  73196. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  73197. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  73198. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  73199. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  73200. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  73201. this._scaleVector.x = xs * Math.sqrt(xsq);
  73202. this._scaleVector.y = ys * Math.sqrt(ysq);
  73203. this._scaleVector.z = zs * Math.sqrt(zsq);
  73204. if (this._parent) {
  73205. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  73206. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  73207. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  73208. }
  73209. 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);
  73210. };
  73211. /**
  73212. * Get the world direction from an axis that is in the local space of the bone.
  73213. * @param localAxis The local direction that is used to compute the world direction.
  73214. * @param mesh The mesh that this bone is attached to.
  73215. * @returns The world direction
  73216. */
  73217. Bone.prototype.getDirection = function (localAxis, mesh) {
  73218. if (mesh === void 0) { mesh = null; }
  73219. var result = BABYLON.Vector3.Zero();
  73220. this.getDirectionToRef(localAxis, mesh, result);
  73221. return result;
  73222. };
  73223. /**
  73224. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  73225. * @param localAxis The local direction that is used to compute the world direction.
  73226. * @param mesh The mesh that this bone is attached to.
  73227. * @param result The vector3 that the world direction will be copied to.
  73228. */
  73229. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  73230. if (mesh === void 0) { mesh = null; }
  73231. var wm = null;
  73232. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73233. if (mesh) {
  73234. wm = mesh.getWorldMatrix();
  73235. }
  73236. this._skeleton.computeAbsoluteTransforms();
  73237. var mat = Bone._tmpMats[0];
  73238. mat.copyFrom(this.getAbsoluteTransform());
  73239. if (mesh && wm) {
  73240. mat.multiplyToRef(wm, mat);
  73241. }
  73242. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  73243. result.normalize();
  73244. };
  73245. /**
  73246. * Get the euler rotation of the bone in local or world space.
  73247. * @param space The space that the rotation should be in.
  73248. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73249. * @returns The euler rotation
  73250. */
  73251. Bone.prototype.getRotation = function (space, mesh) {
  73252. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73253. if (mesh === void 0) { mesh = null; }
  73254. var result = BABYLON.Vector3.Zero();
  73255. this.getRotationToRef(space, mesh, result);
  73256. return result;
  73257. };
  73258. /**
  73259. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  73260. * @param space The space that the rotation should be in.
  73261. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73262. * @param result The vector3 that the rotation should be copied to.
  73263. */
  73264. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  73265. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73266. if (mesh === void 0) { mesh = null; }
  73267. var quat = Bone._tmpQuat;
  73268. this.getRotationQuaternionToRef(space, mesh, quat);
  73269. quat.toEulerAnglesToRef(result);
  73270. };
  73271. /**
  73272. * Get the quaternion rotation of the bone in either local or world space.
  73273. * @param space The space that the rotation should be in.
  73274. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73275. * @returns The quaternion rotation
  73276. */
  73277. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  73278. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73279. if (mesh === void 0) { mesh = null; }
  73280. var result = BABYLON.Quaternion.Identity();
  73281. this.getRotationQuaternionToRef(space, mesh, result);
  73282. return result;
  73283. };
  73284. /**
  73285. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  73286. * @param space The space that the rotation should be in.
  73287. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73288. * @param result The quaternion that the rotation should be copied to.
  73289. */
  73290. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  73291. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73292. if (mesh === void 0) { mesh = null; }
  73293. if (space == BABYLON.Space.LOCAL) {
  73294. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  73295. }
  73296. else {
  73297. var mat = Bone._tmpMats[0];
  73298. var amat = this.getAbsoluteTransform();
  73299. if (mesh) {
  73300. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73301. }
  73302. else {
  73303. mat.copyFrom(amat);
  73304. }
  73305. mat.m[0] *= this._scalingDeterminant;
  73306. mat.m[1] *= this._scalingDeterminant;
  73307. mat.m[2] *= this._scalingDeterminant;
  73308. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  73309. }
  73310. };
  73311. /**
  73312. * Get the rotation matrix of the bone in local or world space.
  73313. * @param space The space that the rotation should be in.
  73314. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73315. * @returns The rotation matrix
  73316. */
  73317. Bone.prototype.getRotationMatrix = function (space, mesh) {
  73318. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73319. var result = BABYLON.Matrix.Identity();
  73320. this.getRotationMatrixToRef(space, mesh, result);
  73321. return result;
  73322. };
  73323. /**
  73324. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  73325. * @param space The space that the rotation should be in.
  73326. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73327. * @param result The quaternion that the rotation should be copied to.
  73328. */
  73329. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  73330. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73331. if (space == BABYLON.Space.LOCAL) {
  73332. this.getLocalMatrix().getRotationMatrixToRef(result);
  73333. }
  73334. else {
  73335. var mat = Bone._tmpMats[0];
  73336. var amat = this.getAbsoluteTransform();
  73337. if (mesh) {
  73338. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73339. }
  73340. else {
  73341. mat.copyFrom(amat);
  73342. }
  73343. mat.m[0] *= this._scalingDeterminant;
  73344. mat.m[1] *= this._scalingDeterminant;
  73345. mat.m[2] *= this._scalingDeterminant;
  73346. mat.getRotationMatrixToRef(result);
  73347. }
  73348. };
  73349. /**
  73350. * Get the world position of a point that is in the local space of the bone.
  73351. * @param position The local position
  73352. * @param mesh The mesh that this bone is attached to.
  73353. * @returns The world position
  73354. */
  73355. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  73356. if (mesh === void 0) { mesh = null; }
  73357. var result = BABYLON.Vector3.Zero();
  73358. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  73359. return result;
  73360. };
  73361. /**
  73362. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  73363. * @param position The local position
  73364. * @param mesh The mesh that this bone is attached to.
  73365. * @param result The vector3 that the world position should be copied to.
  73366. */
  73367. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  73368. if (mesh === void 0) { mesh = null; }
  73369. var wm = null;
  73370. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73371. if (mesh) {
  73372. wm = mesh.getWorldMatrix();
  73373. }
  73374. this._skeleton.computeAbsoluteTransforms();
  73375. var tmat = Bone._tmpMats[0];
  73376. if (mesh && wm) {
  73377. tmat.copyFrom(this.getAbsoluteTransform());
  73378. tmat.multiplyToRef(wm, tmat);
  73379. }
  73380. else {
  73381. tmat = this.getAbsoluteTransform();
  73382. }
  73383. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73384. };
  73385. /**
  73386. * Get the local position of a point that is in world space.
  73387. * @param position The world position
  73388. * @param mesh The mesh that this bone is attached to.
  73389. * @returns The local position
  73390. */
  73391. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  73392. if (mesh === void 0) { mesh = null; }
  73393. var result = BABYLON.Vector3.Zero();
  73394. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  73395. return result;
  73396. };
  73397. /**
  73398. * Get the local position of a point that is in world space and copy it to the result param.
  73399. * @param position The world position
  73400. * @param mesh The mesh that this bone is attached to.
  73401. * @param result The vector3 that the local position should be copied to.
  73402. */
  73403. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  73404. if (mesh === void 0) { mesh = null; }
  73405. var wm = null;
  73406. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73407. if (mesh) {
  73408. wm = mesh.getWorldMatrix();
  73409. }
  73410. this._skeleton.computeAbsoluteTransforms();
  73411. var tmat = Bone._tmpMats[0];
  73412. tmat.copyFrom(this.getAbsoluteTransform());
  73413. if (mesh && wm) {
  73414. tmat.multiplyToRef(wm, tmat);
  73415. }
  73416. tmat.invert();
  73417. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73418. };
  73419. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73420. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  73421. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73422. return Bone;
  73423. }(BABYLON.Node));
  73424. BABYLON.Bone = Bone;
  73425. })(BABYLON || (BABYLON = {}));
  73426. //# sourceMappingURL=babylon.bone.js.map
  73427. "use strict";
  73428. var BABYLON;
  73429. (function (BABYLON) {
  73430. var BoneIKController = /** @class */ (function () {
  73431. function BoneIKController(mesh, bone, options) {
  73432. this.targetPosition = BABYLON.Vector3.Zero();
  73433. this.poleTargetPosition = BABYLON.Vector3.Zero();
  73434. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  73435. this.poleAngle = 0;
  73436. this.slerpAmount = 1;
  73437. this._bone1Quat = BABYLON.Quaternion.Identity();
  73438. this._bone1Mat = BABYLON.Matrix.Identity();
  73439. this._bone2Ang = Math.PI;
  73440. this._maxAngle = Math.PI;
  73441. this._rightHandedSystem = false;
  73442. this._bendAxis = BABYLON.Vector3.Right();
  73443. this._slerping = false;
  73444. this._adjustRoll = 0;
  73445. this._bone2 = bone;
  73446. this._bone1 = bone.getParent();
  73447. if (!this._bone1) {
  73448. return;
  73449. }
  73450. this.mesh = mesh;
  73451. var bonePos = bone.getPosition();
  73452. if (bone.getAbsoluteTransform().determinant() > 0) {
  73453. this._rightHandedSystem = true;
  73454. this._bendAxis.x = 0;
  73455. this._bendAxis.y = 0;
  73456. this._bendAxis.z = -1;
  73457. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  73458. this._adjustRoll = Math.PI * .5;
  73459. this._bendAxis.z = 1;
  73460. }
  73461. }
  73462. if (this._bone1.length) {
  73463. var boneScale1 = this._bone1.getScale();
  73464. var boneScale2 = this._bone2.getScale();
  73465. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  73466. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  73467. }
  73468. else if (this._bone1.children[0]) {
  73469. mesh.computeWorldMatrix(true);
  73470. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  73471. var pos2 = this._bone2.getAbsolutePosition(mesh);
  73472. var pos3 = this._bone1.getAbsolutePosition(mesh);
  73473. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  73474. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  73475. }
  73476. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  73477. this.maxAngle = Math.PI;
  73478. if (options) {
  73479. if (options.targetMesh) {
  73480. this.targetMesh = options.targetMesh;
  73481. this.targetMesh.computeWorldMatrix(true);
  73482. }
  73483. if (options.poleTargetMesh) {
  73484. this.poleTargetMesh = options.poleTargetMesh;
  73485. this.poleTargetMesh.computeWorldMatrix(true);
  73486. }
  73487. else if (options.poleTargetBone) {
  73488. this.poleTargetBone = options.poleTargetBone;
  73489. }
  73490. else if (this._bone1.getParent()) {
  73491. this.poleTargetBone = this._bone1.getParent();
  73492. }
  73493. if (options.poleTargetLocalOffset) {
  73494. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  73495. }
  73496. if (options.poleAngle) {
  73497. this.poleAngle = options.poleAngle;
  73498. }
  73499. if (options.bendAxis) {
  73500. this._bendAxis.copyFrom(options.bendAxis);
  73501. }
  73502. if (options.maxAngle) {
  73503. this.maxAngle = options.maxAngle;
  73504. }
  73505. if (options.slerpAmount) {
  73506. this.slerpAmount = options.slerpAmount;
  73507. }
  73508. }
  73509. }
  73510. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  73511. get: function () {
  73512. return this._maxAngle;
  73513. },
  73514. set: function (value) {
  73515. this._setMaxAngle(value);
  73516. },
  73517. enumerable: true,
  73518. configurable: true
  73519. });
  73520. BoneIKController.prototype._setMaxAngle = function (ang) {
  73521. if (ang < 0) {
  73522. ang = 0;
  73523. }
  73524. if (ang > Math.PI || ang == undefined) {
  73525. ang = Math.PI;
  73526. }
  73527. this._maxAngle = ang;
  73528. var a = this._bone1Length;
  73529. var b = this._bone2Length;
  73530. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  73531. };
  73532. BoneIKController.prototype.update = function () {
  73533. var bone1 = this._bone1;
  73534. if (!bone1) {
  73535. return;
  73536. }
  73537. var target = this.targetPosition;
  73538. var poleTarget = this.poleTargetPosition;
  73539. var mat1 = BoneIKController._tmpMats[0];
  73540. var mat2 = BoneIKController._tmpMats[1];
  73541. if (this.targetMesh) {
  73542. target.copyFrom(this.targetMesh.getAbsolutePosition());
  73543. }
  73544. if (this.poleTargetBone) {
  73545. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  73546. }
  73547. else if (this.poleTargetMesh) {
  73548. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  73549. }
  73550. var bonePos = BoneIKController._tmpVecs[0];
  73551. var zaxis = BoneIKController._tmpVecs[1];
  73552. var xaxis = BoneIKController._tmpVecs[2];
  73553. var yaxis = BoneIKController._tmpVecs[3];
  73554. var upAxis = BoneIKController._tmpVecs[4];
  73555. var _tmpQuat = BoneIKController._tmpQuat;
  73556. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  73557. poleTarget.subtractToRef(bonePos, upAxis);
  73558. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  73559. upAxis.y = 1;
  73560. }
  73561. else {
  73562. upAxis.normalize();
  73563. }
  73564. target.subtractToRef(bonePos, yaxis);
  73565. yaxis.normalize();
  73566. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  73567. zaxis.normalize();
  73568. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  73569. xaxis.normalize();
  73570. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  73571. var a = this._bone1Length;
  73572. var b = this._bone2Length;
  73573. var c = BABYLON.Vector3.Distance(bonePos, target);
  73574. if (this._maxReach > 0) {
  73575. c = Math.min(this._maxReach, c);
  73576. }
  73577. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  73578. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  73579. if (acosa > 1) {
  73580. acosa = 1;
  73581. }
  73582. if (acosb > 1) {
  73583. acosb = 1;
  73584. }
  73585. if (acosa < -1) {
  73586. acosa = -1;
  73587. }
  73588. if (acosb < -1) {
  73589. acosb = -1;
  73590. }
  73591. var angA = Math.acos(acosa);
  73592. var angB = Math.acos(acosb);
  73593. var angC = -angA - angB;
  73594. if (this._rightHandedSystem) {
  73595. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  73596. mat2.multiplyToRef(mat1, mat1);
  73597. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  73598. mat2.multiplyToRef(mat1, mat1);
  73599. }
  73600. else {
  73601. var _tmpVec = BoneIKController._tmpVecs[5];
  73602. _tmpVec.copyFrom(this._bendAxis);
  73603. _tmpVec.x *= -1;
  73604. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  73605. mat2.multiplyToRef(mat1, mat1);
  73606. }
  73607. if (this.poleAngle) {
  73608. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  73609. mat1.multiplyToRef(mat2, mat1);
  73610. }
  73611. if (this._bone1) {
  73612. if (this.slerpAmount < 1) {
  73613. if (!this._slerping) {
  73614. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  73615. }
  73616. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  73617. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  73618. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  73619. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  73620. this._slerping = true;
  73621. }
  73622. else {
  73623. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  73624. this._bone1Mat.copyFrom(mat1);
  73625. this._slerping = false;
  73626. }
  73627. }
  73628. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  73629. this._bone2Ang = angC;
  73630. };
  73631. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73632. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  73633. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73634. return BoneIKController;
  73635. }());
  73636. BABYLON.BoneIKController = BoneIKController;
  73637. })(BABYLON || (BABYLON = {}));
  73638. //# sourceMappingURL=babylon.boneIKController.js.map
  73639. "use strict";
  73640. var BABYLON;
  73641. (function (BABYLON) {
  73642. var BoneLookController = /** @class */ (function () {
  73643. /**
  73644. * Create a BoneLookController
  73645. * @param mesh the mesh that the bone belongs to
  73646. * @param bone the bone that will be looking to the target
  73647. * @param target the target Vector3 to look at
  73648. * @param settings optional settings:
  73649. * - maxYaw: the maximum angle the bone will yaw to
  73650. * - minYaw: the minimum angle the bone will yaw to
  73651. * - maxPitch: the maximum angle the bone will pitch to
  73652. * - minPitch: the minimum angle the bone will yaw to
  73653. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  73654. * - upAxis: the up axis of the coordinate system
  73655. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73656. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  73657. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  73658. * - adjustYaw: used to make an adjustment to the yaw of the bone
  73659. * - adjustPitch: used to make an adjustment to the pitch of the bone
  73660. * - adjustRoll: used to make an adjustment to the roll of the bone
  73661. **/
  73662. function BoneLookController(mesh, bone, target, options) {
  73663. /**
  73664. * The up axis of the coordinate system that is used when the bone is rotated.
  73665. */
  73666. this.upAxis = BABYLON.Vector3.Up();
  73667. /**
  73668. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73669. */
  73670. this.upAxisSpace = BABYLON.Space.LOCAL;
  73671. /**
  73672. * Used to make an adjustment to the yaw of the bone.
  73673. */
  73674. this.adjustYaw = 0;
  73675. /**
  73676. * Used to make an adjustment to the pitch of the bone.
  73677. */
  73678. this.adjustPitch = 0;
  73679. /**
  73680. * Used to make an adjustment to the roll of the bone.
  73681. */
  73682. this.adjustRoll = 0;
  73683. /**
  73684. * 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).
  73685. */
  73686. this.slerpAmount = 1;
  73687. this._boneQuat = BABYLON.Quaternion.Identity();
  73688. this._slerping = false;
  73689. this._firstFrameSkipped = false;
  73690. this._fowardAxis = BABYLON.Vector3.Forward();
  73691. this.mesh = mesh;
  73692. this.bone = bone;
  73693. this.target = target;
  73694. if (options) {
  73695. if (options.adjustYaw) {
  73696. this.adjustYaw = options.adjustYaw;
  73697. }
  73698. if (options.adjustPitch) {
  73699. this.adjustPitch = options.adjustPitch;
  73700. }
  73701. if (options.adjustRoll) {
  73702. this.adjustRoll = options.adjustRoll;
  73703. }
  73704. if (options.maxYaw != null) {
  73705. this.maxYaw = options.maxYaw;
  73706. }
  73707. else {
  73708. this.maxYaw = Math.PI;
  73709. }
  73710. if (options.minYaw != null) {
  73711. this.minYaw = options.minYaw;
  73712. }
  73713. else {
  73714. this.minYaw = -Math.PI;
  73715. }
  73716. if (options.maxPitch != null) {
  73717. this.maxPitch = options.maxPitch;
  73718. }
  73719. else {
  73720. this.maxPitch = Math.PI;
  73721. }
  73722. if (options.minPitch != null) {
  73723. this.minPitch = options.minPitch;
  73724. }
  73725. else {
  73726. this.minPitch = -Math.PI;
  73727. }
  73728. if (options.slerpAmount != null) {
  73729. this.slerpAmount = options.slerpAmount;
  73730. }
  73731. if (options.upAxis != null) {
  73732. this.upAxis = options.upAxis;
  73733. }
  73734. if (options.upAxisSpace != null) {
  73735. this.upAxisSpace = options.upAxisSpace;
  73736. }
  73737. if (options.yawAxis != null || options.pitchAxis != null) {
  73738. var newYawAxis = BABYLON.Axis.Y;
  73739. var newPitchAxis = BABYLON.Axis.X;
  73740. if (options.yawAxis != null) {
  73741. newYawAxis = options.yawAxis.clone();
  73742. newYawAxis.normalize();
  73743. }
  73744. if (options.pitchAxis != null) {
  73745. newPitchAxis = options.pitchAxis.clone();
  73746. newPitchAxis.normalize();
  73747. }
  73748. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  73749. this._transformYawPitch = BABYLON.Matrix.Identity();
  73750. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  73751. this._transformYawPitchInv = this._transformYawPitch.clone();
  73752. this._transformYawPitch.invert();
  73753. }
  73754. }
  73755. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  73756. this.upAxisSpace = BABYLON.Space.LOCAL;
  73757. }
  73758. }
  73759. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  73760. /**
  73761. * Get/set the minimum yaw angle that the bone can look to.
  73762. */
  73763. get: function () {
  73764. return this._minYaw;
  73765. },
  73766. set: function (value) {
  73767. this._minYaw = value;
  73768. this._minYawSin = Math.sin(value);
  73769. this._minYawCos = Math.cos(value);
  73770. if (this._maxYaw != null) {
  73771. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73772. this._yawRange = this._maxYaw - this._minYaw;
  73773. }
  73774. },
  73775. enumerable: true,
  73776. configurable: true
  73777. });
  73778. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  73779. /**
  73780. * Get/set the maximum yaw angle that the bone can look to.
  73781. */
  73782. get: function () {
  73783. return this._maxYaw;
  73784. },
  73785. set: function (value) {
  73786. this._maxYaw = value;
  73787. this._maxYawSin = Math.sin(value);
  73788. this._maxYawCos = Math.cos(value);
  73789. if (this._minYaw != null) {
  73790. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73791. this._yawRange = this._maxYaw - this._minYaw;
  73792. }
  73793. },
  73794. enumerable: true,
  73795. configurable: true
  73796. });
  73797. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  73798. /**
  73799. * Get/set the minimum pitch angle that the bone can look to.
  73800. */
  73801. get: function () {
  73802. return this._minPitch;
  73803. },
  73804. set: function (value) {
  73805. this._minPitch = value;
  73806. this._minPitchTan = Math.tan(value);
  73807. },
  73808. enumerable: true,
  73809. configurable: true
  73810. });
  73811. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  73812. /**
  73813. * Get/set the maximum pitch angle that the bone can look to.
  73814. */
  73815. get: function () {
  73816. return this._maxPitch;
  73817. },
  73818. set: function (value) {
  73819. this._maxPitch = value;
  73820. this._maxPitchTan = Math.tan(value);
  73821. },
  73822. enumerable: true,
  73823. configurable: true
  73824. });
  73825. /**
  73826. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  73827. */
  73828. BoneLookController.prototype.update = function () {
  73829. //skip the first frame when slerping so that the mesh rotation is correct
  73830. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  73831. this._firstFrameSkipped = true;
  73832. return;
  73833. }
  73834. var bone = this.bone;
  73835. var bonePos = BoneLookController._tmpVecs[0];
  73836. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  73837. var target = this.target;
  73838. var _tmpMat1 = BoneLookController._tmpMats[0];
  73839. var _tmpMat2 = BoneLookController._tmpMats[1];
  73840. var mesh = this.mesh;
  73841. var parentBone = bone.getParent();
  73842. var upAxis = BoneLookController._tmpVecs[1];
  73843. upAxis.copyFrom(this.upAxis);
  73844. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  73845. if (this._transformYawPitch) {
  73846. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  73847. }
  73848. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  73849. }
  73850. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  73851. mesh.getDirectionToRef(upAxis, upAxis);
  73852. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  73853. upAxis.normalize();
  73854. }
  73855. }
  73856. var checkYaw = false;
  73857. var checkPitch = false;
  73858. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  73859. checkYaw = true;
  73860. }
  73861. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  73862. checkPitch = true;
  73863. }
  73864. if (checkYaw || checkPitch) {
  73865. var spaceMat = BoneLookController._tmpMats[2];
  73866. var spaceMatInv = BoneLookController._tmpMats[3];
  73867. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  73868. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  73869. }
  73870. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  73871. spaceMat.copyFrom(mesh.getWorldMatrix());
  73872. }
  73873. else {
  73874. var forwardAxis = BoneLookController._tmpVecs[2];
  73875. forwardAxis.copyFrom(this._fowardAxis);
  73876. if (this._transformYawPitch) {
  73877. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  73878. }
  73879. if (parentBone) {
  73880. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  73881. }
  73882. else {
  73883. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  73884. }
  73885. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  73886. rightAxis.normalize();
  73887. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  73888. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  73889. }
  73890. spaceMat.invertToRef(spaceMatInv);
  73891. var xzlen = null;
  73892. if (checkPitch) {
  73893. var localTarget = BoneLookController._tmpVecs[3];
  73894. target.subtractToRef(bonePos, localTarget);
  73895. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73896. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73897. var pitch = Math.atan2(localTarget.y, xzlen);
  73898. var newPitch = pitch;
  73899. if (pitch > this._maxPitch) {
  73900. localTarget.y = this._maxPitchTan * xzlen;
  73901. newPitch = this._maxPitch;
  73902. }
  73903. else if (pitch < this._minPitch) {
  73904. localTarget.y = this._minPitchTan * xzlen;
  73905. newPitch = this._minPitch;
  73906. }
  73907. if (pitch != newPitch) {
  73908. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73909. localTarget.addInPlace(bonePos);
  73910. target = localTarget;
  73911. }
  73912. }
  73913. if (checkYaw) {
  73914. var localTarget = BoneLookController._tmpVecs[4];
  73915. target.subtractToRef(bonePos, localTarget);
  73916. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73917. var yaw = Math.atan2(localTarget.x, localTarget.z);
  73918. var newYaw = yaw;
  73919. if (yaw > this._maxYaw || yaw < this._minYaw) {
  73920. if (xzlen == null) {
  73921. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73922. }
  73923. if (this._yawRange > Math.PI) {
  73924. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  73925. localTarget.z = this._maxYawCos * xzlen;
  73926. localTarget.x = this._maxYawSin * xzlen;
  73927. newYaw = this._maxYaw;
  73928. }
  73929. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  73930. localTarget.z = this._minYawCos * xzlen;
  73931. localTarget.x = this._minYawSin * xzlen;
  73932. newYaw = this._minYaw;
  73933. }
  73934. }
  73935. else {
  73936. if (yaw > this._maxYaw) {
  73937. localTarget.z = this._maxYawCos * xzlen;
  73938. localTarget.x = this._maxYawSin * xzlen;
  73939. newYaw = this._maxYaw;
  73940. }
  73941. else if (yaw < this._minYaw) {
  73942. localTarget.z = this._minYawCos * xzlen;
  73943. localTarget.x = this._minYawSin * xzlen;
  73944. newYaw = this._minYaw;
  73945. }
  73946. }
  73947. }
  73948. if (this._slerping && this._yawRange > Math.PI) {
  73949. //are we going to be crossing into the min/max region?
  73950. var boneFwd = BoneLookController._tmpVecs[8];
  73951. boneFwd.copyFrom(BABYLON.Axis.Z);
  73952. if (this._transformYawPitch) {
  73953. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  73954. }
  73955. var boneRotMat = BoneLookController._tmpMats[4];
  73956. this._boneQuat.toRotationMatrix(boneRotMat);
  73957. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  73958. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  73959. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  73960. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  73961. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  73962. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  73963. if (angBtwTar > angBtwMidYaw) {
  73964. if (xzlen == null) {
  73965. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73966. }
  73967. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  73968. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  73969. if (angBtwMin < angBtwMax) {
  73970. newYaw = boneYaw + Math.PI * .75;
  73971. localTarget.z = Math.cos(newYaw) * xzlen;
  73972. localTarget.x = Math.sin(newYaw) * xzlen;
  73973. }
  73974. else {
  73975. newYaw = boneYaw - Math.PI * .75;
  73976. localTarget.z = Math.cos(newYaw) * xzlen;
  73977. localTarget.x = Math.sin(newYaw) * xzlen;
  73978. }
  73979. }
  73980. }
  73981. if (yaw != newYaw) {
  73982. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73983. localTarget.addInPlace(bonePos);
  73984. target = localTarget;
  73985. }
  73986. }
  73987. }
  73988. var zaxis = BoneLookController._tmpVecs[5];
  73989. var xaxis = BoneLookController._tmpVecs[6];
  73990. var yaxis = BoneLookController._tmpVecs[7];
  73991. var _tmpQuat = BoneLookController._tmpQuat;
  73992. target.subtractToRef(bonePos, zaxis);
  73993. zaxis.normalize();
  73994. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  73995. xaxis.normalize();
  73996. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  73997. yaxis.normalize();
  73998. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  73999. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  74000. return;
  74001. }
  74002. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  74003. return;
  74004. }
  74005. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  74006. return;
  74007. }
  74008. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  74009. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  74010. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  74011. }
  74012. if (this.slerpAmount < 1) {
  74013. if (!this._slerping) {
  74014. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  74015. }
  74016. if (this._transformYawPitch) {
  74017. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  74018. }
  74019. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  74020. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  74021. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  74022. this._slerping = true;
  74023. }
  74024. else {
  74025. if (this._transformYawPitch) {
  74026. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  74027. }
  74028. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  74029. this._slerping = false;
  74030. }
  74031. };
  74032. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  74033. var angDiff = ang2 - ang1;
  74034. angDiff %= Math.PI * 2;
  74035. if (angDiff > Math.PI) {
  74036. angDiff -= Math.PI * 2;
  74037. }
  74038. else if (angDiff < -Math.PI) {
  74039. angDiff += Math.PI * 2;
  74040. }
  74041. return angDiff;
  74042. };
  74043. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  74044. ang1 %= (2 * Math.PI);
  74045. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  74046. ang2 %= (2 * Math.PI);
  74047. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  74048. var ab = 0;
  74049. if (ang1 < ang2) {
  74050. ab = ang2 - ang1;
  74051. }
  74052. else {
  74053. ab = ang1 - ang2;
  74054. }
  74055. if (ab > Math.PI) {
  74056. ab = Math.PI * 2 - ab;
  74057. }
  74058. return ab;
  74059. };
  74060. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  74061. ang %= (2 * Math.PI);
  74062. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  74063. ang1 %= (2 * Math.PI);
  74064. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  74065. ang2 %= (2 * Math.PI);
  74066. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  74067. if (ang1 < ang2) {
  74068. if (ang > ang1 && ang < ang2) {
  74069. return true;
  74070. }
  74071. }
  74072. else {
  74073. if (ang > ang2 && ang < ang1) {
  74074. return true;
  74075. }
  74076. }
  74077. return false;
  74078. };
  74079. 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()];
  74080. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  74081. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  74082. return BoneLookController;
  74083. }());
  74084. BABYLON.BoneLookController = BoneLookController;
  74085. })(BABYLON || (BABYLON = {}));
  74086. //# sourceMappingURL=babylon.boneLookController.js.map
  74087. "use strict";
  74088. var BABYLON;
  74089. (function (BABYLON) {
  74090. var Skeleton = /** @class */ (function () {
  74091. function Skeleton(name, id, scene) {
  74092. this.name = name;
  74093. this.id = id;
  74094. this.bones = new Array();
  74095. this.needInitialSkinMatrix = false;
  74096. this._isDirty = true;
  74097. this._meshesWithPoseMatrix = new Array();
  74098. this._identity = BABYLON.Matrix.Identity();
  74099. this._ranges = {};
  74100. this._lastAbsoluteTransformsUpdateId = -1;
  74101. /**
  74102. * Specifies if the skeleton should be serialized.
  74103. */
  74104. this.doNotSerialize = false;
  74105. // Events
  74106. /**
  74107. * An event triggered before computing the skeleton's matrices
  74108. * @type {BABYLON.Observable}
  74109. */
  74110. this.onBeforeComputeObservable = new BABYLON.Observable();
  74111. this.bones = [];
  74112. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74113. scene.skeletons.push(this);
  74114. //make sure it will recalculate the matrix next time prepare is called.
  74115. this._isDirty = true;
  74116. }
  74117. // Members
  74118. Skeleton.prototype.getTransformMatrices = function (mesh) {
  74119. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  74120. return mesh._bonesTransformMatrices;
  74121. }
  74122. if (!this._transformMatrices) {
  74123. this.prepare();
  74124. }
  74125. return this._transformMatrices;
  74126. };
  74127. Skeleton.prototype.getScene = function () {
  74128. return this._scene;
  74129. };
  74130. // Methods
  74131. /**
  74132. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  74133. */
  74134. Skeleton.prototype.toString = function (fullDetails) {
  74135. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  74136. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  74137. if (fullDetails) {
  74138. ret += ", Ranges: {";
  74139. var first = true;
  74140. for (var name_1 in this._ranges) {
  74141. if (first) {
  74142. ret += ", ";
  74143. first = false;
  74144. }
  74145. ret += name_1;
  74146. }
  74147. ret += "}";
  74148. }
  74149. return ret;
  74150. };
  74151. /**
  74152. * Get bone's index searching by name
  74153. * @param {string} name is bone's name to search for
  74154. * @return {number} Indice of the bone. Returns -1 if not found
  74155. */
  74156. Skeleton.prototype.getBoneIndexByName = function (name) {
  74157. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  74158. if (this.bones[boneIndex].name === name) {
  74159. return boneIndex;
  74160. }
  74161. }
  74162. return -1;
  74163. };
  74164. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  74165. // check name not already in use
  74166. if (!this._ranges[name]) {
  74167. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  74168. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74169. if (this.bones[i].animations[0]) {
  74170. this.bones[i].animations[0].createRange(name, from, to);
  74171. }
  74172. }
  74173. }
  74174. };
  74175. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  74176. if (deleteFrames === void 0) { deleteFrames = true; }
  74177. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74178. if (this.bones[i].animations[0]) {
  74179. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  74180. }
  74181. }
  74182. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  74183. };
  74184. Skeleton.prototype.getAnimationRange = function (name) {
  74185. return this._ranges[name];
  74186. };
  74187. /**
  74188. * Returns as an Array, all AnimationRanges defined on this skeleton
  74189. */
  74190. Skeleton.prototype.getAnimationRanges = function () {
  74191. var animationRanges = [];
  74192. var name;
  74193. var i = 0;
  74194. for (name in this._ranges) {
  74195. animationRanges[i] = this._ranges[name];
  74196. i++;
  74197. }
  74198. return animationRanges;
  74199. };
  74200. /**
  74201. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  74202. */
  74203. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  74204. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  74205. if (this._ranges[name] || !source.getAnimationRange(name)) {
  74206. return false;
  74207. }
  74208. var ret = true;
  74209. var frameOffset = this._getHighestAnimationFrame() + 1;
  74210. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  74211. var boneDict = {};
  74212. var sourceBones = source.bones;
  74213. var nBones;
  74214. var i;
  74215. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  74216. boneDict[sourceBones[i].name] = sourceBones[i];
  74217. }
  74218. if (this.bones.length !== sourceBones.length) {
  74219. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  74220. ret = false;
  74221. }
  74222. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  74223. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  74224. var boneName = this.bones[i].name;
  74225. var sourceBone = boneDict[boneName];
  74226. if (sourceBone) {
  74227. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  74228. }
  74229. else {
  74230. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  74231. ret = false;
  74232. }
  74233. }
  74234. // do not call createAnimationRange(), since it also is done to bones, which was already done
  74235. var range = source.getAnimationRange(name);
  74236. if (range) {
  74237. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  74238. }
  74239. return ret;
  74240. };
  74241. Skeleton.prototype.returnToRest = function () {
  74242. for (var index = 0; index < this.bones.length; index++) {
  74243. this.bones[index].returnToRest();
  74244. }
  74245. };
  74246. Skeleton.prototype._getHighestAnimationFrame = function () {
  74247. var ret = 0;
  74248. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74249. if (this.bones[i].animations[0]) {
  74250. var highest = this.bones[i].animations[0].getHighestFrame();
  74251. if (ret < highest) {
  74252. ret = highest;
  74253. }
  74254. }
  74255. }
  74256. return ret;
  74257. };
  74258. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  74259. var range = this.getAnimationRange(name);
  74260. if (!range) {
  74261. return null;
  74262. }
  74263. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  74264. };
  74265. Skeleton.prototype._markAsDirty = function () {
  74266. this._isDirty = true;
  74267. };
  74268. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  74269. this._meshesWithPoseMatrix.push(mesh);
  74270. };
  74271. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  74272. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  74273. if (index > -1) {
  74274. this._meshesWithPoseMatrix.splice(index, 1);
  74275. }
  74276. };
  74277. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  74278. this.onBeforeComputeObservable.notifyObservers(this);
  74279. for (var index = 0; index < this.bones.length; index++) {
  74280. var bone = this.bones[index];
  74281. var parentBone = bone.getParent();
  74282. if (parentBone) {
  74283. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  74284. }
  74285. else {
  74286. if (initialSkinMatrix) {
  74287. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  74288. }
  74289. else {
  74290. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  74291. }
  74292. }
  74293. if (bone._index !== -1) {
  74294. var mappedIndex = bone._index === null ? index : bone._index;
  74295. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  74296. }
  74297. }
  74298. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  74299. };
  74300. Skeleton.prototype.prepare = function () {
  74301. if (!this._isDirty) {
  74302. return;
  74303. }
  74304. if (this.needInitialSkinMatrix) {
  74305. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  74306. var mesh = this._meshesWithPoseMatrix[index];
  74307. var poseMatrix = mesh.getPoseMatrix();
  74308. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  74309. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  74310. }
  74311. if (this._synchronizedWithMesh !== mesh) {
  74312. this._synchronizedWithMesh = mesh;
  74313. // Prepare bones
  74314. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  74315. var bone = this.bones[boneIndex];
  74316. if (!bone.getParent()) {
  74317. var matrix = bone.getBaseMatrix();
  74318. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  74319. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  74320. }
  74321. }
  74322. }
  74323. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  74324. }
  74325. }
  74326. else {
  74327. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  74328. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  74329. }
  74330. this._computeTransformMatrices(this._transformMatrices, null);
  74331. }
  74332. this._isDirty = false;
  74333. this._scene._activeBones.addCount(this.bones.length, false);
  74334. };
  74335. Skeleton.prototype.getAnimatables = function () {
  74336. if (!this._animatables || this._animatables.length !== this.bones.length) {
  74337. this._animatables = [];
  74338. for (var index = 0; index < this.bones.length; index++) {
  74339. this._animatables.push(this.bones[index]);
  74340. }
  74341. }
  74342. return this._animatables;
  74343. };
  74344. Skeleton.prototype.clone = function (name, id) {
  74345. var result = new Skeleton(name, id || name, this._scene);
  74346. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74347. for (var index = 0; index < this.bones.length; index++) {
  74348. var source = this.bones[index];
  74349. var parentBone = null;
  74350. var parent_1 = source.getParent();
  74351. if (parent_1) {
  74352. var parentIndex = this.bones.indexOf(parent_1);
  74353. parentBone = result.bones[parentIndex];
  74354. }
  74355. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  74356. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  74357. }
  74358. if (this._ranges) {
  74359. result._ranges = {};
  74360. for (var rangeName in this._ranges) {
  74361. var range = this._ranges[rangeName];
  74362. if (range) {
  74363. result._ranges[rangeName] = range.clone();
  74364. }
  74365. }
  74366. }
  74367. this._isDirty = true;
  74368. return result;
  74369. };
  74370. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  74371. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  74372. this.bones.forEach(function (bone) {
  74373. bone.animations.forEach(function (animation) {
  74374. animation.enableBlending = true;
  74375. animation.blendingSpeed = blendingSpeed;
  74376. });
  74377. });
  74378. };
  74379. Skeleton.prototype.dispose = function () {
  74380. this._meshesWithPoseMatrix = [];
  74381. // Animations
  74382. this.getScene().stopAnimation(this);
  74383. // Remove from scene
  74384. this.getScene().removeSkeleton(this);
  74385. };
  74386. Skeleton.prototype.serialize = function () {
  74387. var serializationObject = {};
  74388. serializationObject.name = this.name;
  74389. serializationObject.id = this.id;
  74390. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  74391. serializationObject.bones = [];
  74392. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74393. for (var index = 0; index < this.bones.length; index++) {
  74394. var bone = this.bones[index];
  74395. var parent_2 = bone.getParent();
  74396. var serializedBone = {
  74397. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  74398. name: bone.name,
  74399. matrix: bone.getBaseMatrix().toArray(),
  74400. rest: bone.getRestPose().toArray()
  74401. };
  74402. serializationObject.bones.push(serializedBone);
  74403. if (bone.length) {
  74404. serializedBone.length = bone.length;
  74405. }
  74406. if (bone.animations && bone.animations.length > 0) {
  74407. serializedBone.animation = bone.animations[0].serialize();
  74408. }
  74409. serializationObject.ranges = [];
  74410. for (var name in this._ranges) {
  74411. var source = this._ranges[name];
  74412. if (!source) {
  74413. continue;
  74414. }
  74415. var range = {};
  74416. range.name = name;
  74417. range.from = source.from;
  74418. range.to = source.to;
  74419. serializationObject.ranges.push(range);
  74420. }
  74421. }
  74422. return serializationObject;
  74423. };
  74424. Skeleton.Parse = function (parsedSkeleton, scene) {
  74425. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  74426. if (parsedSkeleton.dimensionsAtRest) {
  74427. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  74428. }
  74429. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  74430. var index;
  74431. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  74432. var parsedBone = parsedSkeleton.bones[index];
  74433. var parentBone = null;
  74434. if (parsedBone.parentBoneIndex > -1) {
  74435. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  74436. }
  74437. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  74438. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  74439. if (parsedBone.length) {
  74440. bone.length = parsedBone.length;
  74441. }
  74442. if (parsedBone.animation) {
  74443. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  74444. }
  74445. }
  74446. // placed after bones, so createAnimationRange can cascade down
  74447. if (parsedSkeleton.ranges) {
  74448. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  74449. var data = parsedSkeleton.ranges[index];
  74450. skeleton.createAnimationRange(data.name, data.from, data.to);
  74451. }
  74452. }
  74453. return skeleton;
  74454. };
  74455. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  74456. if (forceUpdate === void 0) { forceUpdate = false; }
  74457. var renderId = this._scene.getRenderId();
  74458. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  74459. this.bones[0].computeAbsoluteTransforms();
  74460. this._lastAbsoluteTransformsUpdateId = renderId;
  74461. }
  74462. };
  74463. Skeleton.prototype.getPoseMatrix = function () {
  74464. var poseMatrix = null;
  74465. if (this._meshesWithPoseMatrix.length > 0) {
  74466. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  74467. }
  74468. return poseMatrix;
  74469. };
  74470. Skeleton.prototype.sortBones = function () {
  74471. var bones = new Array();
  74472. var visited = new Array(this.bones.length);
  74473. for (var index = 0; index < this.bones.length; index++) {
  74474. this._sortBones(index, bones, visited);
  74475. }
  74476. this.bones = bones;
  74477. };
  74478. Skeleton.prototype._sortBones = function (index, bones, visited) {
  74479. if (visited[index]) {
  74480. return;
  74481. }
  74482. visited[index] = true;
  74483. var bone = this.bones[index];
  74484. if (bone._index === undefined) {
  74485. bone._index = index;
  74486. }
  74487. var parentBone = bone.getParent();
  74488. if (parentBone) {
  74489. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  74490. }
  74491. bones.push(bone);
  74492. };
  74493. return Skeleton;
  74494. }());
  74495. BABYLON.Skeleton = Skeleton;
  74496. })(BABYLON || (BABYLON = {}));
  74497. //# sourceMappingURL=babylon.skeleton.js.map
  74498. "use strict";
  74499. var BABYLON;
  74500. (function (BABYLON) {
  74501. var SphericalPolynomial = /** @class */ (function () {
  74502. function SphericalPolynomial() {
  74503. this.x = BABYLON.Vector3.Zero();
  74504. this.y = BABYLON.Vector3.Zero();
  74505. this.z = BABYLON.Vector3.Zero();
  74506. this.xx = BABYLON.Vector3.Zero();
  74507. this.yy = BABYLON.Vector3.Zero();
  74508. this.zz = BABYLON.Vector3.Zero();
  74509. this.xy = BABYLON.Vector3.Zero();
  74510. this.yz = BABYLON.Vector3.Zero();
  74511. this.zx = BABYLON.Vector3.Zero();
  74512. }
  74513. SphericalPolynomial.prototype.addAmbient = function (color) {
  74514. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74515. this.xx = this.xx.add(colorVector);
  74516. this.yy = this.yy.add(colorVector);
  74517. this.zz = this.zz.add(colorVector);
  74518. };
  74519. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  74520. var result = new SphericalPolynomial();
  74521. result.x = harmonics.L11.scale(1.02333);
  74522. result.y = harmonics.L1_1.scale(1.02333);
  74523. result.z = harmonics.L10.scale(1.02333);
  74524. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  74525. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  74526. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  74527. result.yz = harmonics.L2_1.scale(0.858086);
  74528. result.zx = harmonics.L21.scale(0.858086);
  74529. result.xy = harmonics.L2_2.scale(0.858086);
  74530. result.scale(1.0 / Math.PI);
  74531. return result;
  74532. };
  74533. SphericalPolynomial.prototype.scale = function (scale) {
  74534. this.x = this.x.scale(scale);
  74535. this.y = this.y.scale(scale);
  74536. this.z = this.z.scale(scale);
  74537. this.xx = this.xx.scale(scale);
  74538. this.yy = this.yy.scale(scale);
  74539. this.zz = this.zz.scale(scale);
  74540. this.yz = this.yz.scale(scale);
  74541. this.zx = this.zx.scale(scale);
  74542. this.xy = this.xy.scale(scale);
  74543. };
  74544. return SphericalPolynomial;
  74545. }());
  74546. BABYLON.SphericalPolynomial = SphericalPolynomial;
  74547. var SphericalHarmonics = /** @class */ (function () {
  74548. function SphericalHarmonics() {
  74549. this.L00 = BABYLON.Vector3.Zero();
  74550. this.L1_1 = BABYLON.Vector3.Zero();
  74551. this.L10 = BABYLON.Vector3.Zero();
  74552. this.L11 = BABYLON.Vector3.Zero();
  74553. this.L2_2 = BABYLON.Vector3.Zero();
  74554. this.L2_1 = BABYLON.Vector3.Zero();
  74555. this.L20 = BABYLON.Vector3.Zero();
  74556. this.L21 = BABYLON.Vector3.Zero();
  74557. this.L22 = BABYLON.Vector3.Zero();
  74558. }
  74559. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  74560. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74561. var c = colorVector.scale(deltaSolidAngle);
  74562. this.L00 = this.L00.add(c.scale(0.282095));
  74563. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  74564. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  74565. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  74566. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  74567. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  74568. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  74569. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  74570. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  74571. };
  74572. SphericalHarmonics.prototype.scale = function (scale) {
  74573. this.L00 = this.L00.scale(scale);
  74574. this.L1_1 = this.L1_1.scale(scale);
  74575. this.L10 = this.L10.scale(scale);
  74576. this.L11 = this.L11.scale(scale);
  74577. this.L2_2 = this.L2_2.scale(scale);
  74578. this.L2_1 = this.L2_1.scale(scale);
  74579. this.L20 = this.L20.scale(scale);
  74580. this.L21 = this.L21.scale(scale);
  74581. this.L22 = this.L22.scale(scale);
  74582. };
  74583. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  74584. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  74585. //
  74586. // E_lm = A_l * L_lm
  74587. //
  74588. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  74589. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  74590. // the scaling factors are given in equation 9.
  74591. // Constant (Band 0)
  74592. this.L00 = this.L00.scale(3.141593);
  74593. // Linear (Band 1)
  74594. this.L1_1 = this.L1_1.scale(2.094395);
  74595. this.L10 = this.L10.scale(2.094395);
  74596. this.L11 = this.L11.scale(2.094395);
  74597. // Quadratic (Band 2)
  74598. this.L2_2 = this.L2_2.scale(0.785398);
  74599. this.L2_1 = this.L2_1.scale(0.785398);
  74600. this.L20 = this.L20.scale(0.785398);
  74601. this.L21 = this.L21.scale(0.785398);
  74602. this.L22 = this.L22.scale(0.785398);
  74603. };
  74604. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  74605. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  74606. // L = (1/pi) * E * rho
  74607. //
  74608. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  74609. this.scale(1.0 / Math.PI);
  74610. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  74611. // (The pixel shader must apply albedo after texture fetches, etc).
  74612. };
  74613. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  74614. var result = new SphericalHarmonics();
  74615. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  74616. result.L1_1 = polynomial.y.scale(0.977204);
  74617. result.L10 = polynomial.z.scale(0.977204);
  74618. result.L11 = polynomial.x.scale(0.977204);
  74619. result.L2_2 = polynomial.xy.scale(1.16538);
  74620. result.L2_1 = polynomial.yz.scale(1.16538);
  74621. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  74622. result.L21 = polynomial.zx.scale(1.16538);
  74623. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  74624. result.scale(Math.PI);
  74625. return result;
  74626. };
  74627. return SphericalHarmonics;
  74628. }());
  74629. BABYLON.SphericalHarmonics = SphericalHarmonics;
  74630. })(BABYLON || (BABYLON = {}));
  74631. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  74632. "use strict";
  74633. var BABYLON;
  74634. (function (BABYLON) {
  74635. var FileFaceOrientation = /** @class */ (function () {
  74636. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  74637. this.name = name;
  74638. this.worldAxisForNormal = worldAxisForNormal;
  74639. this.worldAxisForFileX = worldAxisForFileX;
  74640. this.worldAxisForFileY = worldAxisForFileY;
  74641. }
  74642. return FileFaceOrientation;
  74643. }());
  74644. ;
  74645. /**
  74646. * Helper class dealing with the extraction of spherical polynomial dataArray
  74647. * from a cube map.
  74648. */
  74649. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  74650. function CubeMapToSphericalPolynomialTools() {
  74651. }
  74652. /**
  74653. * Converts a texture to the according Spherical Polynomial data.
  74654. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74655. *
  74656. * @param texture The texture to extract the information from.
  74657. * @return The Spherical Polynomial data.
  74658. */
  74659. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  74660. if (!texture.isCube) {
  74661. // Only supports cube Textures currently.
  74662. return null;
  74663. }
  74664. var size = texture.getSize().width;
  74665. var right = texture.readPixels(0);
  74666. var left = texture.readPixels(1);
  74667. var up;
  74668. var down;
  74669. if (texture.isRenderTarget) {
  74670. up = texture.readPixels(3);
  74671. down = texture.readPixels(2);
  74672. }
  74673. else {
  74674. up = texture.readPixels(2);
  74675. down = texture.readPixels(3);
  74676. }
  74677. var front = texture.readPixels(4);
  74678. var back = texture.readPixels(5);
  74679. var gammaSpace = texture.gammaSpace;
  74680. // Always read as RGBA.
  74681. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  74682. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74683. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74684. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74685. }
  74686. var cubeInfo = {
  74687. size: size,
  74688. right: right,
  74689. left: left,
  74690. up: up,
  74691. down: down,
  74692. front: front,
  74693. back: back,
  74694. format: format,
  74695. type: type,
  74696. gammaSpace: gammaSpace,
  74697. };
  74698. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  74699. };
  74700. /**
  74701. * Converts a cubemap to the according Spherical Polynomial data.
  74702. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74703. *
  74704. * @param cubeInfo The Cube map to extract the information from.
  74705. * @return The Spherical Polynomial data.
  74706. */
  74707. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  74708. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  74709. var totalSolidAngle = 0.0;
  74710. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  74711. var du = 2.0 / cubeInfo.size;
  74712. var dv = du;
  74713. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  74714. var minUV = du * 0.5 - 1.0;
  74715. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74716. var fileFace = this.FileFaces[faceIndex];
  74717. var dataArray = cubeInfo[fileFace.name];
  74718. var v = minUV;
  74719. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  74720. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  74721. // Because SP is still linear, so summation is fine in that basis.
  74722. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  74723. for (var y = 0; y < cubeInfo.size; y++) {
  74724. var u = minUV;
  74725. for (var x = 0; x < cubeInfo.size; x++) {
  74726. // World direction (not normalised)
  74727. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  74728. worldDirection.normalize();
  74729. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  74730. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  74731. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  74732. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  74733. // Handle Integer types.
  74734. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74735. r /= 255;
  74736. g /= 255;
  74737. b /= 255;
  74738. }
  74739. // Handle Gamma space textures.
  74740. if (cubeInfo.gammaSpace) {
  74741. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  74742. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  74743. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  74744. }
  74745. var color = new BABYLON.Color3(r, g, b);
  74746. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  74747. totalSolidAngle += deltaSolidAngle;
  74748. u += du;
  74749. }
  74750. v += dv;
  74751. }
  74752. }
  74753. // Solid angle for entire sphere is 4*pi
  74754. var sphereSolidAngle = 4.0 * Math.PI;
  74755. // Adjust the solid angle to allow for how many faces we processed.
  74756. var facesProcessed = 6.0;
  74757. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  74758. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  74759. // This is needed because the numerical integration over the cube uses a
  74760. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  74761. // and also to compensate for accumulative error due to float precision in the summation.
  74762. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  74763. sphericalHarmonics.scale(correctionFactor);
  74764. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  74765. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  74766. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  74767. };
  74768. CubeMapToSphericalPolynomialTools.FileFaces = [
  74769. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  74770. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  74771. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  74772. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  74773. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  74774. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  74775. ];
  74776. return CubeMapToSphericalPolynomialTools;
  74777. }());
  74778. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  74779. })(BABYLON || (BABYLON = {}));
  74780. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  74781. "use strict";
  74782. var BABYLON;
  74783. (function (BABYLON) {
  74784. /**
  74785. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  74786. */
  74787. var PanoramaToCubeMapTools = /** @class */ (function () {
  74788. function PanoramaToCubeMapTools() {
  74789. }
  74790. /**
  74791. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  74792. *
  74793. * @param float32Array The source data.
  74794. * @param inputWidth The width of the input panorama.
  74795. * @param inputhHeight The height of the input panorama.
  74796. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  74797. * @return The cubemap data
  74798. */
  74799. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  74800. if (!float32Array) {
  74801. throw "ConvertPanoramaToCubemap: input cannot be null";
  74802. }
  74803. if (float32Array.length != inputWidth * inputHeight * 3) {
  74804. throw "ConvertPanoramaToCubemap: input size is wrong";
  74805. }
  74806. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  74807. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  74808. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  74809. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  74810. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  74811. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  74812. return {
  74813. front: textureFront,
  74814. back: textureBack,
  74815. left: textureLeft,
  74816. right: textureRight,
  74817. up: textureUp,
  74818. down: textureDown,
  74819. size: size,
  74820. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  74821. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  74822. gammaSpace: false,
  74823. };
  74824. };
  74825. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  74826. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  74827. var textureArray = new Float32Array(buffer);
  74828. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  74829. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  74830. var dy = 1 / texSize;
  74831. var fy = 0;
  74832. for (var y = 0; y < texSize; y++) {
  74833. var xv1 = faceData[0];
  74834. var xv2 = faceData[2];
  74835. for (var x = 0; x < texSize; x++) {
  74836. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  74837. v.normalize();
  74838. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  74839. // 3 channels per pixels
  74840. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  74841. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  74842. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  74843. xv1 = xv1.add(rotDX1);
  74844. xv2 = xv2.add(rotDX2);
  74845. }
  74846. fy += dy;
  74847. }
  74848. return textureArray;
  74849. };
  74850. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  74851. var theta = Math.atan2(vDir.z, vDir.x);
  74852. var phi = Math.acos(vDir.y);
  74853. while (theta < -Math.PI)
  74854. theta += 2 * Math.PI;
  74855. while (theta > Math.PI)
  74856. theta -= 2 * Math.PI;
  74857. var dx = theta / Math.PI;
  74858. var dy = phi / Math.PI;
  74859. // recenter.
  74860. dx = dx * 0.5 + 0.5;
  74861. var px = Math.round(dx * inputWidth);
  74862. if (px < 0)
  74863. px = 0;
  74864. else if (px >= inputWidth)
  74865. px = inputWidth - 1;
  74866. var py = Math.round(dy * inputHeight);
  74867. if (py < 0)
  74868. py = 0;
  74869. else if (py >= inputHeight)
  74870. py = inputHeight - 1;
  74871. var inputY = (inputHeight - py - 1);
  74872. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  74873. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  74874. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  74875. return {
  74876. r: r,
  74877. g: g,
  74878. b: b
  74879. };
  74880. };
  74881. PanoramaToCubeMapTools.FACE_FRONT = [
  74882. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74883. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74884. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74885. new BABYLON.Vector3(1.0, 1.0, -1.0)
  74886. ];
  74887. PanoramaToCubeMapTools.FACE_BACK = [
  74888. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74889. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74890. new BABYLON.Vector3(1.0, 1.0, 1.0),
  74891. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  74892. ];
  74893. PanoramaToCubeMapTools.FACE_RIGHT = [
  74894. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74895. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74896. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74897. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74898. ];
  74899. PanoramaToCubeMapTools.FACE_LEFT = [
  74900. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74901. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74902. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74903. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  74904. ];
  74905. PanoramaToCubeMapTools.FACE_DOWN = [
  74906. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74907. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74908. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74909. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74910. ];
  74911. PanoramaToCubeMapTools.FACE_UP = [
  74912. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74913. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74914. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74915. new BABYLON.Vector3(1.0, -1.0, -1.0)
  74916. ];
  74917. return PanoramaToCubeMapTools;
  74918. }());
  74919. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  74920. })(BABYLON || (BABYLON = {}));
  74921. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  74922. "use strict";
  74923. var BABYLON;
  74924. (function (BABYLON) {
  74925. ;
  74926. /**
  74927. * This groups tools to convert HDR texture to native colors array.
  74928. */
  74929. var HDRTools = /** @class */ (function () {
  74930. function HDRTools() {
  74931. }
  74932. HDRTools.Ldexp = function (mantissa, exponent) {
  74933. if (exponent > 1023) {
  74934. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  74935. }
  74936. if (exponent < -1074) {
  74937. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  74938. }
  74939. return mantissa * Math.pow(2, exponent);
  74940. };
  74941. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  74942. if (exponent > 0) {
  74943. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  74944. float32array[index + 0] = red * exponent;
  74945. float32array[index + 1] = green * exponent;
  74946. float32array[index + 2] = blue * exponent;
  74947. }
  74948. else {
  74949. float32array[index + 0] = 0;
  74950. float32array[index + 1] = 0;
  74951. float32array[index + 2] = 0;
  74952. }
  74953. };
  74954. HDRTools.readStringLine = function (uint8array, startIndex) {
  74955. var line = "";
  74956. var character = "";
  74957. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  74958. character = String.fromCharCode(uint8array[i]);
  74959. if (character == "\n") {
  74960. break;
  74961. }
  74962. line += character;
  74963. }
  74964. return line;
  74965. };
  74966. /**
  74967. * Reads header information from an RGBE texture stored in a native array.
  74968. * More information on this format are available here:
  74969. * https://en.wikipedia.org/wiki/RGBE_image_format
  74970. *
  74971. * @param uint8array The binary file stored in native array.
  74972. * @return The header information.
  74973. */
  74974. HDRTools.RGBE_ReadHeader = function (uint8array) {
  74975. var height = 0;
  74976. var width = 0;
  74977. var line = this.readStringLine(uint8array, 0);
  74978. if (line[0] != '#' || line[1] != '?') {
  74979. throw "Bad HDR Format.";
  74980. }
  74981. var endOfHeader = false;
  74982. var findFormat = false;
  74983. var lineIndex = 0;
  74984. do {
  74985. lineIndex += (line.length + 1);
  74986. line = this.readStringLine(uint8array, lineIndex);
  74987. if (line == "FORMAT=32-bit_rle_rgbe") {
  74988. findFormat = true;
  74989. }
  74990. else if (line.length == 0) {
  74991. endOfHeader = true;
  74992. }
  74993. } while (!endOfHeader);
  74994. if (!findFormat) {
  74995. throw "HDR Bad header format, unsupported FORMAT";
  74996. }
  74997. lineIndex += (line.length + 1);
  74998. line = this.readStringLine(uint8array, lineIndex);
  74999. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  75000. var match = sizeRegexp.exec(line);
  75001. // TODO. Support +Y and -X if needed.
  75002. if (!match || match.length < 3) {
  75003. throw "HDR Bad header format, no size";
  75004. }
  75005. width = parseInt(match[2]);
  75006. height = parseInt(match[1]);
  75007. if (width < 8 || width > 0x7fff) {
  75008. throw "HDR Bad header format, unsupported size";
  75009. }
  75010. lineIndex += (line.length + 1);
  75011. return {
  75012. height: height,
  75013. width: width,
  75014. dataPosition: lineIndex
  75015. };
  75016. };
  75017. /**
  75018. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  75019. * This RGBE texture needs to store the information as a panorama.
  75020. *
  75021. * More information on this format are available here:
  75022. * https://en.wikipedia.org/wiki/RGBE_image_format
  75023. *
  75024. * @param buffer The binary file stored in an array buffer.
  75025. * @param size The expected size of the extracted cubemap.
  75026. * @return The Cube Map information.
  75027. */
  75028. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  75029. var uint8array = new Uint8Array(buffer);
  75030. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  75031. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  75032. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  75033. return cubeMapData;
  75034. };
  75035. /**
  75036. * Returns the pixels data extracted from an RGBE texture.
  75037. * This pixels will be stored left to right up to down in the R G B order in one array.
  75038. *
  75039. * More information on this format are available here:
  75040. * https://en.wikipedia.org/wiki/RGBE_image_format
  75041. *
  75042. * @param uint8array The binary file stored in an array buffer.
  75043. * @param hdrInfo The header information of the file.
  75044. * @return The pixels data in RGB right to left up to down order.
  75045. */
  75046. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  75047. // Keep for multi format supports.
  75048. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  75049. };
  75050. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  75051. var num_scanlines = hdrInfo.height;
  75052. var scanline_width = hdrInfo.width;
  75053. var a, b, c, d, count;
  75054. var dataIndex = hdrInfo.dataPosition;
  75055. var index = 0, endIndex = 0, i = 0;
  75056. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  75057. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  75058. // 3 channels of 4 bytes per pixel in float.
  75059. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  75060. var resultArray = new Float32Array(resultBuffer);
  75061. // read in each successive scanline
  75062. while (num_scanlines > 0) {
  75063. a = uint8array[dataIndex++];
  75064. b = uint8array[dataIndex++];
  75065. c = uint8array[dataIndex++];
  75066. d = uint8array[dataIndex++];
  75067. if (a != 2 || b != 2 || (c & 0x80)) {
  75068. // this file is not run length encoded
  75069. throw "HDR Bad header format, not RLE";
  75070. }
  75071. if (((c << 8) | d) != scanline_width) {
  75072. throw "HDR Bad header format, wrong scan line width";
  75073. }
  75074. index = 0;
  75075. // read each of the four channels for the scanline into the buffer
  75076. for (i = 0; i < 4; i++) {
  75077. endIndex = (i + 1) * scanline_width;
  75078. while (index < endIndex) {
  75079. a = uint8array[dataIndex++];
  75080. b = uint8array[dataIndex++];
  75081. if (a > 128) {
  75082. // a run of the same value
  75083. count = a - 128;
  75084. if ((count == 0) || (count > endIndex - index)) {
  75085. throw "HDR Bad Format, bad scanline data (run)";
  75086. }
  75087. while (count-- > 0) {
  75088. scanLineArray[index++] = b;
  75089. }
  75090. }
  75091. else {
  75092. // a non-run
  75093. count = a;
  75094. if ((count == 0) || (count > endIndex - index)) {
  75095. throw "HDR Bad Format, bad scanline data (non-run)";
  75096. }
  75097. scanLineArray[index++] = b;
  75098. if (--count > 0) {
  75099. for (var j = 0; j < count; j++) {
  75100. scanLineArray[index++] = uint8array[dataIndex++];
  75101. }
  75102. }
  75103. }
  75104. }
  75105. }
  75106. // now convert data from buffer into floats
  75107. for (i = 0; i < scanline_width; i++) {
  75108. a = scanLineArray[i];
  75109. b = scanLineArray[i + scanline_width];
  75110. c = scanLineArray[i + 2 * scanline_width];
  75111. d = scanLineArray[i + 3 * scanline_width];
  75112. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  75113. }
  75114. num_scanlines--;
  75115. }
  75116. return resultArray;
  75117. };
  75118. return HDRTools;
  75119. }());
  75120. BABYLON.HDRTools = HDRTools;
  75121. })(BABYLON || (BABYLON = {}));
  75122. //# sourceMappingURL=babylon.hdr.js.map
  75123. "use strict";
  75124. var BABYLON;
  75125. (function (BABYLON) {
  75126. /**
  75127. * This represents a texture coming from an HDR input.
  75128. *
  75129. * The only supported format is currently panorama picture stored in RGBE format.
  75130. * Example of such files can be found on HDRLib: http://hdrlib.com/
  75131. */
  75132. var HDRCubeTexture = /** @class */ (function (_super) {
  75133. __extends(HDRCubeTexture, _super);
  75134. /**
  75135. * Instantiates an HDRTexture from the following parameters.
  75136. *
  75137. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  75138. * @param scene The scene the texture will be used in
  75139. * @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.
  75140. * @param noMipmap Forces to not generate the mipmap if true
  75141. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  75142. * @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)
  75143. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  75144. */
  75145. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  75146. if (noMipmap === void 0) { noMipmap = false; }
  75147. if (generateHarmonics === void 0) { generateHarmonics = true; }
  75148. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  75149. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  75150. if (onLoad === void 0) { onLoad = null; }
  75151. if (onError === void 0) { onError = null; }
  75152. var _this = _super.call(this, scene) || this;
  75153. _this._useInGammaSpace = false;
  75154. _this._generateHarmonics = true;
  75155. _this._isBABYLONPreprocessed = false;
  75156. _this._onLoad = null;
  75157. _this._onError = null;
  75158. /**
  75159. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  75160. */
  75161. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  75162. /**
  75163. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  75164. * This is usefull at run time to apply the good shader.
  75165. */
  75166. _this.isPMREM = false;
  75167. _this._isBlocking = true;
  75168. /**
  75169. * Gets or sets the center of the bounding box associated with the cube texture
  75170. * It must define where the camera used to render the texture was set
  75171. */
  75172. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  75173. if (!url) {
  75174. return _this;
  75175. }
  75176. _this.name = url;
  75177. _this.url = url;
  75178. _this.hasAlpha = false;
  75179. _this.isCube = true;
  75180. _this._textureMatrix = BABYLON.Matrix.Identity();
  75181. _this._onLoad = onLoad;
  75182. _this._onError = onError;
  75183. _this.gammaSpace = false;
  75184. var caps = scene.getEngine().getCaps();
  75185. if (size) {
  75186. _this._isBABYLONPreprocessed = false;
  75187. _this._noMipmap = noMipmap;
  75188. _this._size = size;
  75189. _this._useInGammaSpace = useInGammaSpace;
  75190. _this._usePMREMGenerator = usePMREMGenerator &&
  75191. caps.textureLOD &&
  75192. caps.textureFloat &&
  75193. !_this._useInGammaSpace;
  75194. }
  75195. else {
  75196. _this._isBABYLONPreprocessed = true;
  75197. _this._noMipmap = false;
  75198. _this._useInGammaSpace = false;
  75199. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  75200. !_this._useInGammaSpace;
  75201. }
  75202. _this.isPMREM = _this._usePMREMGenerator;
  75203. _this._texture = _this._getFromCache(url, _this._noMipmap);
  75204. if (!_this._texture) {
  75205. if (!scene.useDelayedTextureLoading) {
  75206. _this.loadTexture();
  75207. }
  75208. else {
  75209. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  75210. }
  75211. }
  75212. return _this;
  75213. }
  75214. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  75215. /**
  75216. * Gets wether or not the texture is blocking during loading.
  75217. */
  75218. get: function () {
  75219. return this._isBlocking;
  75220. },
  75221. /**
  75222. * Sets wether or not the texture is blocking during loading.
  75223. */
  75224. set: function (value) {
  75225. this._isBlocking = value;
  75226. },
  75227. enumerable: true,
  75228. configurable: true
  75229. });
  75230. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  75231. get: function () {
  75232. return this._boundingBoxSize;
  75233. },
  75234. /**
  75235. * Gets or sets the size of the bounding box associated with the cube texture
  75236. * When defined, the cubemap will switch to local mode
  75237. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  75238. * @example https://www.babylonjs-playground.com/#RNASML
  75239. */
  75240. set: function (value) {
  75241. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  75242. return;
  75243. }
  75244. this._boundingBoxSize = value;
  75245. var scene = this.getScene();
  75246. if (scene) {
  75247. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  75248. }
  75249. },
  75250. enumerable: true,
  75251. configurable: true
  75252. });
  75253. /**
  75254. * Occurs when the file is a preprocessed .babylon.hdr file.
  75255. */
  75256. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  75257. var _this = this;
  75258. var mipLevels = 0;
  75259. var floatArrayView = null;
  75260. var scene = this.getScene();
  75261. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  75262. var mips = new Array();
  75263. if (!floatArrayView) {
  75264. return mips;
  75265. }
  75266. var startIndex = 30;
  75267. for (var level = 0; level < mipLevels; level++) {
  75268. mips.push([]);
  75269. // Fill each pixel of the mip level.
  75270. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  75271. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  75272. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  75273. mips[level].push(faceData);
  75274. startIndex += faceSize;
  75275. }
  75276. }
  75277. return mips;
  75278. } : null;
  75279. var callback = function (buffer) {
  75280. var scene = _this.getScene();
  75281. if (!scene) {
  75282. return null;
  75283. }
  75284. // Create Native Array Views
  75285. var intArrayView = new Int32Array(buffer);
  75286. floatArrayView = new Float32Array(buffer);
  75287. // Fill header.
  75288. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  75289. _this._size = intArrayView[1]; // CubeMap max mip face size.
  75290. // Update Texture Information.
  75291. if (!_this._texture) {
  75292. return null;
  75293. }
  75294. _this._texture.updateSize(_this._size, _this._size);
  75295. // Fill polynomial information.
  75296. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  75297. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  75298. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  75299. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  75300. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  75301. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  75302. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  75303. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  75304. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  75305. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  75306. _this.sphericalPolynomial = sphericalPolynomial;
  75307. // Fill pixel data.
  75308. mipLevels = intArrayView[29]; // Number of mip levels.
  75309. var startIndex = 30;
  75310. var data = [];
  75311. var faceSize = Math.pow(_this._size, 2) * 3;
  75312. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  75313. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  75314. startIndex += faceSize;
  75315. }
  75316. var results = [];
  75317. var byteArray = null;
  75318. // Push each faces.
  75319. for (var k = 0; k < 6; k++) {
  75320. var dataFace = null;
  75321. // To be deprecated.
  75322. if (version === 1) {
  75323. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  75324. dataFace = data[j];
  75325. }
  75326. // If special cases.
  75327. if (!mipmapGenerator && dataFace) {
  75328. if (!scene.getEngine().getCaps().textureFloat) {
  75329. // 3 channels of 1 bytes per pixel in bytes.
  75330. var byteBuffer = new ArrayBuffer(faceSize);
  75331. byteArray = new Uint8Array(byteBuffer);
  75332. }
  75333. for (var i = 0; i < _this._size * _this._size; i++) {
  75334. // Put in gamma space if requested.
  75335. if (_this._useInGammaSpace) {
  75336. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75337. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75338. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75339. }
  75340. // Convert to int texture for fallback.
  75341. if (byteArray) {
  75342. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75343. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75344. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75345. // May use luminance instead if the result is not accurate.
  75346. var max = Math.max(Math.max(r, g), b);
  75347. if (max > 255) {
  75348. var scale = 255 / max;
  75349. r *= scale;
  75350. g *= scale;
  75351. b *= scale;
  75352. }
  75353. byteArray[(i * 3) + 0] = r;
  75354. byteArray[(i * 3) + 1] = g;
  75355. byteArray[(i * 3) + 2] = b;
  75356. }
  75357. }
  75358. }
  75359. // Fill the array accordingly.
  75360. if (byteArray) {
  75361. results.push(byteArray);
  75362. }
  75363. else {
  75364. results.push(dataFace);
  75365. }
  75366. }
  75367. return results;
  75368. };
  75369. if (scene) {
  75370. 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);
  75371. }
  75372. };
  75373. /**
  75374. * Occurs when the file is raw .hdr file.
  75375. */
  75376. HDRCubeTexture.prototype.loadHDRTexture = function () {
  75377. var _this = this;
  75378. var callback = function (buffer) {
  75379. var scene = _this.getScene();
  75380. if (!scene) {
  75381. return null;
  75382. }
  75383. // Extract the raw linear data.
  75384. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  75385. // Generate harmonics if needed.
  75386. if (_this._generateHarmonics) {
  75387. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  75388. _this.sphericalPolynomial = sphericalPolynomial;
  75389. }
  75390. var results = [];
  75391. var byteArray = null;
  75392. // Push each faces.
  75393. for (var j = 0; j < 6; j++) {
  75394. // Create uintarray fallback.
  75395. if (!scene.getEngine().getCaps().textureFloat) {
  75396. // 3 channels of 1 bytes per pixel in bytes.
  75397. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  75398. byteArray = new Uint8Array(byteBuffer);
  75399. }
  75400. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  75401. // If special cases.
  75402. if (_this._useInGammaSpace || byteArray) {
  75403. for (var i = 0; i < _this._size * _this._size; i++) {
  75404. // Put in gamma space if requested.
  75405. if (_this._useInGammaSpace) {
  75406. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75407. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75408. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75409. }
  75410. // Convert to int texture for fallback.
  75411. if (byteArray) {
  75412. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75413. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75414. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75415. // May use luminance instead if the result is not accurate.
  75416. var max = Math.max(Math.max(r, g), b);
  75417. if (max > 255) {
  75418. var scale = 255 / max;
  75419. r *= scale;
  75420. g *= scale;
  75421. b *= scale;
  75422. }
  75423. byteArray[(i * 3) + 0] = r;
  75424. byteArray[(i * 3) + 1] = g;
  75425. byteArray[(i * 3) + 2] = b;
  75426. }
  75427. }
  75428. }
  75429. if (byteArray) {
  75430. results.push(byteArray);
  75431. }
  75432. else {
  75433. results.push(dataFace);
  75434. }
  75435. }
  75436. return results;
  75437. };
  75438. var mipmapGenerator = null;
  75439. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  75440. // if (!this._noMipmap &&
  75441. // this._usePMREMGenerator) {
  75442. // mipmapGenerator = (data: ArrayBufferView[]) => {
  75443. // // Custom setup of the generator matching with the PBR shader values.
  75444. // var generator = new BABYLON.PMREMGenerator(data,
  75445. // this._size,
  75446. // this._size,
  75447. // 0,
  75448. // 3,
  75449. // this.getScene().getEngine().getCaps().textureFloat,
  75450. // 2048,
  75451. // 0.25,
  75452. // false,
  75453. // true);
  75454. // return generator.filterCubeMap();
  75455. // };
  75456. // }
  75457. var scene = this.getScene();
  75458. if (scene) {
  75459. 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);
  75460. }
  75461. };
  75462. /**
  75463. * Starts the loading process of the texture.
  75464. */
  75465. HDRCubeTexture.prototype.loadTexture = function () {
  75466. if (this._isBABYLONPreprocessed) {
  75467. this.loadBabylonTexture();
  75468. }
  75469. else {
  75470. this.loadHDRTexture();
  75471. }
  75472. };
  75473. HDRCubeTexture.prototype.clone = function () {
  75474. var scene = this.getScene();
  75475. if (!scene) {
  75476. return this;
  75477. }
  75478. var size = (this._isBABYLONPreprocessed ? null : this._size);
  75479. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  75480. // Base texture
  75481. newTexture.level = this.level;
  75482. newTexture.wrapU = this.wrapU;
  75483. newTexture.wrapV = this.wrapV;
  75484. newTexture.coordinatesIndex = this.coordinatesIndex;
  75485. newTexture.coordinatesMode = this.coordinatesMode;
  75486. return newTexture;
  75487. };
  75488. // Methods
  75489. HDRCubeTexture.prototype.delayLoad = function () {
  75490. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  75491. return;
  75492. }
  75493. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  75494. this._texture = this._getFromCache(this.url, this._noMipmap);
  75495. if (!this._texture) {
  75496. this.loadTexture();
  75497. }
  75498. };
  75499. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  75500. return this._textureMatrix;
  75501. };
  75502. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  75503. this._textureMatrix = value;
  75504. };
  75505. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  75506. var texture = null;
  75507. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  75508. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  75509. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  75510. texture.name = parsedTexture.name;
  75511. texture.hasAlpha = parsedTexture.hasAlpha;
  75512. texture.level = parsedTexture.level;
  75513. texture.coordinatesMode = parsedTexture.coordinatesMode;
  75514. texture.isBlocking = parsedTexture.isBlocking;
  75515. }
  75516. if (texture) {
  75517. if (parsedTexture.boundingBoxPosition) {
  75518. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  75519. }
  75520. if (parsedTexture.boundingBoxSize) {
  75521. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  75522. }
  75523. }
  75524. return texture;
  75525. };
  75526. HDRCubeTexture.prototype.serialize = function () {
  75527. if (!this.name) {
  75528. return null;
  75529. }
  75530. var serializationObject = {};
  75531. serializationObject.name = this.name;
  75532. serializationObject.hasAlpha = this.hasAlpha;
  75533. serializationObject.isCube = true;
  75534. serializationObject.level = this.level;
  75535. serializationObject.size = this._size;
  75536. serializationObject.coordinatesMode = this.coordinatesMode;
  75537. serializationObject.useInGammaSpace = this._useInGammaSpace;
  75538. serializationObject.generateHarmonics = this._generateHarmonics;
  75539. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  75540. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  75541. serializationObject.customType = "BABYLON.HDRCubeTexture";
  75542. serializationObject.noMipmap = this._noMipmap;
  75543. serializationObject.isBlocking = this._isBlocking;
  75544. return serializationObject;
  75545. };
  75546. /**
  75547. * Saves as a file the data contained in the texture in a binary format.
  75548. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75549. * as the spherical used in the lighting.
  75550. * @param url The HDR file url.
  75551. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75552. * @param onError Method called if any error happens during download.
  75553. * @return The packed binary data.
  75554. */
  75555. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  75556. if (onError === void 0) { onError = null; }
  75557. var callback = function (buffer) {
  75558. var data = new Blob([buffer], { type: 'application/octet-stream' });
  75559. // Returns a URL you can use as a href.
  75560. var objUrl = window.URL.createObjectURL(data);
  75561. // Simulates a link to it and click to dowload.
  75562. var a = document.createElement("a");
  75563. document.body.appendChild(a);
  75564. a.style.display = "none";
  75565. a.href = objUrl;
  75566. a.download = "envmap.babylon.hdr";
  75567. a.click();
  75568. };
  75569. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  75570. };
  75571. /**
  75572. * Serializes the data contained in the texture in a binary format.
  75573. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75574. * as the spherical used in the lighting.
  75575. * @param url The HDR file url.
  75576. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75577. * @param onError Method called if any error happens during download.
  75578. * @return The packed binary data.
  75579. */
  75580. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  75581. if (onError === void 0) { onError = null; }
  75582. // Needs the url tho create the texture.
  75583. if (!url) {
  75584. return;
  75585. }
  75586. // Check Power of two size.
  75587. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  75588. return;
  75589. }
  75590. // Coming Back in 3.x.
  75591. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  75592. };
  75593. HDRCubeTexture._facesMapping = [
  75594. "right",
  75595. "left",
  75596. "up",
  75597. "down",
  75598. "front",
  75599. "back"
  75600. ];
  75601. return HDRCubeTexture;
  75602. }(BABYLON.BaseTexture));
  75603. BABYLON.HDRCubeTexture = HDRCubeTexture;
  75604. })(BABYLON || (BABYLON = {}));
  75605. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  75606. "use strict";
  75607. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  75608. // Huge respect for a such great lib.
  75609. // Earcut license:
  75610. // Copyright (c) 2016, Mapbox
  75611. //
  75612. // Permission to use, copy, modify, and/or distribute this software for any purpose
  75613. // with or without fee is hereby granted, provided that the above copyright notice
  75614. // and this permission notice appear in all copies.
  75615. //
  75616. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  75617. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  75618. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  75619. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  75620. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  75621. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  75622. // THIS SOFTWARE.
  75623. var Earcut;
  75624. (function (Earcut) {
  75625. /**
  75626. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  75627. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  75628. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  75629. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  75630. */
  75631. function earcut(data, holeIndices, dim) {
  75632. dim = dim || 2;
  75633. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  75634. if (!outerNode)
  75635. return triangles;
  75636. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  75637. if (hasHoles)
  75638. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  75639. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  75640. if (data.length > 80 * dim) {
  75641. minX = maxX = data[0];
  75642. minY = maxY = data[1];
  75643. for (var i = dim; i < outerLen; i += dim) {
  75644. x = data[i];
  75645. y = data[i + 1];
  75646. if (x < minX)
  75647. minX = x;
  75648. if (y < minY)
  75649. minY = y;
  75650. if (x > maxX)
  75651. maxX = x;
  75652. if (y > maxY)
  75653. maxY = y;
  75654. }
  75655. // minX, minY and size are later used to transform coords into integers for z-order calculation
  75656. size = Math.max(maxX - minX, maxY - minY);
  75657. }
  75658. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  75659. return triangles;
  75660. }
  75661. Earcut.earcut = earcut;
  75662. var Node = /** @class */ (function () {
  75663. function Node(i, x, y) {
  75664. this.i = i;
  75665. this.x = x;
  75666. this.y = y;
  75667. this.prev = null;
  75668. this.next = null;
  75669. this.z = null;
  75670. this.prevZ = null;
  75671. this.nextZ = null;
  75672. this.steiner = false;
  75673. }
  75674. return Node;
  75675. }());
  75676. // create a circular doubly linked list from polygon points in the specified winding order
  75677. function linkedList(data, start, end, dim, clockwise) {
  75678. var i, last = null;
  75679. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  75680. for (i = start; i < end; i += dim)
  75681. last = insertNode(i, data[i], data[i + 1], last);
  75682. }
  75683. else {
  75684. for (i = end - dim; i >= start; i -= dim)
  75685. last = insertNode(i, data[i], data[i + 1], last);
  75686. }
  75687. if (last && equals(last, last.next)) {
  75688. removeNode(last);
  75689. last = last.next;
  75690. }
  75691. return last;
  75692. }
  75693. // eliminate colinear or duplicate points
  75694. function filterPoints(start, end) {
  75695. if (!start)
  75696. return start;
  75697. if (!end)
  75698. end = start;
  75699. var p = start, again;
  75700. do {
  75701. again = false;
  75702. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  75703. removeNode(p);
  75704. p = end = p.prev;
  75705. if (p === p.next)
  75706. return undefined;
  75707. again = true;
  75708. }
  75709. else {
  75710. p = p.next;
  75711. }
  75712. } while (again || p !== end);
  75713. return end;
  75714. }
  75715. // main ear slicing loop which triangulates a polygon (given as a linked list)
  75716. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  75717. if (!ear)
  75718. return;
  75719. // interlink polygon nodes in z-order
  75720. if (!pass && size)
  75721. indexCurve(ear, minX, minY, size);
  75722. var stop = ear, prev, next;
  75723. // iterate through ears, slicing them one by one
  75724. while (ear.prev !== ear.next) {
  75725. prev = ear.prev;
  75726. next = ear.next;
  75727. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  75728. // cut off the triangle
  75729. triangles.push(prev.i / dim);
  75730. triangles.push(ear.i / dim);
  75731. triangles.push(next.i / dim);
  75732. removeNode(ear);
  75733. // skipping the next vertice leads to less sliver triangles
  75734. ear = next.next;
  75735. stop = next.next;
  75736. continue;
  75737. }
  75738. ear = next;
  75739. // if we looped through the whole remaining polygon and can't find any more ears
  75740. if (ear === stop) {
  75741. // try filtering points and slicing again
  75742. if (!pass) {
  75743. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  75744. // if this didn't work, try curing all small self-intersections locally
  75745. }
  75746. else if (pass === 1) {
  75747. ear = cureLocalIntersections(ear, triangles, dim);
  75748. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  75749. // as a last resort, try splitting the remaining polygon into two
  75750. }
  75751. else if (pass === 2) {
  75752. splitEarcut(ear, triangles, dim, minX, minY, size);
  75753. }
  75754. break;
  75755. }
  75756. }
  75757. }
  75758. // check whether a polygon node forms a valid ear with adjacent nodes
  75759. function isEar(ear) {
  75760. var a = ear.prev, b = ear, c = ear.next;
  75761. if (area(a, b, c) >= 0)
  75762. return false; // reflex, can't be an ear
  75763. // now make sure we don't have other points inside the potential ear
  75764. var p = ear.next.next;
  75765. while (p !== ear.prev) {
  75766. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75767. area(p.prev, p, p.next) >= 0)
  75768. return false;
  75769. p = p.next;
  75770. }
  75771. return true;
  75772. }
  75773. function isEarHashed(ear, minX, minY, size) {
  75774. var a = ear.prev, b = ear, c = ear.next;
  75775. if (area(a, b, c) >= 0)
  75776. return false; // reflex, can't be an ear
  75777. // triangle bbox; min & max are calculated like this for speed
  75778. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  75779. // z-order range for the current triangle bbox;
  75780. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  75781. // first look for points inside the triangle in increasing z-order
  75782. var p = ear.nextZ;
  75783. while (p && p.z <= maxZ) {
  75784. if (p !== ear.prev &&
  75785. p !== ear.next &&
  75786. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75787. area(p.prev, p, p.next) >= 0)
  75788. return false;
  75789. p = p.nextZ;
  75790. }
  75791. // then look for points in decreasing z-order
  75792. p = ear.prevZ;
  75793. while (p && p.z >= minZ) {
  75794. if (p !== ear.prev &&
  75795. p !== ear.next &&
  75796. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75797. area(p.prev, p, p.next) >= 0)
  75798. return false;
  75799. p = p.prevZ;
  75800. }
  75801. return true;
  75802. }
  75803. // go through all polygon nodes and cure small local self-intersections
  75804. function cureLocalIntersections(start, triangles, dim) {
  75805. var p = start;
  75806. do {
  75807. var a = p.prev, b = p.next.next;
  75808. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  75809. triangles.push(a.i / dim);
  75810. triangles.push(p.i / dim);
  75811. triangles.push(b.i / dim);
  75812. // remove two nodes involved
  75813. removeNode(p);
  75814. removeNode(p.next);
  75815. p = start = b;
  75816. }
  75817. p = p.next;
  75818. } while (p !== start);
  75819. return p;
  75820. }
  75821. // try splitting polygon into two and triangulate them independently
  75822. function splitEarcut(start, triangles, dim, minX, minY, size) {
  75823. // look for a valid diagonal that divides the polygon into two
  75824. var a = start;
  75825. do {
  75826. var b = a.next.next;
  75827. while (b !== a.prev) {
  75828. if (a.i !== b.i && isValidDiagonal(a, b)) {
  75829. // split the polygon in two by the diagonal
  75830. var c = splitPolygon(a, b);
  75831. // filter colinear points around the cuts
  75832. a = filterPoints(a, a.next);
  75833. c = filterPoints(c, c.next);
  75834. // run earcut on each half
  75835. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  75836. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  75837. return;
  75838. }
  75839. b = b.next;
  75840. }
  75841. a = a.next;
  75842. } while (a !== start);
  75843. }
  75844. // link every hole into the outer loop, producing a single-ring polygon without holes
  75845. function eliminateHoles(data, holeIndices, outerNode, dim) {
  75846. var queue = [], i, len, start, end, list;
  75847. for (i = 0, len = holeIndices.length; i < len; i++) {
  75848. start = holeIndices[i] * dim;
  75849. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75850. list = linkedList(data, start, end, dim, false);
  75851. if (list === list.next)
  75852. list.steiner = true;
  75853. queue.push(getLeftmost(list));
  75854. }
  75855. queue.sort(compareX);
  75856. // process holes from left to right
  75857. for (i = 0; i < queue.length; i++) {
  75858. eliminateHole(queue[i], outerNode);
  75859. outerNode = filterPoints(outerNode, outerNode.next);
  75860. }
  75861. return outerNode;
  75862. }
  75863. function compareX(a, b) {
  75864. return a.x - b.x;
  75865. }
  75866. // find a bridge between vertices that connects hole with an outer ring and and link it
  75867. function eliminateHole(hole, outerNode) {
  75868. outerNode = findHoleBridge(hole, outerNode);
  75869. if (outerNode) {
  75870. var b = splitPolygon(outerNode, hole);
  75871. filterPoints(b, b.next);
  75872. }
  75873. }
  75874. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  75875. function findHoleBridge(hole, outerNode) {
  75876. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  75877. // find a segment intersected by a ray from the hole's leftmost point to the left;
  75878. // segment's endpoint with lesser x will be potential connection point
  75879. do {
  75880. if (hy <= p.y && hy >= p.next.y) {
  75881. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  75882. if (x <= hx && x > qx) {
  75883. qx = x;
  75884. if (x === hx) {
  75885. if (hy === p.y)
  75886. return p;
  75887. if (hy === p.next.y)
  75888. return p.next;
  75889. }
  75890. m = p.x < p.next.x ? p : p.next;
  75891. }
  75892. }
  75893. p = p.next;
  75894. } while (p !== outerNode);
  75895. if (!m)
  75896. return null;
  75897. if (hx === qx)
  75898. return m.prev; // hole touches outer segment; pick lower endpoint
  75899. // look for points inside the triangle of hole point, segment intersection and endpoint;
  75900. // if there are no points found, we have a valid connection;
  75901. // otherwise choose the point of the minimum angle with the ray as connection point
  75902. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  75903. p = m.next;
  75904. while (p !== stop) {
  75905. if (hx >= p.x &&
  75906. p.x >= mx &&
  75907. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  75908. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  75909. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  75910. m = p;
  75911. tanMin = tan;
  75912. }
  75913. }
  75914. p = p.next;
  75915. }
  75916. return m;
  75917. }
  75918. // interlink polygon nodes in z-order
  75919. function indexCurve(start, minX, minY, size) {
  75920. var p = start;
  75921. do {
  75922. if (p.z === null)
  75923. p.z = zOrder(p.x, p.y, minX, minY, size);
  75924. p.prevZ = p.prev;
  75925. p.nextZ = p.next;
  75926. p = p.next;
  75927. } while (p !== start);
  75928. p.prevZ.nextZ = null;
  75929. p.prevZ = null;
  75930. sortLinked(p);
  75931. }
  75932. // Simon Tatham's linked list merge sort algorithm
  75933. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  75934. function sortLinked(list) {
  75935. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  75936. do {
  75937. p = list;
  75938. list = null;
  75939. tail = null;
  75940. numMerges = 0;
  75941. while (p) {
  75942. numMerges++;
  75943. q = p;
  75944. pSize = 0;
  75945. for (i = 0; i < inSize; i++) {
  75946. pSize++;
  75947. q = q.nextZ;
  75948. if (!q)
  75949. break;
  75950. }
  75951. qSize = inSize;
  75952. while (pSize > 0 || (qSize > 0 && q)) {
  75953. if (pSize === 0) {
  75954. e = q;
  75955. q = q.nextZ;
  75956. qSize--;
  75957. }
  75958. else if (qSize === 0 || !q) {
  75959. e = p;
  75960. p = p.nextZ;
  75961. pSize--;
  75962. }
  75963. else if (p.z <= q.z) {
  75964. e = p;
  75965. p = p.nextZ;
  75966. pSize--;
  75967. }
  75968. else {
  75969. e = q;
  75970. q = q.nextZ;
  75971. qSize--;
  75972. }
  75973. if (tail)
  75974. tail.nextZ = e;
  75975. else
  75976. list = e;
  75977. e.prevZ = tail;
  75978. tail = e;
  75979. }
  75980. p = q;
  75981. }
  75982. tail.nextZ = null;
  75983. inSize *= 2;
  75984. } while (numMerges > 1);
  75985. return list;
  75986. }
  75987. // z-order of a point given coords and size of the data bounding box
  75988. function zOrder(x, y, minX, minY, size) {
  75989. // coords are transformed into non-negative 15-bit integer range
  75990. x = 32767 * (x - minX) / size;
  75991. y = 32767 * (y - minY) / size;
  75992. x = (x | (x << 8)) & 0x00FF00FF;
  75993. x = (x | (x << 4)) & 0x0F0F0F0F;
  75994. x = (x | (x << 2)) & 0x33333333;
  75995. x = (x | (x << 1)) & 0x55555555;
  75996. y = (y | (y << 8)) & 0x00FF00FF;
  75997. y = (y | (y << 4)) & 0x0F0F0F0F;
  75998. y = (y | (y << 2)) & 0x33333333;
  75999. y = (y | (y << 1)) & 0x55555555;
  76000. return x | (y << 1);
  76001. }
  76002. // find the leftmost node of a polygon ring
  76003. function getLeftmost(start) {
  76004. var p = start, leftmost = start;
  76005. do {
  76006. if (p.x < leftmost.x)
  76007. leftmost = p;
  76008. p = p.next;
  76009. } while (p !== start);
  76010. return leftmost;
  76011. }
  76012. // check if a point lies within a convex triangle
  76013. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  76014. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  76015. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  76016. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  76017. }
  76018. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  76019. function isValidDiagonal(a, b) {
  76020. return a.next.i !== b.i &&
  76021. a.prev.i !== b.i &&
  76022. !intersectsPolygon(a, b) &&
  76023. locallyInside(a, b) &&
  76024. locallyInside(b, a) &&
  76025. middleInside(a, b);
  76026. }
  76027. // signed area of a triangle
  76028. function area(p, q, r) {
  76029. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  76030. }
  76031. // check if two points are equal
  76032. function equals(p1, p2) {
  76033. return p1.x === p2.x && p1.y === p2.y;
  76034. }
  76035. // check if two segments intersect
  76036. function intersects(p1, q1, p2, q2) {
  76037. if ((equals(p1, q1) && equals(p2, q2)) ||
  76038. (equals(p1, q2) && equals(p2, q1)))
  76039. return true;
  76040. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  76041. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  76042. }
  76043. // check if a polygon diagonal intersects any polygon segments
  76044. function intersectsPolygon(a, b) {
  76045. var p = a;
  76046. do {
  76047. if (p.i !== a.i &&
  76048. p.next.i !== a.i &&
  76049. p.i !== b.i &&
  76050. p.next.i !== b.i &&
  76051. intersects(p, p.next, a, b))
  76052. return true;
  76053. p = p.next;
  76054. } while (p !== a);
  76055. return false;
  76056. }
  76057. // check if a polygon diagonal is locally inside the polygon
  76058. function locallyInside(a, b) {
  76059. return area(a.prev, a, a.next) < 0
  76060. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  76061. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  76062. }
  76063. // check if the middle point of a polygon diagonal is inside the polygon
  76064. function middleInside(a, b) {
  76065. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  76066. do {
  76067. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  76068. inside = !inside;
  76069. p = p.next;
  76070. } while (p !== a);
  76071. return inside;
  76072. }
  76073. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  76074. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  76075. function splitPolygon(a, b) {
  76076. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  76077. a.next = b;
  76078. b.prev = a;
  76079. a2.next = an;
  76080. an.prev = a2;
  76081. b2.next = a2;
  76082. a2.prev = b2;
  76083. bp.next = b2;
  76084. b2.prev = bp;
  76085. return b2;
  76086. }
  76087. // create a node and optionally link it with previous one (in a circular doubly linked list)
  76088. function insertNode(i, x, y, last) {
  76089. var p = new Node(i, x, y);
  76090. if (!last) {
  76091. p.prev = p;
  76092. p.next = p;
  76093. }
  76094. else {
  76095. p.next = last.next;
  76096. p.prev = last;
  76097. last.next.prev = p;
  76098. last.next = p;
  76099. }
  76100. return p;
  76101. }
  76102. function removeNode(p) {
  76103. p.next.prev = p.prev;
  76104. p.prev.next = p.next;
  76105. if (p.prevZ)
  76106. p.prevZ.nextZ = p.nextZ;
  76107. if (p.nextZ)
  76108. p.nextZ.prevZ = p.prevZ;
  76109. }
  76110. /**
  76111. * return a percentage difference between the polygon area and its triangulation area;
  76112. * used to verify correctness of triangulation
  76113. */
  76114. function deviation(data, holeIndices, dim, triangles) {
  76115. var hasHoles = holeIndices && holeIndices.length;
  76116. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  76117. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  76118. if (hasHoles) {
  76119. for (var i = 0, len = holeIndices.length; i < len; i++) {
  76120. var start = holeIndices[i] * dim;
  76121. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  76122. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  76123. }
  76124. }
  76125. var trianglesArea = 0;
  76126. for (i = 0; i < triangles.length; i += 3) {
  76127. var a = triangles[i] * dim;
  76128. var b = triangles[i + 1] * dim;
  76129. var c = triangles[i + 2] * dim;
  76130. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  76131. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  76132. }
  76133. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  76134. }
  76135. Earcut.deviation = deviation;
  76136. ;
  76137. function signedArea(data, start, end, dim) {
  76138. var sum = 0;
  76139. for (var i = start, j = end - dim; i < end; i += dim) {
  76140. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  76141. j = i;
  76142. }
  76143. return sum;
  76144. }
  76145. /**
  76146. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  76147. */
  76148. function flatten(data) {
  76149. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  76150. for (var i = 0; i < data.length; i++) {
  76151. for (var j = 0; j < data[i].length; j++) {
  76152. for (var d = 0; d < dim; d++)
  76153. result.vertices.push(data[i][j][d]);
  76154. }
  76155. if (i > 0) {
  76156. holeIndex += data[i - 1].length;
  76157. result.holes.push(holeIndex);
  76158. }
  76159. }
  76160. return result;
  76161. }
  76162. Earcut.flatten = flatten;
  76163. ;
  76164. })(Earcut || (Earcut = {}));
  76165. //# sourceMappingURL=babylon.earcut.js.map
  76166. "use strict";
  76167. var BABYLON;
  76168. (function (BABYLON) {
  76169. var IndexedVector2 = /** @class */ (function (_super) {
  76170. __extends(IndexedVector2, _super);
  76171. function IndexedVector2(original, index) {
  76172. var _this = _super.call(this, original.x, original.y) || this;
  76173. _this.index = index;
  76174. return _this;
  76175. }
  76176. return IndexedVector2;
  76177. }(BABYLON.Vector2));
  76178. var PolygonPoints = /** @class */ (function () {
  76179. function PolygonPoints() {
  76180. this.elements = new Array();
  76181. }
  76182. PolygonPoints.prototype.add = function (originalPoints) {
  76183. var _this = this;
  76184. var result = new Array();
  76185. originalPoints.forEach(function (point) {
  76186. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  76187. var newPoint = new IndexedVector2(point, _this.elements.length);
  76188. result.push(newPoint);
  76189. _this.elements.push(newPoint);
  76190. }
  76191. });
  76192. return result;
  76193. };
  76194. PolygonPoints.prototype.computeBounds = function () {
  76195. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  76196. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  76197. this.elements.forEach(function (point) {
  76198. // x
  76199. if (point.x < lmin.x) {
  76200. lmin.x = point.x;
  76201. }
  76202. else if (point.x > lmax.x) {
  76203. lmax.x = point.x;
  76204. }
  76205. // y
  76206. if (point.y < lmin.y) {
  76207. lmin.y = point.y;
  76208. }
  76209. else if (point.y > lmax.y) {
  76210. lmax.y = point.y;
  76211. }
  76212. });
  76213. return {
  76214. min: lmin,
  76215. max: lmax,
  76216. width: lmax.x - lmin.x,
  76217. height: lmax.y - lmin.y
  76218. };
  76219. };
  76220. return PolygonPoints;
  76221. }());
  76222. var Polygon = /** @class */ (function () {
  76223. function Polygon() {
  76224. }
  76225. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  76226. return [
  76227. new BABYLON.Vector2(xmin, ymin),
  76228. new BABYLON.Vector2(xmax, ymin),
  76229. new BABYLON.Vector2(xmax, ymax),
  76230. new BABYLON.Vector2(xmin, ymax)
  76231. ];
  76232. };
  76233. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  76234. if (cx === void 0) { cx = 0; }
  76235. if (cy === void 0) { cy = 0; }
  76236. if (numberOfSides === void 0) { numberOfSides = 32; }
  76237. var result = new Array();
  76238. var angle = 0;
  76239. var increment = (Math.PI * 2) / numberOfSides;
  76240. for (var i = 0; i < numberOfSides; i++) {
  76241. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  76242. angle -= increment;
  76243. }
  76244. return result;
  76245. };
  76246. Polygon.Parse = function (input) {
  76247. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  76248. var i, result = [];
  76249. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  76250. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  76251. }
  76252. return result;
  76253. };
  76254. Polygon.StartingAt = function (x, y) {
  76255. return BABYLON.Path2.StartingAt(x, y);
  76256. };
  76257. return Polygon;
  76258. }());
  76259. BABYLON.Polygon = Polygon;
  76260. var PolygonMeshBuilder = /** @class */ (function () {
  76261. function PolygonMeshBuilder(name, contours, scene) {
  76262. this._points = new PolygonPoints();
  76263. this._outlinepoints = new PolygonPoints();
  76264. this._holes = new Array();
  76265. this._epoints = new Array();
  76266. this._eholes = new Array();
  76267. this._name = name;
  76268. this._scene = scene;
  76269. var points;
  76270. if (contours instanceof BABYLON.Path2) {
  76271. points = contours.getPoints();
  76272. }
  76273. else {
  76274. points = contours;
  76275. }
  76276. this._addToepoint(points);
  76277. this._points.add(points);
  76278. this._outlinepoints.add(points);
  76279. }
  76280. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  76281. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  76282. var p = points_1[_i];
  76283. this._epoints.push(p.x, p.y);
  76284. }
  76285. };
  76286. PolygonMeshBuilder.prototype.addHole = function (hole) {
  76287. this._points.add(hole);
  76288. var holepoints = new PolygonPoints();
  76289. holepoints.add(hole);
  76290. this._holes.push(holepoints);
  76291. this._eholes.push(this._epoints.length / 2);
  76292. this._addToepoint(hole);
  76293. return this;
  76294. };
  76295. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  76296. var _this = this;
  76297. if (updatable === void 0) { updatable = false; }
  76298. if (depth === void 0) { depth = 0; }
  76299. var result = new BABYLON.Mesh(this._name, this._scene);
  76300. var normals = new Array();
  76301. var positions = new Array();
  76302. var uvs = new Array();
  76303. var bounds = this._points.computeBounds();
  76304. this._points.elements.forEach(function (p) {
  76305. normals.push(0, 1.0, 0);
  76306. positions.push(p.x, 0, p.y);
  76307. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  76308. });
  76309. var indices = new Array();
  76310. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  76311. for (var i = 0; i < res.length; i++) {
  76312. indices.push(res[i]);
  76313. }
  76314. if (depth > 0) {
  76315. var positionscount = (positions.length / 3); //get the current pointcount
  76316. this._points.elements.forEach(function (p) {
  76317. normals.push(0, -1.0, 0);
  76318. positions.push(p.x, -depth, p.y);
  76319. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  76320. });
  76321. var totalCount = indices.length;
  76322. for (var i = 0; i < totalCount; i += 3) {
  76323. var i0 = indices[i + 0];
  76324. var i1 = indices[i + 1];
  76325. var i2 = indices[i + 2];
  76326. indices.push(i2 + positionscount);
  76327. indices.push(i1 + positionscount);
  76328. indices.push(i0 + positionscount);
  76329. }
  76330. //Add the sides
  76331. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  76332. this._holes.forEach(function (hole) {
  76333. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  76334. });
  76335. }
  76336. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  76337. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  76338. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  76339. result.setIndices(indices);
  76340. return result;
  76341. };
  76342. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  76343. var StartIndex = positions.length / 3;
  76344. var ulength = 0;
  76345. for (var i = 0; i < points.elements.length; i++) {
  76346. var p = points.elements[i];
  76347. var p1;
  76348. if ((i + 1) > points.elements.length - 1) {
  76349. p1 = points.elements[0];
  76350. }
  76351. else {
  76352. p1 = points.elements[i + 1];
  76353. }
  76354. positions.push(p.x, 0, p.y);
  76355. positions.push(p.x, -depth, p.y);
  76356. positions.push(p1.x, 0, p1.y);
  76357. positions.push(p1.x, -depth, p1.y);
  76358. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  76359. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  76360. var v3 = v2.subtract(v1);
  76361. var v4 = new BABYLON.Vector3(0, 1, 0);
  76362. var vn = BABYLON.Vector3.Cross(v3, v4);
  76363. vn = vn.normalize();
  76364. uvs.push(ulength / bounds.width, 0);
  76365. uvs.push(ulength / bounds.width, 1);
  76366. ulength += v3.length();
  76367. uvs.push((ulength / bounds.width), 0);
  76368. uvs.push((ulength / bounds.width), 1);
  76369. if (!flip) {
  76370. normals.push(-vn.x, -vn.y, -vn.z);
  76371. normals.push(-vn.x, -vn.y, -vn.z);
  76372. normals.push(-vn.x, -vn.y, -vn.z);
  76373. normals.push(-vn.x, -vn.y, -vn.z);
  76374. indices.push(StartIndex);
  76375. indices.push(StartIndex + 1);
  76376. indices.push(StartIndex + 2);
  76377. indices.push(StartIndex + 1);
  76378. indices.push(StartIndex + 3);
  76379. indices.push(StartIndex + 2);
  76380. }
  76381. else {
  76382. normals.push(vn.x, vn.y, vn.z);
  76383. normals.push(vn.x, vn.y, vn.z);
  76384. normals.push(vn.x, vn.y, vn.z);
  76385. normals.push(vn.x, vn.y, vn.z);
  76386. indices.push(StartIndex);
  76387. indices.push(StartIndex + 2);
  76388. indices.push(StartIndex + 1);
  76389. indices.push(StartIndex + 1);
  76390. indices.push(StartIndex + 2);
  76391. indices.push(StartIndex + 3);
  76392. }
  76393. StartIndex += 4;
  76394. }
  76395. ;
  76396. };
  76397. return PolygonMeshBuilder;
  76398. }());
  76399. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  76400. })(BABYLON || (BABYLON = {}));
  76401. //# sourceMappingURL=babylon.polygonMesh.js.map
  76402. "use strict";
  76403. var BABYLON;
  76404. (function (BABYLON) {
  76405. // Unique ID when we import meshes from Babylon to CSG
  76406. var currentCSGMeshId = 0;
  76407. // # class Vertex
  76408. // Represents a vertex of a polygon. Use your own vertex class instead of this
  76409. // one to provide additional features like texture coordinates and vertex
  76410. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  76411. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  76412. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  76413. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  76414. // is not used anywhere else.
  76415. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  76416. var Vertex = /** @class */ (function () {
  76417. function Vertex(pos, normal, uv) {
  76418. this.pos = pos;
  76419. this.normal = normal;
  76420. this.uv = uv;
  76421. }
  76422. Vertex.prototype.clone = function () {
  76423. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  76424. };
  76425. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  76426. // orientation of a polygon is flipped.
  76427. Vertex.prototype.flip = function () {
  76428. this.normal = this.normal.scale(-1);
  76429. };
  76430. // Create a new vertex between this vertex and `other` by linearly
  76431. // interpolating all properties using a parameter of `t`. Subclasses should
  76432. // override this to interpolate additional properties.
  76433. Vertex.prototype.interpolate = function (other, t) {
  76434. 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));
  76435. };
  76436. return Vertex;
  76437. }());
  76438. // # class Plane
  76439. // Represents a plane in 3D space.
  76440. var Plane = /** @class */ (function () {
  76441. function Plane(normal, w) {
  76442. this.normal = normal;
  76443. this.w = w;
  76444. }
  76445. Plane.FromPoints = function (a, b, c) {
  76446. var v0 = c.subtract(a);
  76447. var v1 = b.subtract(a);
  76448. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  76449. return null;
  76450. }
  76451. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  76452. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  76453. };
  76454. Plane.prototype.clone = function () {
  76455. return new Plane(this.normal.clone(), this.w);
  76456. };
  76457. Plane.prototype.flip = function () {
  76458. this.normal.scaleInPlace(-1);
  76459. this.w = -this.w;
  76460. };
  76461. // Split `polygon` by this plane if needed, then put the polygon or polygon
  76462. // fragments in the appropriate lists. Coplanar polygons go into either
  76463. // `coplanarFront` or `coplanarBack` depending on their orientation with
  76464. // respect to this plane. Polygons in front or in back of this plane go into
  76465. // either `front` or `back`.
  76466. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  76467. var COPLANAR = 0;
  76468. var FRONT = 1;
  76469. var BACK = 2;
  76470. var SPANNING = 3;
  76471. // Classify each point as well as the entire polygon into one of the above
  76472. // four classes.
  76473. var polygonType = 0;
  76474. var types = [];
  76475. var i;
  76476. var t;
  76477. for (i = 0; i < polygon.vertices.length; i++) {
  76478. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  76479. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  76480. polygonType |= type;
  76481. types.push(type);
  76482. }
  76483. // Put the polygon in the correct list, splitting it when necessary.
  76484. switch (polygonType) {
  76485. case COPLANAR:
  76486. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  76487. break;
  76488. case FRONT:
  76489. front.push(polygon);
  76490. break;
  76491. case BACK:
  76492. back.push(polygon);
  76493. break;
  76494. case SPANNING:
  76495. var f = [], b = [];
  76496. for (i = 0; i < polygon.vertices.length; i++) {
  76497. var j = (i + 1) % polygon.vertices.length;
  76498. var ti = types[i], tj = types[j];
  76499. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  76500. if (ti !== BACK)
  76501. f.push(vi);
  76502. if (ti !== FRONT)
  76503. b.push(ti !== BACK ? vi.clone() : vi);
  76504. if ((ti | tj) === SPANNING) {
  76505. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  76506. var v = vi.interpolate(vj, t);
  76507. f.push(v);
  76508. b.push(v.clone());
  76509. }
  76510. }
  76511. var poly;
  76512. if (f.length >= 3) {
  76513. poly = new Polygon(f, polygon.shared);
  76514. if (poly.plane)
  76515. front.push(poly);
  76516. }
  76517. if (b.length >= 3) {
  76518. poly = new Polygon(b, polygon.shared);
  76519. if (poly.plane)
  76520. back.push(poly);
  76521. }
  76522. break;
  76523. }
  76524. };
  76525. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  76526. // point is on the plane.
  76527. Plane.EPSILON = 1e-5;
  76528. return Plane;
  76529. }());
  76530. // # class Polygon
  76531. // Represents a convex polygon. The vertices used to initialize a polygon must
  76532. // be coplanar and form a convex loop.
  76533. //
  76534. // Each convex polygon has a `shared` property, which is shared between all
  76535. // polygons that are clones of each other or were split from the same polygon.
  76536. // This can be used to define per-polygon properties (such as surface color).
  76537. var Polygon = /** @class */ (function () {
  76538. function Polygon(vertices, shared) {
  76539. this.vertices = vertices;
  76540. this.shared = shared;
  76541. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  76542. }
  76543. Polygon.prototype.clone = function () {
  76544. var vertices = this.vertices.map(function (v) { return v.clone(); });
  76545. return new Polygon(vertices, this.shared);
  76546. };
  76547. Polygon.prototype.flip = function () {
  76548. this.vertices.reverse().map(function (v) { v.flip(); });
  76549. this.plane.flip();
  76550. };
  76551. return Polygon;
  76552. }());
  76553. // # class Node
  76554. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  76555. // by picking a polygon to split along. That polygon (and all other coplanar
  76556. // polygons) are added directly to that node and the other polygons are added to
  76557. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  76558. // no distinction between internal and leaf nodes.
  76559. var Node = /** @class */ (function () {
  76560. function Node(polygons) {
  76561. this.plane = null;
  76562. this.front = null;
  76563. this.back = null;
  76564. this.polygons = new Array();
  76565. if (polygons) {
  76566. this.build(polygons);
  76567. }
  76568. }
  76569. Node.prototype.clone = function () {
  76570. var node = new Node();
  76571. node.plane = this.plane && this.plane.clone();
  76572. node.front = this.front && this.front.clone();
  76573. node.back = this.back && this.back.clone();
  76574. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  76575. return node;
  76576. };
  76577. // Convert solid space to empty space and empty space to solid space.
  76578. Node.prototype.invert = function () {
  76579. for (var i = 0; i < this.polygons.length; i++) {
  76580. this.polygons[i].flip();
  76581. }
  76582. if (this.plane) {
  76583. this.plane.flip();
  76584. }
  76585. if (this.front) {
  76586. this.front.invert();
  76587. }
  76588. if (this.back) {
  76589. this.back.invert();
  76590. }
  76591. var temp = this.front;
  76592. this.front = this.back;
  76593. this.back = temp;
  76594. };
  76595. // Recursively remove all polygons in `polygons` that are inside this BSP
  76596. // tree.
  76597. Node.prototype.clipPolygons = function (polygons) {
  76598. if (!this.plane)
  76599. return polygons.slice();
  76600. var front = new Array(), back = new Array();
  76601. for (var i = 0; i < polygons.length; i++) {
  76602. this.plane.splitPolygon(polygons[i], front, back, front, back);
  76603. }
  76604. if (this.front) {
  76605. front = this.front.clipPolygons(front);
  76606. }
  76607. if (this.back) {
  76608. back = this.back.clipPolygons(back);
  76609. }
  76610. else {
  76611. back = [];
  76612. }
  76613. return front.concat(back);
  76614. };
  76615. // Remove all polygons in this BSP tree that are inside the other BSP tree
  76616. // `bsp`.
  76617. Node.prototype.clipTo = function (bsp) {
  76618. this.polygons = bsp.clipPolygons(this.polygons);
  76619. if (this.front)
  76620. this.front.clipTo(bsp);
  76621. if (this.back)
  76622. this.back.clipTo(bsp);
  76623. };
  76624. // Return a list of all polygons in this BSP tree.
  76625. Node.prototype.allPolygons = function () {
  76626. var polygons = this.polygons.slice();
  76627. if (this.front)
  76628. polygons = polygons.concat(this.front.allPolygons());
  76629. if (this.back)
  76630. polygons = polygons.concat(this.back.allPolygons());
  76631. return polygons;
  76632. };
  76633. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  76634. // new polygons are filtered down to the bottom of the tree and become new
  76635. // nodes there. Each set of polygons is partitioned using the first polygon
  76636. // (no heuristic is used to pick a good split).
  76637. Node.prototype.build = function (polygons) {
  76638. if (!polygons.length)
  76639. return;
  76640. if (!this.plane)
  76641. this.plane = polygons[0].plane.clone();
  76642. var front = new Array(), back = new Array();
  76643. for (var i = 0; i < polygons.length; i++) {
  76644. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  76645. }
  76646. if (front.length) {
  76647. if (!this.front)
  76648. this.front = new Node();
  76649. this.front.build(front);
  76650. }
  76651. if (back.length) {
  76652. if (!this.back)
  76653. this.back = new Node();
  76654. this.back.build(back);
  76655. }
  76656. };
  76657. return Node;
  76658. }());
  76659. var CSG = /** @class */ (function () {
  76660. function CSG() {
  76661. this.polygons = new Array();
  76662. }
  76663. // Convert BABYLON.Mesh to BABYLON.CSG
  76664. CSG.FromMesh = function (mesh) {
  76665. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  76666. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  76667. if (mesh instanceof BABYLON.Mesh) {
  76668. mesh.computeWorldMatrix(true);
  76669. matrix = mesh.getWorldMatrix();
  76670. meshPosition = mesh.position.clone();
  76671. meshRotation = mesh.rotation.clone();
  76672. if (mesh.rotationQuaternion) {
  76673. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  76674. }
  76675. meshScaling = mesh.scaling.clone();
  76676. }
  76677. else {
  76678. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  76679. }
  76680. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  76681. var subMeshes = mesh.subMeshes;
  76682. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  76683. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  76684. vertices = [];
  76685. for (var j = 0; j < 3; j++) {
  76686. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  76687. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  76688. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  76689. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  76690. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  76691. vertex = new Vertex(position, normal, uv);
  76692. vertices.push(vertex);
  76693. }
  76694. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  76695. // To handle the case of degenerated triangle
  76696. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  76697. if (polygon.plane)
  76698. polygons.push(polygon);
  76699. }
  76700. }
  76701. var csg = CSG.FromPolygons(polygons);
  76702. csg.matrix = matrix;
  76703. csg.position = meshPosition;
  76704. csg.rotation = meshRotation;
  76705. csg.scaling = meshScaling;
  76706. csg.rotationQuaternion = meshRotationQuaternion;
  76707. currentCSGMeshId++;
  76708. return csg;
  76709. };
  76710. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  76711. CSG.FromPolygons = function (polygons) {
  76712. var csg = new CSG();
  76713. csg.polygons = polygons;
  76714. return csg;
  76715. };
  76716. CSG.prototype.clone = function () {
  76717. var csg = new CSG();
  76718. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  76719. csg.copyTransformAttributes(this);
  76720. return csg;
  76721. };
  76722. CSG.prototype.union = function (csg) {
  76723. var a = new Node(this.clone().polygons);
  76724. var b = new Node(csg.clone().polygons);
  76725. a.clipTo(b);
  76726. b.clipTo(a);
  76727. b.invert();
  76728. b.clipTo(a);
  76729. b.invert();
  76730. a.build(b.allPolygons());
  76731. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76732. };
  76733. CSG.prototype.unionInPlace = function (csg) {
  76734. var a = new Node(this.polygons);
  76735. var b = new Node(csg.polygons);
  76736. a.clipTo(b);
  76737. b.clipTo(a);
  76738. b.invert();
  76739. b.clipTo(a);
  76740. b.invert();
  76741. a.build(b.allPolygons());
  76742. this.polygons = a.allPolygons();
  76743. };
  76744. CSG.prototype.subtract = function (csg) {
  76745. var a = new Node(this.clone().polygons);
  76746. var b = new Node(csg.clone().polygons);
  76747. a.invert();
  76748. a.clipTo(b);
  76749. b.clipTo(a);
  76750. b.invert();
  76751. b.clipTo(a);
  76752. b.invert();
  76753. a.build(b.allPolygons());
  76754. a.invert();
  76755. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76756. };
  76757. CSG.prototype.subtractInPlace = function (csg) {
  76758. var a = new Node(this.polygons);
  76759. var b = new Node(csg.polygons);
  76760. a.invert();
  76761. a.clipTo(b);
  76762. b.clipTo(a);
  76763. b.invert();
  76764. b.clipTo(a);
  76765. b.invert();
  76766. a.build(b.allPolygons());
  76767. a.invert();
  76768. this.polygons = a.allPolygons();
  76769. };
  76770. CSG.prototype.intersect = function (csg) {
  76771. var a = new Node(this.clone().polygons);
  76772. var b = new Node(csg.clone().polygons);
  76773. a.invert();
  76774. b.clipTo(a);
  76775. b.invert();
  76776. a.clipTo(b);
  76777. b.clipTo(a);
  76778. a.build(b.allPolygons());
  76779. a.invert();
  76780. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76781. };
  76782. CSG.prototype.intersectInPlace = function (csg) {
  76783. var a = new Node(this.polygons);
  76784. var b = new Node(csg.polygons);
  76785. a.invert();
  76786. b.clipTo(a);
  76787. b.invert();
  76788. a.clipTo(b);
  76789. b.clipTo(a);
  76790. a.build(b.allPolygons());
  76791. a.invert();
  76792. this.polygons = a.allPolygons();
  76793. };
  76794. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  76795. // not modified.
  76796. CSG.prototype.inverse = function () {
  76797. var csg = this.clone();
  76798. csg.inverseInPlace();
  76799. return csg;
  76800. };
  76801. CSG.prototype.inverseInPlace = function () {
  76802. this.polygons.map(function (p) { p.flip(); });
  76803. };
  76804. // This is used to keep meshes transformations so they can be restored
  76805. // when we build back a Babylon Mesh
  76806. // NB : All CSG operations are performed in world coordinates
  76807. CSG.prototype.copyTransformAttributes = function (csg) {
  76808. this.matrix = csg.matrix;
  76809. this.position = csg.position;
  76810. this.rotation = csg.rotation;
  76811. this.scaling = csg.scaling;
  76812. this.rotationQuaternion = csg.rotationQuaternion;
  76813. return this;
  76814. };
  76815. // Build Raw mesh from CSG
  76816. // Coordinates here are in world space
  76817. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  76818. var matrix = this.matrix.clone();
  76819. matrix.invert();
  76820. 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;
  76821. if (keepSubMeshes) {
  76822. // Sort Polygons, since subMeshes are indices range
  76823. polygons.sort(function (a, b) {
  76824. if (a.shared.meshId === b.shared.meshId) {
  76825. return a.shared.subMeshId - b.shared.subMeshId;
  76826. }
  76827. else {
  76828. return a.shared.meshId - b.shared.meshId;
  76829. }
  76830. });
  76831. }
  76832. for (var i = 0, il = polygons.length; i < il; i++) {
  76833. polygon = polygons[i];
  76834. // Building SubMeshes
  76835. if (!subMesh_dict[polygon.shared.meshId]) {
  76836. subMesh_dict[polygon.shared.meshId] = {};
  76837. }
  76838. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  76839. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  76840. indexStart: +Infinity,
  76841. indexEnd: -Infinity,
  76842. materialIndex: polygon.shared.materialIndex
  76843. };
  76844. }
  76845. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  76846. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  76847. polygonIndices[0] = 0;
  76848. polygonIndices[1] = j - 1;
  76849. polygonIndices[2] = j;
  76850. for (var k = 0; k < 3; k++) {
  76851. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  76852. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  76853. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  76854. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  76855. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  76856. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  76857. // Check if 2 points can be merged
  76858. if (!(typeof vertex_idx !== 'undefined' &&
  76859. normals[vertex_idx * 3] === localNormal.x &&
  76860. normals[vertex_idx * 3 + 1] === localNormal.y &&
  76861. normals[vertex_idx * 3 + 2] === localNormal.z &&
  76862. uvs[vertex_idx * 2] === uv.x &&
  76863. uvs[vertex_idx * 2 + 1] === uv.y)) {
  76864. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  76865. uvs.push(uv.x, uv.y);
  76866. normals.push(normal.x, normal.y, normal.z);
  76867. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  76868. }
  76869. indices.push(vertex_idx);
  76870. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  76871. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  76872. currentIndex++;
  76873. }
  76874. }
  76875. }
  76876. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  76877. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  76878. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  76879. mesh.setIndices(indices, null);
  76880. if (keepSubMeshes) {
  76881. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  76882. var materialIndexOffset = 0, materialMaxIndex;
  76883. mesh.subMeshes = new Array();
  76884. for (var m in subMesh_dict) {
  76885. materialMaxIndex = -1;
  76886. for (var sm in subMesh_dict[m]) {
  76887. subMesh_obj = subMesh_dict[m][sm];
  76888. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  76889. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  76890. }
  76891. materialIndexOffset += ++materialMaxIndex;
  76892. }
  76893. }
  76894. return mesh;
  76895. };
  76896. // Build Mesh from CSG taking material and transforms into account
  76897. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  76898. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  76899. mesh.material = material;
  76900. mesh.position.copyFrom(this.position);
  76901. mesh.rotation.copyFrom(this.rotation);
  76902. if (this.rotationQuaternion) {
  76903. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  76904. }
  76905. mesh.scaling.copyFrom(this.scaling);
  76906. mesh.computeWorldMatrix(true);
  76907. return mesh;
  76908. };
  76909. return CSG;
  76910. }());
  76911. BABYLON.CSG = CSG;
  76912. })(BABYLON || (BABYLON = {}));
  76913. //# sourceMappingURL=babylon.csg.js.map
  76914. "use strict";
  76915. var BABYLON;
  76916. (function (BABYLON) {
  76917. var LensFlare = /** @class */ (function () {
  76918. function LensFlare(size, position, color, imgUrl, system) {
  76919. this.size = size;
  76920. this.position = position;
  76921. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  76922. this.color = color || new BABYLON.Color3(1, 1, 1);
  76923. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  76924. this._system = system;
  76925. system.lensFlares.push(this);
  76926. }
  76927. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  76928. return new LensFlare(size, position, color, imgUrl, system);
  76929. };
  76930. LensFlare.prototype.dispose = function () {
  76931. if (this.texture) {
  76932. this.texture.dispose();
  76933. }
  76934. // Remove from scene
  76935. var index = this._system.lensFlares.indexOf(this);
  76936. this._system.lensFlares.splice(index, 1);
  76937. };
  76938. ;
  76939. return LensFlare;
  76940. }());
  76941. BABYLON.LensFlare = LensFlare;
  76942. })(BABYLON || (BABYLON = {}));
  76943. //# sourceMappingURL=babylon.lensFlare.js.map
  76944. "use strict";
  76945. var BABYLON;
  76946. (function (BABYLON) {
  76947. var LensFlareSystem = /** @class */ (function () {
  76948. function LensFlareSystem(name, emitter, scene) {
  76949. this.name = name;
  76950. this.lensFlares = new Array();
  76951. this.borderLimit = 300;
  76952. this.viewportBorder = 0;
  76953. this.layerMask = 0x0FFFFFFF;
  76954. this._vertexBuffers = {};
  76955. this._isEnabled = true;
  76956. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76957. this._emitter = emitter;
  76958. this.id = name;
  76959. scene.lensFlareSystems.push(this);
  76960. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  76961. var engine = scene.getEngine();
  76962. // VBO
  76963. var vertices = [];
  76964. vertices.push(1, 1);
  76965. vertices.push(-1, 1);
  76966. vertices.push(-1, -1);
  76967. vertices.push(1, -1);
  76968. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76969. // Indices
  76970. var indices = [];
  76971. indices.push(0);
  76972. indices.push(1);
  76973. indices.push(2);
  76974. indices.push(0);
  76975. indices.push(2);
  76976. indices.push(3);
  76977. this._indexBuffer = engine.createIndexBuffer(indices);
  76978. // Effects
  76979. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  76980. }
  76981. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  76982. get: function () {
  76983. return this._isEnabled;
  76984. },
  76985. set: function (value) {
  76986. this._isEnabled = value;
  76987. },
  76988. enumerable: true,
  76989. configurable: true
  76990. });
  76991. LensFlareSystem.prototype.getScene = function () {
  76992. return this._scene;
  76993. };
  76994. LensFlareSystem.prototype.getEmitter = function () {
  76995. return this._emitter;
  76996. };
  76997. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  76998. this._emitter = newEmitter;
  76999. };
  77000. LensFlareSystem.prototype.getEmitterPosition = function () {
  77001. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  77002. };
  77003. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  77004. var position = this.getEmitterPosition();
  77005. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  77006. this._positionX = position.x;
  77007. this._positionY = position.y;
  77008. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  77009. if (this.viewportBorder > 0) {
  77010. globalViewport.x -= this.viewportBorder;
  77011. globalViewport.y -= this.viewportBorder;
  77012. globalViewport.width += this.viewportBorder * 2;
  77013. globalViewport.height += this.viewportBorder * 2;
  77014. position.x += this.viewportBorder;
  77015. position.y += this.viewportBorder;
  77016. this._positionX += this.viewportBorder;
  77017. this._positionY += this.viewportBorder;
  77018. }
  77019. if (position.z > 0) {
  77020. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  77021. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  77022. return true;
  77023. }
  77024. return true;
  77025. }
  77026. return false;
  77027. };
  77028. LensFlareSystem.prototype._isVisible = function () {
  77029. if (!this._isEnabled || !this._scene.activeCamera) {
  77030. return false;
  77031. }
  77032. var emitterPosition = this.getEmitterPosition();
  77033. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  77034. var distance = direction.length();
  77035. direction.normalize();
  77036. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  77037. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  77038. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  77039. };
  77040. LensFlareSystem.prototype.render = function () {
  77041. if (!this._effect.isReady() || !this._scene.activeCamera)
  77042. return false;
  77043. var engine = this._scene.getEngine();
  77044. var viewport = this._scene.activeCamera.viewport;
  77045. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  77046. // Position
  77047. if (!this.computeEffectivePosition(globalViewport)) {
  77048. return false;
  77049. }
  77050. // Visibility
  77051. if (!this._isVisible()) {
  77052. return false;
  77053. }
  77054. // Intensity
  77055. var awayX;
  77056. var awayY;
  77057. if (this._positionX < this.borderLimit + globalViewport.x) {
  77058. awayX = this.borderLimit + globalViewport.x - this._positionX;
  77059. }
  77060. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  77061. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  77062. }
  77063. else {
  77064. awayX = 0;
  77065. }
  77066. if (this._positionY < this.borderLimit + globalViewport.y) {
  77067. awayY = this.borderLimit + globalViewport.y - this._positionY;
  77068. }
  77069. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  77070. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  77071. }
  77072. else {
  77073. awayY = 0;
  77074. }
  77075. var away = (awayX > awayY) ? awayX : awayY;
  77076. away -= this.viewportBorder;
  77077. if (away > this.borderLimit) {
  77078. away = this.borderLimit;
  77079. }
  77080. var intensity = 1.0 - (away / this.borderLimit);
  77081. if (intensity < 0) {
  77082. return false;
  77083. }
  77084. if (intensity > 1.0) {
  77085. intensity = 1.0;
  77086. }
  77087. if (this.viewportBorder > 0) {
  77088. globalViewport.x += this.viewportBorder;
  77089. globalViewport.y += this.viewportBorder;
  77090. globalViewport.width -= this.viewportBorder * 2;
  77091. globalViewport.height -= this.viewportBorder * 2;
  77092. this._positionX -= this.viewportBorder;
  77093. this._positionY -= this.viewportBorder;
  77094. }
  77095. // Position
  77096. var centerX = globalViewport.x + globalViewport.width / 2;
  77097. var centerY = globalViewport.y + globalViewport.height / 2;
  77098. var distX = centerX - this._positionX;
  77099. var distY = centerY - this._positionY;
  77100. // Effects
  77101. engine.enableEffect(this._effect);
  77102. engine.setState(false);
  77103. engine.setDepthBuffer(false);
  77104. // VBOs
  77105. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  77106. // Flares
  77107. for (var index = 0; index < this.lensFlares.length; index++) {
  77108. var flare = this.lensFlares[index];
  77109. engine.setAlphaMode(flare.alphaMode);
  77110. var x = centerX - (distX * flare.position);
  77111. var y = centerY - (distY * flare.position);
  77112. var cw = flare.size;
  77113. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  77114. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  77115. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  77116. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  77117. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  77118. // Texture
  77119. this._effect.setTexture("textureSampler", flare.texture);
  77120. // Color
  77121. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  77122. // Draw order
  77123. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77124. }
  77125. engine.setDepthBuffer(true);
  77126. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77127. return true;
  77128. };
  77129. LensFlareSystem.prototype.dispose = function () {
  77130. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77131. if (vertexBuffer) {
  77132. vertexBuffer.dispose();
  77133. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77134. }
  77135. if (this._indexBuffer) {
  77136. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77137. this._indexBuffer = null;
  77138. }
  77139. while (this.lensFlares.length) {
  77140. this.lensFlares[0].dispose();
  77141. }
  77142. // Remove from scene
  77143. var index = this._scene.lensFlareSystems.indexOf(this);
  77144. this._scene.lensFlareSystems.splice(index, 1);
  77145. };
  77146. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  77147. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  77148. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  77149. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  77150. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  77151. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  77152. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  77153. var parsedFlare = parsedLensFlareSystem.flares[index];
  77154. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  77155. }
  77156. return lensFlareSystem;
  77157. };
  77158. LensFlareSystem.prototype.serialize = function () {
  77159. var serializationObject = {};
  77160. serializationObject.id = this.id;
  77161. serializationObject.name = this.name;
  77162. serializationObject.emitterId = this.getEmitter().id;
  77163. serializationObject.borderLimit = this.borderLimit;
  77164. serializationObject.flares = [];
  77165. for (var index = 0; index < this.lensFlares.length; index++) {
  77166. var flare = this.lensFlares[index];
  77167. serializationObject.flares.push({
  77168. size: flare.size,
  77169. position: flare.position,
  77170. color: flare.color.asArray(),
  77171. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  77172. });
  77173. }
  77174. return serializationObject;
  77175. };
  77176. return LensFlareSystem;
  77177. }());
  77178. BABYLON.LensFlareSystem = LensFlareSystem;
  77179. })(BABYLON || (BABYLON = {}));
  77180. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  77181. "use strict";
  77182. var BABYLON;
  77183. (function (BABYLON) {
  77184. /**
  77185. * This is a holder class for the physics joint created by the physics plugin.
  77186. * It holds a set of functions to control the underlying joint.
  77187. */
  77188. var PhysicsJoint = /** @class */ (function () {
  77189. function PhysicsJoint(type, jointData) {
  77190. this.type = type;
  77191. this.jointData = jointData;
  77192. jointData.nativeParams = jointData.nativeParams || {};
  77193. }
  77194. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  77195. get: function () {
  77196. return this._physicsJoint;
  77197. },
  77198. set: function (newJoint) {
  77199. if (this._physicsJoint) {
  77200. //remove from the wolrd
  77201. }
  77202. this._physicsJoint = newJoint;
  77203. },
  77204. enumerable: true,
  77205. configurable: true
  77206. });
  77207. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  77208. set: function (physicsPlugin) {
  77209. this._physicsPlugin = physicsPlugin;
  77210. },
  77211. enumerable: true,
  77212. configurable: true
  77213. });
  77214. /**
  77215. * Execute a function that is physics-plugin specific.
  77216. * @param {Function} func the function that will be executed.
  77217. * It accepts two parameters: the physics world and the physics joint.
  77218. */
  77219. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  77220. func(this._physicsPlugin.world, this._physicsJoint);
  77221. };
  77222. //TODO check if the native joints are the same
  77223. //Joint Types
  77224. PhysicsJoint.DistanceJoint = 0;
  77225. PhysicsJoint.HingeJoint = 1;
  77226. PhysicsJoint.BallAndSocketJoint = 2;
  77227. PhysicsJoint.WheelJoint = 3;
  77228. PhysicsJoint.SliderJoint = 4;
  77229. //OIMO
  77230. PhysicsJoint.PrismaticJoint = 5;
  77231. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  77232. PhysicsJoint.UniversalJoint = 6;
  77233. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  77234. //Cannon
  77235. //Similar to a Ball-Joint. Different in params
  77236. PhysicsJoint.PointToPointJoint = 8;
  77237. //Cannon only at the moment
  77238. PhysicsJoint.SpringJoint = 9;
  77239. PhysicsJoint.LockJoint = 10;
  77240. return PhysicsJoint;
  77241. }());
  77242. BABYLON.PhysicsJoint = PhysicsJoint;
  77243. /**
  77244. * A class representing a physics distance joint.
  77245. */
  77246. var DistanceJoint = /** @class */ (function (_super) {
  77247. __extends(DistanceJoint, _super);
  77248. function DistanceJoint(jointData) {
  77249. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  77250. }
  77251. /**
  77252. * Update the predefined distance.
  77253. */
  77254. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  77255. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  77256. };
  77257. return DistanceJoint;
  77258. }(PhysicsJoint));
  77259. BABYLON.DistanceJoint = DistanceJoint;
  77260. var MotorEnabledJoint = /** @class */ (function (_super) {
  77261. __extends(MotorEnabledJoint, _super);
  77262. function MotorEnabledJoint(type, jointData) {
  77263. return _super.call(this, type, jointData) || this;
  77264. }
  77265. /**
  77266. * Set the motor values.
  77267. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77268. * @param {number} force the force to apply
  77269. * @param {number} maxForce max force for this motor.
  77270. */
  77271. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  77272. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  77273. };
  77274. /**
  77275. * Set the motor's limits.
  77276. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77277. */
  77278. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  77279. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  77280. };
  77281. return MotorEnabledJoint;
  77282. }(PhysicsJoint));
  77283. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  77284. /**
  77285. * This class represents a single hinge physics joint
  77286. */
  77287. var HingeJoint = /** @class */ (function (_super) {
  77288. __extends(HingeJoint, _super);
  77289. function HingeJoint(jointData) {
  77290. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  77291. }
  77292. /**
  77293. * Set the motor values.
  77294. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77295. * @param {number} force the force to apply
  77296. * @param {number} maxForce max force for this motor.
  77297. */
  77298. HingeJoint.prototype.setMotor = function (force, maxForce) {
  77299. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  77300. };
  77301. /**
  77302. * Set the motor's limits.
  77303. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77304. */
  77305. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  77306. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  77307. };
  77308. return HingeJoint;
  77309. }(MotorEnabledJoint));
  77310. BABYLON.HingeJoint = HingeJoint;
  77311. /**
  77312. * This class represents a dual hinge physics joint (same as wheel joint)
  77313. */
  77314. var Hinge2Joint = /** @class */ (function (_super) {
  77315. __extends(Hinge2Joint, _super);
  77316. function Hinge2Joint(jointData) {
  77317. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  77318. }
  77319. /**
  77320. * Set the motor values.
  77321. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77322. * @param {number} force the force to apply
  77323. * @param {number} maxForce max force for this motor.
  77324. * @param {motorIndex} the motor's index, 0 or 1.
  77325. */
  77326. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  77327. if (motorIndex === void 0) { motorIndex = 0; }
  77328. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  77329. };
  77330. /**
  77331. * Set the motor limits.
  77332. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77333. * @param {number} upperLimit the upper limit
  77334. * @param {number} lowerLimit lower limit
  77335. * @param {motorIndex} the motor's index, 0 or 1.
  77336. */
  77337. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  77338. if (motorIndex === void 0) { motorIndex = 0; }
  77339. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  77340. };
  77341. return Hinge2Joint;
  77342. }(MotorEnabledJoint));
  77343. BABYLON.Hinge2Joint = Hinge2Joint;
  77344. })(BABYLON || (BABYLON = {}));
  77345. //# sourceMappingURL=babylon.physicsJoint.js.map
  77346. "use strict";
  77347. var BABYLON;
  77348. (function (BABYLON) {
  77349. var PhysicsImpostor = /** @class */ (function () {
  77350. function PhysicsImpostor(object, type, _options, _scene) {
  77351. if (_options === void 0) { _options = { mass: 0 }; }
  77352. var _this = this;
  77353. this.object = object;
  77354. this.type = type;
  77355. this._options = _options;
  77356. this._scene = _scene;
  77357. this._bodyUpdateRequired = false;
  77358. this._onBeforePhysicsStepCallbacks = new Array();
  77359. this._onAfterPhysicsStepCallbacks = new Array();
  77360. this._onPhysicsCollideCallbacks = [];
  77361. this._deltaPosition = BABYLON.Vector3.Zero();
  77362. this._isDisposed = false;
  77363. //temp variables for parent rotation calculations
  77364. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  77365. this._tmpQuat = new BABYLON.Quaternion();
  77366. this._tmpQuat2 = new BABYLON.Quaternion();
  77367. /**
  77368. * this function is executed by the physics engine.
  77369. */
  77370. this.beforeStep = function () {
  77371. if (!_this._physicsEngine) {
  77372. return;
  77373. }
  77374. _this.object.translate(_this._deltaPosition, -1);
  77375. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  77376. _this.object.computeWorldMatrix(false);
  77377. if (_this.object.parent && _this.object.rotationQuaternion) {
  77378. _this.getParentsRotation();
  77379. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  77380. }
  77381. else {
  77382. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  77383. }
  77384. if (!_this._options.disableBidirectionalTransformation) {
  77385. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  77386. }
  77387. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  77388. func(_this);
  77389. });
  77390. };
  77391. /**
  77392. * this function is executed by the physics engine.
  77393. */
  77394. this.afterStep = function () {
  77395. if (!_this._physicsEngine) {
  77396. return;
  77397. }
  77398. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  77399. func(_this);
  77400. });
  77401. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  77402. // object has now its world rotation. needs to be converted to local.
  77403. if (_this.object.parent && _this.object.rotationQuaternion) {
  77404. _this.getParentsRotation();
  77405. _this._tmpQuat.conjugateInPlace();
  77406. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  77407. }
  77408. // take the position set and make it the absolute position of this object.
  77409. _this.object.setAbsolutePosition(_this.object.position);
  77410. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  77411. _this.object.translate(_this._deltaPosition, 1);
  77412. };
  77413. /**
  77414. * Legacy collision detection event support
  77415. */
  77416. this.onCollideEvent = null;
  77417. //event and body object due to cannon's event-based architecture.
  77418. this.onCollide = function (e) {
  77419. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  77420. return;
  77421. }
  77422. if (!_this._physicsEngine) {
  77423. return;
  77424. }
  77425. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  77426. if (otherImpostor) {
  77427. // Legacy collision detection event support
  77428. if (_this.onCollideEvent) {
  77429. _this.onCollideEvent(_this, otherImpostor);
  77430. }
  77431. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  77432. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  77433. }).forEach(function (obj) {
  77434. obj.callback(_this, otherImpostor);
  77435. });
  77436. }
  77437. };
  77438. //sanity check!
  77439. if (!this.object) {
  77440. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  77441. return;
  77442. }
  77443. //legacy support for old syntax.
  77444. if (!this._scene && object.getScene) {
  77445. this._scene = object.getScene();
  77446. }
  77447. if (!this._scene) {
  77448. return;
  77449. }
  77450. this._physicsEngine = this._scene.getPhysicsEngine();
  77451. if (!this._physicsEngine) {
  77452. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  77453. }
  77454. else {
  77455. //set the object's quaternion, if not set
  77456. if (!this.object.rotationQuaternion) {
  77457. if (this.object.rotation) {
  77458. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  77459. }
  77460. else {
  77461. this.object.rotationQuaternion = new BABYLON.Quaternion();
  77462. }
  77463. }
  77464. //default options params
  77465. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  77466. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  77467. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  77468. this._joints = [];
  77469. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  77470. if (!this.object.parent || this._options.ignoreParent) {
  77471. this._init();
  77472. }
  77473. else if (this.object.parent.physicsImpostor) {
  77474. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  77475. }
  77476. }
  77477. }
  77478. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  77479. get: function () {
  77480. return this._isDisposed;
  77481. },
  77482. enumerable: true,
  77483. configurable: true
  77484. });
  77485. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  77486. get: function () {
  77487. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  77488. },
  77489. set: function (value) {
  77490. this.setMass(value);
  77491. },
  77492. enumerable: true,
  77493. configurable: true
  77494. });
  77495. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  77496. get: function () {
  77497. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  77498. },
  77499. set: function (value) {
  77500. if (!this._physicsEngine) {
  77501. return;
  77502. }
  77503. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  77504. },
  77505. enumerable: true,
  77506. configurable: true
  77507. });
  77508. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  77509. get: function () {
  77510. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  77511. },
  77512. set: function (value) {
  77513. if (!this._physicsEngine) {
  77514. return;
  77515. }
  77516. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  77517. },
  77518. enumerable: true,
  77519. configurable: true
  77520. });
  77521. /**
  77522. * This function will completly initialize this impostor.
  77523. * It will create a new body - but only if this mesh has no parent.
  77524. * If it has, this impostor will not be used other than to define the impostor
  77525. * of the child mesh.
  77526. */
  77527. PhysicsImpostor.prototype._init = function () {
  77528. if (!this._physicsEngine) {
  77529. return;
  77530. }
  77531. this._physicsEngine.removeImpostor(this);
  77532. this.physicsBody = null;
  77533. this._parent = this._parent || this._getPhysicsParent();
  77534. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  77535. this._physicsEngine.addImpostor(this);
  77536. }
  77537. };
  77538. PhysicsImpostor.prototype._getPhysicsParent = function () {
  77539. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  77540. var parentMesh = this.object.parent;
  77541. return parentMesh.physicsImpostor;
  77542. }
  77543. return null;
  77544. };
  77545. /**
  77546. * Should a new body be generated.
  77547. */
  77548. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  77549. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  77550. };
  77551. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  77552. this.forceUpdate();
  77553. };
  77554. /**
  77555. * Force a regeneration of this or the parent's impostor's body.
  77556. * Use under cautious - This will remove all joints already implemented.
  77557. */
  77558. PhysicsImpostor.prototype.forceUpdate = function () {
  77559. this._init();
  77560. if (this.parent && !this._options.ignoreParent) {
  77561. this.parent.forceUpdate();
  77562. }
  77563. };
  77564. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  77565. /*public get mesh(): AbstractMesh {
  77566. return this._mesh;
  77567. }*/
  77568. /**
  77569. * Gets the body that holds this impostor. Either its own, or its parent.
  77570. */
  77571. get: function () {
  77572. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  77573. },
  77574. /**
  77575. * Set the physics body. Used mainly by the physics engine/plugin
  77576. */
  77577. set: function (physicsBody) {
  77578. if (this._physicsBody && this._physicsEngine) {
  77579. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  77580. }
  77581. this._physicsBody = physicsBody;
  77582. this.resetUpdateFlags();
  77583. },
  77584. enumerable: true,
  77585. configurable: true
  77586. });
  77587. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  77588. get: function () {
  77589. return !this._options.ignoreParent && this._parent ? this._parent : null;
  77590. },
  77591. set: function (value) {
  77592. this._parent = value;
  77593. },
  77594. enumerable: true,
  77595. configurable: true
  77596. });
  77597. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  77598. this._bodyUpdateRequired = false;
  77599. };
  77600. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  77601. if (this.object.getBoundingInfo) {
  77602. var q = this.object.rotationQuaternion;
  77603. //reset rotation
  77604. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  77605. //calculate the world matrix with no rotation
  77606. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77607. var boundingInfo = this.object.getBoundingInfo();
  77608. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  77609. //bring back the rotation
  77610. this.object.rotationQuaternion = q;
  77611. //calculate the world matrix with the new rotation
  77612. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77613. return size;
  77614. }
  77615. else {
  77616. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  77617. }
  77618. };
  77619. PhysicsImpostor.prototype.getObjectCenter = function () {
  77620. if (this.object.getBoundingInfo) {
  77621. var boundingInfo = this.object.getBoundingInfo();
  77622. return boundingInfo.boundingBox.centerWorld;
  77623. }
  77624. else {
  77625. return this.object.position;
  77626. }
  77627. };
  77628. /**
  77629. * Get a specific parametes from the options parameter.
  77630. */
  77631. PhysicsImpostor.prototype.getParam = function (paramName) {
  77632. return this._options[paramName];
  77633. };
  77634. /**
  77635. * Sets a specific parameter in the options given to the physics plugin
  77636. */
  77637. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  77638. this._options[paramName] = value;
  77639. this._bodyUpdateRequired = true;
  77640. };
  77641. /**
  77642. * Specifically change the body's mass option. Won't recreate the physics body object
  77643. */
  77644. PhysicsImpostor.prototype.setMass = function (mass) {
  77645. if (this.getParam("mass") !== mass) {
  77646. this.setParam("mass", mass);
  77647. }
  77648. if (this._physicsEngine) {
  77649. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  77650. }
  77651. };
  77652. PhysicsImpostor.prototype.getLinearVelocity = function () {
  77653. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  77654. };
  77655. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  77656. if (this._physicsEngine) {
  77657. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  77658. }
  77659. };
  77660. PhysicsImpostor.prototype.getAngularVelocity = function () {
  77661. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  77662. };
  77663. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  77664. if (this._physicsEngine) {
  77665. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  77666. }
  77667. };
  77668. /**
  77669. * Execute a function with the physics plugin native code.
  77670. * Provide a function the will have two variables - the world object and the physics body object.
  77671. */
  77672. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  77673. if (this._physicsEngine) {
  77674. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  77675. }
  77676. };
  77677. /**
  77678. * Register a function that will be executed before the physics world is stepping forward.
  77679. */
  77680. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  77681. this._onBeforePhysicsStepCallbacks.push(func);
  77682. };
  77683. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  77684. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  77685. if (index > -1) {
  77686. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  77687. }
  77688. else {
  77689. BABYLON.Tools.Warn("Function to remove was not found");
  77690. }
  77691. };
  77692. /**
  77693. * Register a function that will be executed after the physics step
  77694. */
  77695. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  77696. this._onAfterPhysicsStepCallbacks.push(func);
  77697. };
  77698. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  77699. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  77700. if (index > -1) {
  77701. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  77702. }
  77703. else {
  77704. BABYLON.Tools.Warn("Function to remove was not found");
  77705. }
  77706. };
  77707. /**
  77708. * register a function that will be executed when this impostor collides against a different body.
  77709. */
  77710. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  77711. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77712. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  77713. };
  77714. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  77715. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77716. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  77717. if (index > -1) {
  77718. this._onPhysicsCollideCallbacks.splice(index, 1);
  77719. }
  77720. else {
  77721. BABYLON.Tools.Warn("Function to remove was not found");
  77722. }
  77723. };
  77724. PhysicsImpostor.prototype.getParentsRotation = function () {
  77725. var parent = this.object.parent;
  77726. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  77727. while (parent) {
  77728. if (parent.rotationQuaternion) {
  77729. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  77730. }
  77731. else {
  77732. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  77733. }
  77734. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  77735. parent = parent.parent;
  77736. }
  77737. return this._tmpQuat;
  77738. };
  77739. /**
  77740. * Apply a force
  77741. */
  77742. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  77743. if (this._physicsEngine) {
  77744. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  77745. }
  77746. return this;
  77747. };
  77748. /**
  77749. * Apply an impulse
  77750. */
  77751. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  77752. if (this._physicsEngine) {
  77753. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  77754. }
  77755. return this;
  77756. };
  77757. /**
  77758. * A help function to create a joint.
  77759. */
  77760. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  77761. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  77762. this.addJoint(otherImpostor, joint);
  77763. return this;
  77764. };
  77765. /**
  77766. * Add a joint to this impostor with a different impostor.
  77767. */
  77768. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  77769. this._joints.push({
  77770. otherImpostor: otherImpostor,
  77771. joint: joint
  77772. });
  77773. if (this._physicsEngine) {
  77774. this._physicsEngine.addJoint(this, otherImpostor, joint);
  77775. }
  77776. return this;
  77777. };
  77778. /**
  77779. * Will keep this body still, in a sleep mode.
  77780. */
  77781. PhysicsImpostor.prototype.sleep = function () {
  77782. if (this._physicsEngine) {
  77783. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  77784. }
  77785. return this;
  77786. };
  77787. /**
  77788. * Wake the body up.
  77789. */
  77790. PhysicsImpostor.prototype.wakeUp = function () {
  77791. if (this._physicsEngine) {
  77792. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  77793. }
  77794. return this;
  77795. };
  77796. PhysicsImpostor.prototype.clone = function (newObject) {
  77797. if (!newObject)
  77798. return null;
  77799. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  77800. };
  77801. PhysicsImpostor.prototype.dispose = function () {
  77802. var _this = this;
  77803. //no dispose if no physics engine is available.
  77804. if (!this._physicsEngine) {
  77805. return;
  77806. }
  77807. this._joints.forEach(function (j) {
  77808. if (_this._physicsEngine) {
  77809. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  77810. }
  77811. });
  77812. //dispose the physics body
  77813. this._physicsEngine.removeImpostor(this);
  77814. if (this.parent) {
  77815. this.parent.forceUpdate();
  77816. }
  77817. else {
  77818. /*this._object.getChildMeshes().forEach(function(mesh) {
  77819. if (mesh.physicsImpostor) {
  77820. if (disposeChildren) {
  77821. mesh.physicsImpostor.dispose();
  77822. mesh.physicsImpostor = null;
  77823. }
  77824. }
  77825. })*/
  77826. }
  77827. this._isDisposed = true;
  77828. };
  77829. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  77830. this._deltaPosition.copyFrom(position);
  77831. };
  77832. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  77833. if (!this._deltaRotation) {
  77834. this._deltaRotation = new BABYLON.Quaternion();
  77835. }
  77836. this._deltaRotation.copyFrom(rotation);
  77837. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  77838. };
  77839. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  77840. if (this._physicsEngine) {
  77841. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  77842. }
  77843. return this;
  77844. };
  77845. PhysicsImpostor.prototype.getRadius = function () {
  77846. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  77847. };
  77848. /**
  77849. * Sync a bone with this impostor
  77850. * @param bone The bone to sync to the impostor.
  77851. * @param boneMesh The mesh that the bone is influencing.
  77852. * @param jointPivot The pivot of the joint / bone in local space.
  77853. * @param distToJoint Optional distance from the impostor to the joint.
  77854. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77855. */
  77856. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  77857. var tempVec = PhysicsImpostor._tmpVecs[0];
  77858. var mesh = this.object;
  77859. if (mesh.rotationQuaternion) {
  77860. if (adjustRotation) {
  77861. var tempQuat = PhysicsImpostor._tmpQuat;
  77862. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  77863. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  77864. }
  77865. else {
  77866. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  77867. }
  77868. }
  77869. tempVec.x = 0;
  77870. tempVec.y = 0;
  77871. tempVec.z = 0;
  77872. if (jointPivot) {
  77873. tempVec.x = jointPivot.x;
  77874. tempVec.y = jointPivot.y;
  77875. tempVec.z = jointPivot.z;
  77876. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  77877. if (distToJoint === undefined || distToJoint === null) {
  77878. distToJoint = jointPivot.length();
  77879. }
  77880. tempVec.x *= distToJoint;
  77881. tempVec.y *= distToJoint;
  77882. tempVec.z *= distToJoint;
  77883. }
  77884. if (bone.getParent()) {
  77885. tempVec.addInPlace(mesh.getAbsolutePosition());
  77886. bone.setAbsolutePosition(tempVec, boneMesh);
  77887. }
  77888. else {
  77889. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  77890. boneMesh.position.x -= tempVec.x;
  77891. boneMesh.position.y -= tempVec.y;
  77892. boneMesh.position.z -= tempVec.z;
  77893. }
  77894. };
  77895. /**
  77896. * Sync impostor to a bone
  77897. * @param bone The bone that the impostor will be synced to.
  77898. * @param boneMesh The mesh that the bone is influencing.
  77899. * @param jointPivot The pivot of the joint / bone in local space.
  77900. * @param distToJoint Optional distance from the impostor to the joint.
  77901. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77902. * @param boneAxis Optional vector3 axis the bone is aligned with
  77903. */
  77904. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  77905. var mesh = this.object;
  77906. if (mesh.rotationQuaternion) {
  77907. if (adjustRotation) {
  77908. var tempQuat = PhysicsImpostor._tmpQuat;
  77909. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  77910. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  77911. }
  77912. else {
  77913. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  77914. }
  77915. }
  77916. var pos = PhysicsImpostor._tmpVecs[0];
  77917. var boneDir = PhysicsImpostor._tmpVecs[1];
  77918. if (!boneAxis) {
  77919. boneAxis = PhysicsImpostor._tmpVecs[2];
  77920. boneAxis.x = 0;
  77921. boneAxis.y = 1;
  77922. boneAxis.z = 0;
  77923. }
  77924. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  77925. bone.getAbsolutePositionToRef(boneMesh, pos);
  77926. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  77927. distToJoint = jointPivot.length();
  77928. }
  77929. if (distToJoint !== undefined && distToJoint !== null) {
  77930. pos.x += boneDir.x * distToJoint;
  77931. pos.y += boneDir.y * distToJoint;
  77932. pos.z += boneDir.z * distToJoint;
  77933. }
  77934. mesh.setAbsolutePosition(pos);
  77935. };
  77936. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  77937. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  77938. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77939. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  77940. //Impostor types
  77941. PhysicsImpostor.NoImpostor = 0;
  77942. PhysicsImpostor.SphereImpostor = 1;
  77943. PhysicsImpostor.BoxImpostor = 2;
  77944. PhysicsImpostor.PlaneImpostor = 3;
  77945. PhysicsImpostor.MeshImpostor = 4;
  77946. PhysicsImpostor.CylinderImpostor = 7;
  77947. PhysicsImpostor.ParticleImpostor = 8;
  77948. PhysicsImpostor.HeightmapImpostor = 9;
  77949. return PhysicsImpostor;
  77950. }());
  77951. BABYLON.PhysicsImpostor = PhysicsImpostor;
  77952. })(BABYLON || (BABYLON = {}));
  77953. //# sourceMappingURL=babylon.physicsImpostor.js.map
  77954. "use strict";
  77955. var BABYLON;
  77956. (function (BABYLON) {
  77957. var PhysicsEngine = /** @class */ (function () {
  77958. function PhysicsEngine(gravity, _physicsPlugin) {
  77959. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  77960. this._physicsPlugin = _physicsPlugin;
  77961. //new methods and parameters
  77962. this._impostors = [];
  77963. this._joints = [];
  77964. if (!this._physicsPlugin.isSupported()) {
  77965. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  77966. + "Please make sure it is included.");
  77967. }
  77968. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  77969. this.setGravity(gravity);
  77970. this.setTimeStep();
  77971. }
  77972. PhysicsEngine.prototype.setGravity = function (gravity) {
  77973. this.gravity = gravity;
  77974. this._physicsPlugin.setGravity(this.gravity);
  77975. };
  77976. /**
  77977. * Set the time step of the physics engine.
  77978. * default is 1/60.
  77979. * To slow it down, enter 1/600 for example.
  77980. * To speed it up, 1/30
  77981. * @param {number} newTimeStep the new timestep to apply to this world.
  77982. */
  77983. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  77984. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  77985. this._physicsPlugin.setTimeStep(newTimeStep);
  77986. };
  77987. /**
  77988. * Get the time step of the physics engine.
  77989. */
  77990. PhysicsEngine.prototype.getTimeStep = function () {
  77991. return this._physicsPlugin.getTimeStep();
  77992. };
  77993. PhysicsEngine.prototype.dispose = function () {
  77994. this._impostors.forEach(function (impostor) {
  77995. impostor.dispose();
  77996. });
  77997. this._physicsPlugin.dispose();
  77998. };
  77999. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  78000. return this._physicsPlugin.name;
  78001. };
  78002. /**
  78003. * Adding a new impostor for the impostor tracking.
  78004. * This will be done by the impostor itself.
  78005. * @param {PhysicsImpostor} impostor the impostor to add
  78006. */
  78007. PhysicsEngine.prototype.addImpostor = function (impostor) {
  78008. impostor.uniqueId = this._impostors.push(impostor);
  78009. //if no parent, generate the body
  78010. if (!impostor.parent) {
  78011. this._physicsPlugin.generatePhysicsBody(impostor);
  78012. }
  78013. };
  78014. /**
  78015. * Remove an impostor from the engine.
  78016. * This impostor and its mesh will not longer be updated by the physics engine.
  78017. * @param {PhysicsImpostor} impostor the impostor to remove
  78018. */
  78019. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  78020. var index = this._impostors.indexOf(impostor);
  78021. if (index > -1) {
  78022. var removed = this._impostors.splice(index, 1);
  78023. //Is it needed?
  78024. if (removed.length) {
  78025. //this will also remove it from the world.
  78026. removed[0].physicsBody = null;
  78027. }
  78028. }
  78029. };
  78030. /**
  78031. * Add a joint to the physics engine
  78032. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  78033. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  78034. * @param {PhysicsJoint} the joint that will connect both impostors.
  78035. */
  78036. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  78037. var impostorJoint = {
  78038. mainImpostor: mainImpostor,
  78039. connectedImpostor: connectedImpostor,
  78040. joint: joint
  78041. };
  78042. joint.physicsPlugin = this._physicsPlugin;
  78043. this._joints.push(impostorJoint);
  78044. this._physicsPlugin.generateJoint(impostorJoint);
  78045. };
  78046. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  78047. var matchingJoints = this._joints.filter(function (impostorJoint) {
  78048. return (impostorJoint.connectedImpostor === connectedImpostor
  78049. && impostorJoint.joint === joint
  78050. && impostorJoint.mainImpostor === mainImpostor);
  78051. });
  78052. if (matchingJoints.length) {
  78053. this._physicsPlugin.removeJoint(matchingJoints[0]);
  78054. //TODO remove it from the list as well
  78055. }
  78056. };
  78057. /**
  78058. * Called by the scene. no need to call it.
  78059. */
  78060. PhysicsEngine.prototype._step = function (delta) {
  78061. var _this = this;
  78062. //check if any mesh has no body / requires an update
  78063. this._impostors.forEach(function (impostor) {
  78064. if (impostor.isBodyInitRequired()) {
  78065. _this._physicsPlugin.generatePhysicsBody(impostor);
  78066. }
  78067. });
  78068. if (delta > 0.1) {
  78069. delta = 0.1;
  78070. }
  78071. else if (delta <= 0) {
  78072. delta = 1.0 / 60.0;
  78073. }
  78074. this._physicsPlugin.executeStep(delta, this._impostors);
  78075. };
  78076. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  78077. return this._physicsPlugin;
  78078. };
  78079. PhysicsEngine.prototype.getImpostors = function () {
  78080. return this._impostors;
  78081. };
  78082. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  78083. for (var i = 0; i < this._impostors.length; ++i) {
  78084. if (this._impostors[i].object === object) {
  78085. return this._impostors[i];
  78086. }
  78087. }
  78088. return null;
  78089. };
  78090. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  78091. for (var i = 0; i < this._impostors.length; ++i) {
  78092. if (this._impostors[i].physicsBody === body) {
  78093. return this._impostors[i];
  78094. }
  78095. }
  78096. return null;
  78097. };
  78098. // Statics
  78099. PhysicsEngine.Epsilon = 0.001;
  78100. return PhysicsEngine;
  78101. }());
  78102. BABYLON.PhysicsEngine = PhysicsEngine;
  78103. })(BABYLON || (BABYLON = {}));
  78104. //# sourceMappingURL=babylon.physicsEngine.js.map
  78105. "use strict";
  78106. var BABYLON;
  78107. (function (BABYLON) {
  78108. var PhysicsHelper = /** @class */ (function () {
  78109. function PhysicsHelper(scene) {
  78110. this._scene = scene;
  78111. this._physicsEngine = this._scene.getPhysicsEngine();
  78112. if (!this._physicsEngine) {
  78113. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  78114. }
  78115. }
  78116. /**
  78117. * @param {Vector3} origin the origin of the explosion
  78118. * @param {number} radius the explosion radius
  78119. * @param {number} strength the explosion strength
  78120. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78121. */
  78122. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  78123. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78124. if (!this._physicsEngine) {
  78125. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  78126. return null;
  78127. }
  78128. var impostors = this._physicsEngine.getImpostors();
  78129. if (impostors.length === 0) {
  78130. return null;
  78131. }
  78132. var event = new PhysicsRadialExplosionEvent(this._scene);
  78133. impostors.forEach(function (impostor) {
  78134. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  78135. if (!impostorForceAndContactPoint) {
  78136. return;
  78137. }
  78138. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78139. });
  78140. event.dispose(false);
  78141. return event;
  78142. };
  78143. /**
  78144. * @param {Vector3} origin the origin of the explosion
  78145. * @param {number} radius the explosion radius
  78146. * @param {number} strength the explosion strength
  78147. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78148. */
  78149. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  78150. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78151. if (!this._physicsEngine) {
  78152. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78153. return null;
  78154. }
  78155. var impostors = this._physicsEngine.getImpostors();
  78156. if (impostors.length === 0) {
  78157. return null;
  78158. }
  78159. var event = new PhysicsRadialExplosionEvent(this._scene);
  78160. impostors.forEach(function (impostor) {
  78161. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  78162. if (!impostorForceAndContactPoint) {
  78163. return;
  78164. }
  78165. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78166. });
  78167. event.dispose(false);
  78168. return event;
  78169. };
  78170. /**
  78171. * @param {Vector3} origin the origin of the explosion
  78172. * @param {number} radius the explosion radius
  78173. * @param {number} strength the explosion strength
  78174. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78175. */
  78176. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  78177. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78178. if (!this._physicsEngine) {
  78179. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78180. return null;
  78181. }
  78182. var impostors = this._physicsEngine.getImpostors();
  78183. if (impostors.length === 0) {
  78184. return null;
  78185. }
  78186. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  78187. event.dispose(false);
  78188. return event;
  78189. };
  78190. /**
  78191. * @param {Vector3} origin the origin of the updraft
  78192. * @param {number} radius the radius of the updraft
  78193. * @param {number} strength the strength of the updraft
  78194. * @param {number} height the height of the updraft
  78195. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  78196. */
  78197. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  78198. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  78199. if (!this._physicsEngine) {
  78200. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78201. return null;
  78202. }
  78203. if (this._physicsEngine.getImpostors().length === 0) {
  78204. return null;
  78205. }
  78206. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  78207. event.dispose(false);
  78208. return event;
  78209. };
  78210. /**
  78211. * @param {Vector3} origin the of the vortex
  78212. * @param {number} radius the radius of the vortex
  78213. * @param {number} strength the strength of the vortex
  78214. * @param {number} height the height of the vortex
  78215. */
  78216. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  78217. if (!this._physicsEngine) {
  78218. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78219. return null;
  78220. }
  78221. if (this._physicsEngine.getImpostors().length === 0) {
  78222. return null;
  78223. }
  78224. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  78225. event.dispose(false);
  78226. return event;
  78227. };
  78228. return PhysicsHelper;
  78229. }());
  78230. BABYLON.PhysicsHelper = PhysicsHelper;
  78231. /***** Radial explosion *****/
  78232. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  78233. function PhysicsRadialExplosionEvent(scene) {
  78234. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  78235. this._rays = [];
  78236. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  78237. this._scene = scene;
  78238. }
  78239. /**
  78240. * Returns the data related to the radial explosion event (sphere & rays).
  78241. * @returns {PhysicsRadialExplosionEventData}
  78242. */
  78243. PhysicsRadialExplosionEvent.prototype.getData = function () {
  78244. this._dataFetched = true;
  78245. return {
  78246. sphere: this._sphere,
  78247. rays: this._rays,
  78248. };
  78249. };
  78250. /**
  78251. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  78252. * @param impostor
  78253. * @param {Vector3} origin the origin of the explosion
  78254. * @param {number} radius the explosion radius
  78255. * @param {number} strength the explosion strength
  78256. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  78257. * @returns {Nullable<PhysicsForceAndContactPoint>}
  78258. */
  78259. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  78260. if (impostor.mass === 0) {
  78261. return null;
  78262. }
  78263. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  78264. return null;
  78265. }
  78266. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  78267. return null;
  78268. }
  78269. var impostorObjectCenter = impostor.getObjectCenter();
  78270. var direction = impostorObjectCenter.subtract(origin);
  78271. var ray = new BABYLON.Ray(origin, direction, radius);
  78272. this._rays.push(ray);
  78273. var hit = ray.intersectsMesh(impostor.object);
  78274. var contactPoint = hit.pickedPoint;
  78275. if (!contactPoint) {
  78276. return null;
  78277. }
  78278. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  78279. if (distanceFromOrigin > radius) {
  78280. return null;
  78281. }
  78282. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  78283. ? strength
  78284. : strength * (1 - (distanceFromOrigin / radius));
  78285. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78286. return { force: force, contactPoint: contactPoint };
  78287. };
  78288. /**
  78289. * Disposes the sphere.
  78290. * @param {bolean} force
  78291. */
  78292. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  78293. var _this = this;
  78294. if (force === void 0) { force = true; }
  78295. if (force) {
  78296. this._sphere.dispose();
  78297. }
  78298. else {
  78299. setTimeout(function () {
  78300. if (!_this._dataFetched) {
  78301. _this._sphere.dispose();
  78302. }
  78303. }, 0);
  78304. }
  78305. };
  78306. /*** Helpers ***/
  78307. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  78308. if (!this._sphere) {
  78309. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  78310. this._sphere.isVisible = false;
  78311. }
  78312. };
  78313. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  78314. var impostorObject = impostor.object;
  78315. this._prepareSphere();
  78316. this._sphere.position = origin;
  78317. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  78318. this._sphere._updateBoundingInfo();
  78319. this._sphere.computeWorldMatrix(true);
  78320. return this._sphere.intersectsMesh(impostorObject, true);
  78321. };
  78322. return PhysicsRadialExplosionEvent;
  78323. }());
  78324. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  78325. /***** Gravitational Field *****/
  78326. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  78327. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  78328. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78329. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78330. this._physicsHelper = physicsHelper;
  78331. this._scene = scene;
  78332. this._origin = origin;
  78333. this._radius = radius;
  78334. this._strength = strength;
  78335. this._falloff = falloff;
  78336. this._tickCallback = this._tick.bind(this);
  78337. }
  78338. /**
  78339. * Returns the data related to the gravitational field event (sphere).
  78340. * @returns {PhysicsGravitationalFieldEventData}
  78341. */
  78342. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  78343. this._dataFetched = true;
  78344. return {
  78345. sphere: this._sphere,
  78346. };
  78347. };
  78348. /**
  78349. * Enables the gravitational field.
  78350. */
  78351. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  78352. this._tickCallback.call(this);
  78353. this._scene.registerBeforeRender(this._tickCallback);
  78354. };
  78355. /**
  78356. * Disables the gravitational field.
  78357. */
  78358. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  78359. this._scene.unregisterBeforeRender(this._tickCallback);
  78360. };
  78361. /**
  78362. * Disposes the sphere.
  78363. * @param {bolean} force
  78364. */
  78365. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  78366. var _this = this;
  78367. if (force === void 0) { force = true; }
  78368. if (force) {
  78369. this._sphere.dispose();
  78370. }
  78371. else {
  78372. setTimeout(function () {
  78373. if (!_this._dataFetched) {
  78374. _this._sphere.dispose();
  78375. }
  78376. }, 0);
  78377. }
  78378. };
  78379. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  78380. // Since the params won't change, we fetch the event only once
  78381. if (this._sphere) {
  78382. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78383. }
  78384. else {
  78385. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78386. if (radialExplosionEvent) {
  78387. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  78388. }
  78389. }
  78390. };
  78391. return PhysicsGravitationalFieldEvent;
  78392. }());
  78393. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  78394. /***** Updraft *****/
  78395. var PhysicsUpdraftEvent = /** @class */ (function () {
  78396. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  78397. this._scene = _scene;
  78398. this._origin = _origin;
  78399. this._radius = _radius;
  78400. this._strength = _strength;
  78401. this._height = _height;
  78402. this._updraftMode = _updraftMode;
  78403. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78404. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  78405. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78406. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78407. this._physicsEngine = this._scene.getPhysicsEngine();
  78408. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78409. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78410. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78411. this._originDirection = this._origin.subtract(this._originTop).normalize();
  78412. }
  78413. this._tickCallback = this._tick.bind(this);
  78414. }
  78415. /**
  78416. * Returns the data related to the updraft event (cylinder).
  78417. * @returns {PhysicsUpdraftEventData}
  78418. */
  78419. PhysicsUpdraftEvent.prototype.getData = function () {
  78420. this._dataFetched = true;
  78421. return {
  78422. cylinder: this._cylinder,
  78423. };
  78424. };
  78425. /**
  78426. * Enables the updraft.
  78427. */
  78428. PhysicsUpdraftEvent.prototype.enable = function () {
  78429. this._tickCallback.call(this);
  78430. this._scene.registerBeforeRender(this._tickCallback);
  78431. };
  78432. /**
  78433. * Disables the cortex.
  78434. */
  78435. PhysicsUpdraftEvent.prototype.disable = function () {
  78436. this._scene.unregisterBeforeRender(this._tickCallback);
  78437. };
  78438. /**
  78439. * Disposes the sphere.
  78440. * @param {bolean} force
  78441. */
  78442. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  78443. var _this = this;
  78444. if (force === void 0) { force = true; }
  78445. if (force) {
  78446. this._cylinder.dispose();
  78447. }
  78448. else {
  78449. setTimeout(function () {
  78450. if (!_this._dataFetched) {
  78451. _this._cylinder.dispose();
  78452. }
  78453. }, 0);
  78454. }
  78455. };
  78456. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78457. if (impostor.mass === 0) {
  78458. return null;
  78459. }
  78460. if (!this._intersectsWithCylinder(impostor)) {
  78461. return null;
  78462. }
  78463. var impostorObjectCenter = impostor.getObjectCenter();
  78464. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78465. var direction = this._originDirection;
  78466. }
  78467. else {
  78468. var direction = impostorObjectCenter.subtract(this._originTop);
  78469. }
  78470. var multiplier = this._strength * -1;
  78471. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78472. return { force: force, contactPoint: impostorObjectCenter };
  78473. };
  78474. PhysicsUpdraftEvent.prototype._tick = function () {
  78475. var _this = this;
  78476. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78477. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78478. if (!impostorForceAndContactPoint) {
  78479. return;
  78480. }
  78481. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78482. });
  78483. };
  78484. /*** Helpers ***/
  78485. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  78486. if (!this._cylinder) {
  78487. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  78488. height: this._height,
  78489. diameter: this._radius * 2,
  78490. }, this._scene);
  78491. this._cylinder.isVisible = false;
  78492. }
  78493. };
  78494. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  78495. var impostorObject = impostor.object;
  78496. this._prepareCylinder();
  78497. this._cylinder.position = this._cylinderPosition;
  78498. return this._cylinder.intersectsMesh(impostorObject, true);
  78499. };
  78500. return PhysicsUpdraftEvent;
  78501. }());
  78502. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  78503. /***** Vortex *****/
  78504. var PhysicsVortexEvent = /** @class */ (function () {
  78505. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  78506. this._scene = _scene;
  78507. this._origin = _origin;
  78508. this._radius = _radius;
  78509. this._strength = _strength;
  78510. this._height = _height;
  78511. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78512. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  78513. this._updraftMultiplier = 0.02;
  78514. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78515. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78516. this._physicsEngine = this._scene.getPhysicsEngine();
  78517. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78518. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78519. this._tickCallback = this._tick.bind(this);
  78520. }
  78521. /**
  78522. * Returns the data related to the vortex event (cylinder).
  78523. * @returns {PhysicsVortexEventData}
  78524. */
  78525. PhysicsVortexEvent.prototype.getData = function () {
  78526. this._dataFetched = true;
  78527. return {
  78528. cylinder: this._cylinder,
  78529. };
  78530. };
  78531. /**
  78532. * Enables the vortex.
  78533. */
  78534. PhysicsVortexEvent.prototype.enable = function () {
  78535. this._tickCallback.call(this);
  78536. this._scene.registerBeforeRender(this._tickCallback);
  78537. };
  78538. /**
  78539. * Disables the cortex.
  78540. */
  78541. PhysicsVortexEvent.prototype.disable = function () {
  78542. this._scene.unregisterBeforeRender(this._tickCallback);
  78543. };
  78544. /**
  78545. * Disposes the sphere.
  78546. * @param {bolean} force
  78547. */
  78548. PhysicsVortexEvent.prototype.dispose = function (force) {
  78549. var _this = this;
  78550. if (force === void 0) { force = true; }
  78551. if (force) {
  78552. this._cylinder.dispose();
  78553. }
  78554. else {
  78555. setTimeout(function () {
  78556. if (!_this._dataFetched) {
  78557. _this._cylinder.dispose();
  78558. }
  78559. }, 0);
  78560. }
  78561. };
  78562. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78563. if (impostor.mass === 0) {
  78564. return null;
  78565. }
  78566. if (!this._intersectsWithCylinder(impostor)) {
  78567. return null;
  78568. }
  78569. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  78570. return null;
  78571. }
  78572. var impostorObjectCenter = impostor.getObjectCenter();
  78573. 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)
  78574. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  78575. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  78576. var hit = ray.intersectsMesh(impostor.object);
  78577. var contactPoint = hit.pickedPoint;
  78578. if (!contactPoint) {
  78579. return null;
  78580. }
  78581. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  78582. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  78583. var directionToOrigin = contactPoint.normalize();
  78584. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78585. directionToOrigin = directionToOrigin.negate();
  78586. }
  78587. // TODO: find a more physically based solution
  78588. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78589. var forceX = directionToOrigin.x * this._strength / 8;
  78590. var forceY = directionToOrigin.y * this._updraftMultiplier;
  78591. var forceZ = directionToOrigin.z * this._strength / 8;
  78592. }
  78593. else {
  78594. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  78595. var forceY = this._originTop.y * this._updraftMultiplier;
  78596. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  78597. }
  78598. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  78599. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  78600. return { force: force, contactPoint: impostorObjectCenter };
  78601. };
  78602. PhysicsVortexEvent.prototype._tick = function () {
  78603. var _this = this;
  78604. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78605. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78606. if (!impostorForceAndContactPoint) {
  78607. return;
  78608. }
  78609. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78610. });
  78611. };
  78612. /*** Helpers ***/
  78613. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  78614. if (!this._cylinder) {
  78615. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  78616. height: this._height,
  78617. diameter: this._radius * 2,
  78618. }, this._scene);
  78619. this._cylinder.isVisible = false;
  78620. }
  78621. };
  78622. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  78623. var impostorObject = impostor.object;
  78624. this._prepareCylinder();
  78625. this._cylinder.position = this._cylinderPosition;
  78626. return this._cylinder.intersectsMesh(impostorObject, true);
  78627. };
  78628. return PhysicsVortexEvent;
  78629. }());
  78630. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  78631. /***** Enums *****/
  78632. /**
  78633. * The strenght of the force in correspondence to the distance of the affected object
  78634. */
  78635. var PhysicsRadialImpulseFalloff;
  78636. (function (PhysicsRadialImpulseFalloff) {
  78637. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  78638. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  78639. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  78640. /**
  78641. * The strenght of the force in correspondence to the distance of the affected object
  78642. */
  78643. var PhysicsUpdraftMode;
  78644. (function (PhysicsUpdraftMode) {
  78645. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  78646. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  78647. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  78648. })(BABYLON || (BABYLON = {}));
  78649. //# sourceMappingURL=babylon.physicsHelper.js.map
  78650. "use strict";
  78651. var BABYLON;
  78652. (function (BABYLON) {
  78653. var CannonJSPlugin = /** @class */ (function () {
  78654. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  78655. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  78656. if (iterations === void 0) { iterations = 10; }
  78657. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  78658. this.name = "CannonJSPlugin";
  78659. this._physicsMaterials = new Array();
  78660. this._fixedTimeStep = 1 / 60;
  78661. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  78662. this.BJSCANNON = CANNON;
  78663. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  78664. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  78665. this._tmpPosition = BABYLON.Vector3.Zero();
  78666. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  78667. this._tmpUnityRotation = new BABYLON.Quaternion();
  78668. if (!this.isSupported()) {
  78669. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  78670. return;
  78671. }
  78672. this._extendNamespace();
  78673. this.world = new this.BJSCANNON.World();
  78674. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  78675. this.world.solver.iterations = iterations;
  78676. }
  78677. CannonJSPlugin.prototype.setGravity = function (gravity) {
  78678. this.world.gravity.copy(gravity);
  78679. };
  78680. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  78681. this._fixedTimeStep = timeStep;
  78682. };
  78683. CannonJSPlugin.prototype.getTimeStep = function () {
  78684. return this._fixedTimeStep;
  78685. };
  78686. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  78687. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  78688. };
  78689. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78690. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78691. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78692. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  78693. };
  78694. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78695. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78696. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78697. impostor.physicsBody.applyForce(impulse, worldPoint);
  78698. };
  78699. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78700. //parent-child relationship. Does this impostor has a parent impostor?
  78701. if (impostor.parent) {
  78702. if (impostor.physicsBody) {
  78703. this.removePhysicsBody(impostor);
  78704. //TODO is that needed?
  78705. impostor.forceUpdate();
  78706. }
  78707. return;
  78708. }
  78709. //should a new body be created for this impostor?
  78710. if (impostor.isBodyInitRequired()) {
  78711. var shape = this._createShape(impostor);
  78712. //unregister events, if body is being changed
  78713. var oldBody = impostor.physicsBody;
  78714. if (oldBody) {
  78715. this.removePhysicsBody(impostor);
  78716. }
  78717. //create the body and material
  78718. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  78719. var bodyCreationObject = {
  78720. mass: impostor.getParam("mass"),
  78721. material: material
  78722. };
  78723. // A simple extend, in case native options were used.
  78724. var nativeOptions = impostor.getParam("nativeOptions");
  78725. for (var key in nativeOptions) {
  78726. if (nativeOptions.hasOwnProperty(key)) {
  78727. bodyCreationObject[key] = nativeOptions[key];
  78728. }
  78729. }
  78730. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  78731. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  78732. this.world.addEventListener("preStep", impostor.beforeStep);
  78733. this.world.addEventListener("postStep", impostor.afterStep);
  78734. impostor.physicsBody.addShape(shape);
  78735. this.world.add(impostor.physicsBody);
  78736. //try to keep the body moving in the right direction by taking old properties.
  78737. //Should be tested!
  78738. if (oldBody) {
  78739. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  78740. impostor.physicsBody[param].copy(oldBody[param]);
  78741. });
  78742. }
  78743. this._processChildMeshes(impostor);
  78744. }
  78745. //now update the body's transformation
  78746. this._updatePhysicsBodyTransformation(impostor);
  78747. };
  78748. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  78749. var _this = this;
  78750. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  78751. var currentRotation = mainImpostor.object.rotationQuaternion;
  78752. if (meshChildren.length) {
  78753. var processMesh = function (localPosition, mesh) {
  78754. if (!currentRotation || !mesh.rotationQuaternion) {
  78755. return;
  78756. }
  78757. var childImpostor = mesh.getPhysicsImpostor();
  78758. if (childImpostor) {
  78759. var parent = childImpostor.parent;
  78760. if (parent !== mainImpostor) {
  78761. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  78762. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  78763. if (childImpostor.physicsBody) {
  78764. _this.removePhysicsBody(childImpostor);
  78765. childImpostor.physicsBody = null;
  78766. }
  78767. childImpostor.parent = mainImpostor;
  78768. childImpostor.resetUpdateFlags();
  78769. 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));
  78770. //Add the mass of the children.
  78771. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  78772. }
  78773. }
  78774. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  78775. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  78776. };
  78777. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  78778. }
  78779. };
  78780. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78781. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  78782. this.world.removeEventListener("preStep", impostor.beforeStep);
  78783. this.world.removeEventListener("postStep", impostor.afterStep);
  78784. this.world.remove(impostor.physicsBody);
  78785. };
  78786. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78787. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78788. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78789. if (!mainBody || !connectedBody) {
  78790. return;
  78791. }
  78792. var constraint;
  78793. var jointData = impostorJoint.joint.jointData;
  78794. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  78795. var constraintData = {
  78796. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  78797. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  78798. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  78799. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  78800. maxForce: jointData.nativeParams.maxForce,
  78801. collideConnected: !!jointData.collision
  78802. };
  78803. switch (impostorJoint.joint.type) {
  78804. case BABYLON.PhysicsJoint.HingeJoint:
  78805. case BABYLON.PhysicsJoint.Hinge2Joint:
  78806. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  78807. break;
  78808. case BABYLON.PhysicsJoint.DistanceJoint:
  78809. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  78810. break;
  78811. case BABYLON.PhysicsJoint.SpringJoint:
  78812. var springData = jointData;
  78813. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  78814. restLength: springData.length,
  78815. stiffness: springData.stiffness,
  78816. damping: springData.damping,
  78817. localAnchorA: constraintData.pivotA,
  78818. localAnchorB: constraintData.pivotB
  78819. });
  78820. break;
  78821. case BABYLON.PhysicsJoint.LockJoint:
  78822. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  78823. break;
  78824. case BABYLON.PhysicsJoint.PointToPointJoint:
  78825. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78826. default:
  78827. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  78828. break;
  78829. }
  78830. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  78831. constraint.collideConnected = !!jointData.collision;
  78832. impostorJoint.joint.physicsJoint = constraint;
  78833. //don't add spring as constraint, as it is not one.
  78834. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  78835. this.world.addConstraint(constraint);
  78836. }
  78837. else {
  78838. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  78839. constraint.applyForce();
  78840. });
  78841. }
  78842. };
  78843. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78844. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  78845. };
  78846. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  78847. var index;
  78848. var mat;
  78849. for (index = 0; index < this._physicsMaterials.length; index++) {
  78850. mat = this._physicsMaterials[index];
  78851. if (mat.friction === friction && mat.restitution === restitution) {
  78852. return mat;
  78853. }
  78854. }
  78855. var currentMat = new this.BJSCANNON.Material(name);
  78856. currentMat.friction = friction;
  78857. currentMat.restitution = restitution;
  78858. this._physicsMaterials.push(currentMat);
  78859. return currentMat;
  78860. };
  78861. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  78862. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  78863. };
  78864. CannonJSPlugin.prototype._createShape = function (impostor) {
  78865. var object = impostor.object;
  78866. var returnValue;
  78867. var extendSize = impostor.getObjectExtendSize();
  78868. switch (impostor.type) {
  78869. case BABYLON.PhysicsImpostor.SphereImpostor:
  78870. var radiusX = extendSize.x;
  78871. var radiusY = extendSize.y;
  78872. var radiusZ = extendSize.z;
  78873. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  78874. break;
  78875. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  78876. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78877. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  78878. break;
  78879. case BABYLON.PhysicsImpostor.BoxImpostor:
  78880. var box = extendSize.scale(0.5);
  78881. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  78882. break;
  78883. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78884. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  78885. returnValue = new this.BJSCANNON.Plane();
  78886. break;
  78887. case BABYLON.PhysicsImpostor.MeshImpostor:
  78888. // should transform the vertex data to world coordinates!!
  78889. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  78890. var rawFaces = object.getIndices ? object.getIndices() : [];
  78891. if (!rawVerts)
  78892. return;
  78893. // get only scale! so the object could transform correctly.
  78894. var oldPosition = object.position.clone();
  78895. var oldRotation = object.rotation && object.rotation.clone();
  78896. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  78897. object.position.copyFromFloats(0, 0, 0);
  78898. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78899. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78900. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78901. var transform = object.computeWorldMatrix(true);
  78902. // convert rawVerts to object space
  78903. var temp = new Array();
  78904. var index;
  78905. for (index = 0; index < rawVerts.length; index += 3) {
  78906. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  78907. }
  78908. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  78909. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  78910. //now set back the transformation!
  78911. object.position.copyFrom(oldPosition);
  78912. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  78913. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  78914. break;
  78915. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  78916. var oldPosition2 = object.position.clone();
  78917. var oldRotation2 = object.rotation && object.rotation.clone();
  78918. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  78919. object.position.copyFromFloats(0, 0, 0);
  78920. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78921. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78922. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78923. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  78924. returnValue = this._createHeightmap(object);
  78925. object.position.copyFrom(oldPosition2);
  78926. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  78927. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  78928. object.computeWorldMatrix(true);
  78929. break;
  78930. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78931. returnValue = new this.BJSCANNON.Particle();
  78932. break;
  78933. }
  78934. return returnValue;
  78935. };
  78936. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  78937. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78938. var transform = object.computeWorldMatrix(true);
  78939. // convert rawVerts to object space
  78940. var temp = new Array();
  78941. var index;
  78942. for (index = 0; index < pos.length; index += 3) {
  78943. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  78944. }
  78945. pos = temp;
  78946. var matrix = new Array();
  78947. //For now pointDepth will not be used and will be automatically calculated.
  78948. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  78949. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  78950. var boundingInfo = object.getBoundingInfo();
  78951. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  78952. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  78953. var elementSize = dim * 2 / arraySize;
  78954. for (var i = 0; i < pos.length; i = i + 3) {
  78955. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  78956. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  78957. var y = -pos[i + 2] + minY;
  78958. if (!matrix[x]) {
  78959. matrix[x] = [];
  78960. }
  78961. if (!matrix[x][z]) {
  78962. matrix[x][z] = y;
  78963. }
  78964. matrix[x][z] = Math.max(y, matrix[x][z]);
  78965. }
  78966. for (var x = 0; x <= arraySize; ++x) {
  78967. if (!matrix[x]) {
  78968. var loc = 1;
  78969. while (!matrix[(x + loc) % arraySize]) {
  78970. loc++;
  78971. }
  78972. matrix[x] = matrix[(x + loc) % arraySize].slice();
  78973. //console.log("missing x", x);
  78974. }
  78975. for (var z = 0; z <= arraySize; ++z) {
  78976. if (!matrix[x][z]) {
  78977. var loc = 1;
  78978. var newValue;
  78979. while (newValue === undefined) {
  78980. newValue = matrix[x][(z + loc++) % arraySize];
  78981. }
  78982. matrix[x][z] = newValue;
  78983. }
  78984. }
  78985. }
  78986. var shape = new this.BJSCANNON.Heightfield(matrix, {
  78987. elementSize: elementSize
  78988. });
  78989. //For future reference, needed for body transformation
  78990. shape.minY = minY;
  78991. return shape;
  78992. };
  78993. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  78994. var object = impostor.object;
  78995. //make sure it is updated...
  78996. object.computeWorldMatrix && object.computeWorldMatrix(true);
  78997. // The delta between the mesh position and the mesh bounding box center
  78998. var bInfo = object.getBoundingInfo();
  78999. if (!bInfo)
  79000. return;
  79001. var center = impostor.getObjectCenter();
  79002. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  79003. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  79004. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  79005. this._tmpPosition.copyFrom(center);
  79006. var quaternion = object.rotationQuaternion;
  79007. if (!quaternion) {
  79008. return;
  79009. }
  79010. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  79011. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  79012. //-90 DEG in X, precalculated
  79013. quaternion = quaternion.multiply(this._minus90X);
  79014. //Invert! (Precalculated, 90 deg in X)
  79015. //No need to clone. this will never change.
  79016. impostor.setDeltaRotation(this._plus90X);
  79017. }
  79018. //If it is a heightfield, if should be centered.
  79019. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  79020. var mesh = object;
  79021. var boundingInfo = mesh.getBoundingInfo();
  79022. //calculate the correct body position:
  79023. var rotationQuaternion = mesh.rotationQuaternion;
  79024. mesh.rotationQuaternion = this._tmpUnityRotation;
  79025. mesh.computeWorldMatrix(true);
  79026. //get original center with no rotation
  79027. var c = center.clone();
  79028. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  79029. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  79030. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  79031. mesh.setPreTransformMatrix(p);
  79032. mesh.computeWorldMatrix(true);
  79033. //calculate the translation
  79034. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  79035. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  79036. //add it inverted to the delta
  79037. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  79038. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  79039. //rotation is back
  79040. mesh.rotationQuaternion = rotationQuaternion;
  79041. mesh.setPreTransformMatrix(oldPivot);
  79042. mesh.computeWorldMatrix(true);
  79043. }
  79044. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  79045. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  79046. //this._tmpPosition.copyFrom(object.position);
  79047. }
  79048. impostor.setDeltaPosition(this._tmpDeltaPosition);
  79049. //Now update the impostor object
  79050. impostor.physicsBody.position.copy(this._tmpPosition);
  79051. impostor.physicsBody.quaternion.copy(quaternion);
  79052. };
  79053. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79054. impostor.object.position.copyFrom(impostor.physicsBody.position);
  79055. if (impostor.object.rotationQuaternion) {
  79056. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  79057. }
  79058. };
  79059. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79060. impostor.physicsBody.position.copy(newPosition);
  79061. impostor.physicsBody.quaternion.copy(newRotation);
  79062. };
  79063. CannonJSPlugin.prototype.isSupported = function () {
  79064. return this.BJSCANNON !== undefined;
  79065. };
  79066. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79067. impostor.physicsBody.velocity.copy(velocity);
  79068. };
  79069. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79070. impostor.physicsBody.angularVelocity.copy(velocity);
  79071. };
  79072. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79073. var v = impostor.physicsBody.velocity;
  79074. if (!v) {
  79075. return null;
  79076. }
  79077. return new BABYLON.Vector3(v.x, v.y, v.z);
  79078. };
  79079. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79080. var v = impostor.physicsBody.angularVelocity;
  79081. if (!v) {
  79082. return null;
  79083. }
  79084. return new BABYLON.Vector3(v.x, v.y, v.z);
  79085. };
  79086. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79087. impostor.physicsBody.mass = mass;
  79088. impostor.physicsBody.updateMassProperties();
  79089. };
  79090. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  79091. return impostor.physicsBody.mass;
  79092. };
  79093. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  79094. return impostor.physicsBody.material.friction;
  79095. };
  79096. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79097. impostor.physicsBody.material.friction = friction;
  79098. };
  79099. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79100. return impostor.physicsBody.material.restitution;
  79101. };
  79102. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79103. impostor.physicsBody.material.restitution = restitution;
  79104. };
  79105. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  79106. impostor.physicsBody.sleep();
  79107. };
  79108. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  79109. impostor.physicsBody.wakeUp();
  79110. };
  79111. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79112. joint.physicsJoint.distance = maxDistance;
  79113. };
  79114. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  79115. // if (!motorIndex) {
  79116. // joint.physicsJoint.enableMotor();
  79117. // }
  79118. // }
  79119. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  79120. // if (!motorIndex) {
  79121. // joint.physicsJoint.disableMotor();
  79122. // }
  79123. // }
  79124. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79125. if (!motorIndex) {
  79126. joint.physicsJoint.enableMotor();
  79127. joint.physicsJoint.setMotorSpeed(speed);
  79128. if (maxForce) {
  79129. this.setLimit(joint, maxForce);
  79130. }
  79131. }
  79132. };
  79133. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  79134. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  79135. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  79136. };
  79137. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79138. var body = impostor.physicsBody;
  79139. mesh.position.x = body.position.x;
  79140. mesh.position.y = body.position.y;
  79141. mesh.position.z = body.position.z;
  79142. if (mesh.rotationQuaternion) {
  79143. mesh.rotationQuaternion.x = body.quaternion.x;
  79144. mesh.rotationQuaternion.y = body.quaternion.y;
  79145. mesh.rotationQuaternion.z = body.quaternion.z;
  79146. mesh.rotationQuaternion.w = body.quaternion.w;
  79147. }
  79148. };
  79149. CannonJSPlugin.prototype.getRadius = function (impostor) {
  79150. var shape = impostor.physicsBody.shapes[0];
  79151. return shape.boundingSphereRadius;
  79152. };
  79153. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79154. var shape = impostor.physicsBody.shapes[0];
  79155. result.x = shape.halfExtents.x * 2;
  79156. result.y = shape.halfExtents.y * 2;
  79157. result.z = shape.halfExtents.z * 2;
  79158. };
  79159. CannonJSPlugin.prototype.dispose = function () {
  79160. };
  79161. CannonJSPlugin.prototype._extendNamespace = function () {
  79162. //this will force cannon to execute at least one step when using interpolation
  79163. var step_tmp1 = new this.BJSCANNON.Vec3();
  79164. var Engine = this.BJSCANNON;
  79165. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  79166. maxSubSteps = maxSubSteps || 10;
  79167. timeSinceLastCalled = timeSinceLastCalled || 0;
  79168. if (timeSinceLastCalled === 0) {
  79169. this.internalStep(dt);
  79170. this.time += dt;
  79171. }
  79172. else {
  79173. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  79174. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  79175. var t0 = performance.now();
  79176. for (var i = 0; i !== internalSteps; i++) {
  79177. this.internalStep(dt);
  79178. if (performance.now() - t0 > dt * 1000) {
  79179. break;
  79180. }
  79181. }
  79182. this.time += timeSinceLastCalled;
  79183. var h = this.time % dt;
  79184. var h_div_dt = h / dt;
  79185. var interpvelo = step_tmp1;
  79186. var bodies = this.bodies;
  79187. for (var j = 0; j !== bodies.length; j++) {
  79188. var b = bodies[j];
  79189. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  79190. b.position.vsub(b.previousPosition, interpvelo);
  79191. interpvelo.scale(h_div_dt, interpvelo);
  79192. b.position.vadd(interpvelo, b.interpolatedPosition);
  79193. }
  79194. else {
  79195. b.interpolatedPosition.copy(b.position);
  79196. b.interpolatedQuaternion.copy(b.quaternion);
  79197. }
  79198. }
  79199. }
  79200. };
  79201. };
  79202. return CannonJSPlugin;
  79203. }());
  79204. BABYLON.CannonJSPlugin = CannonJSPlugin;
  79205. })(BABYLON || (BABYLON = {}));
  79206. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  79207. "use strict";
  79208. var BABYLON;
  79209. (function (BABYLON) {
  79210. var OimoJSPlugin = /** @class */ (function () {
  79211. function OimoJSPlugin(iterations) {
  79212. this.name = "OimoJSPlugin";
  79213. this._tmpImpostorsArray = [];
  79214. this._tmpPositionVector = BABYLON.Vector3.Zero();
  79215. this.BJSOIMO = OIMO;
  79216. this.world = new this.BJSOIMO.World({
  79217. iterations: iterations
  79218. });
  79219. this.world.clear();
  79220. }
  79221. OimoJSPlugin.prototype.setGravity = function (gravity) {
  79222. this.world.gravity.copy(gravity);
  79223. };
  79224. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  79225. this.world.timeStep = timeStep;
  79226. };
  79227. OimoJSPlugin.prototype.getTimeStep = function () {
  79228. return this.world.timeStep;
  79229. };
  79230. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  79231. var _this = this;
  79232. impostors.forEach(function (impostor) {
  79233. impostor.beforeStep();
  79234. });
  79235. this.world.step();
  79236. impostors.forEach(function (impostor) {
  79237. impostor.afterStep();
  79238. //update the ordered impostors array
  79239. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  79240. });
  79241. //check for collisions
  79242. var contact = this.world.contacts;
  79243. while (contact !== null) {
  79244. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  79245. contact = contact.next;
  79246. continue;
  79247. }
  79248. //is this body colliding with any other? get the impostor
  79249. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  79250. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  79251. if (!mainImpostor || !collidingImpostor) {
  79252. contact = contact.next;
  79253. continue;
  79254. }
  79255. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  79256. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  79257. contact = contact.next;
  79258. }
  79259. };
  79260. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  79261. var mass = impostor.physicsBody.mass;
  79262. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  79263. };
  79264. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  79265. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  79266. this.applyImpulse(impostor, force, contactPoint);
  79267. };
  79268. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  79269. var _this = this;
  79270. //parent-child relationship. Does this impostor has a parent impostor?
  79271. if (impostor.parent) {
  79272. if (impostor.physicsBody) {
  79273. this.removePhysicsBody(impostor);
  79274. //TODO is that needed?
  79275. impostor.forceUpdate();
  79276. }
  79277. return;
  79278. }
  79279. if (impostor.isBodyInitRequired()) {
  79280. var bodyConfig = {
  79281. name: impostor.uniqueId,
  79282. //Oimo must have mass, also for static objects.
  79283. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  79284. size: [],
  79285. type: [],
  79286. pos: [],
  79287. posShape: [],
  79288. rot: [],
  79289. rotShape: [],
  79290. move: impostor.getParam("mass") !== 0,
  79291. density: impostor.getParam("mass"),
  79292. friction: impostor.getParam("friction"),
  79293. restitution: impostor.getParam("restitution"),
  79294. //Supporting older versions of Oimo
  79295. world: this.world
  79296. };
  79297. var impostors = [impostor];
  79298. var addToArray = function (parent) {
  79299. if (!parent.getChildMeshes)
  79300. return;
  79301. parent.getChildMeshes().forEach(function (m) {
  79302. if (m.physicsImpostor) {
  79303. impostors.push(m.physicsImpostor);
  79304. //m.physicsImpostor._init();
  79305. }
  79306. });
  79307. };
  79308. addToArray(impostor.object);
  79309. var checkWithEpsilon_1 = function (value) {
  79310. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  79311. };
  79312. impostors.forEach(function (i) {
  79313. if (!i.object.rotationQuaternion) {
  79314. return;
  79315. }
  79316. //get the correct bounding box
  79317. var oldQuaternion = i.object.rotationQuaternion;
  79318. var rot = oldQuaternion.toEulerAngles();
  79319. var extendSize = i.getObjectExtendSize();
  79320. var radToDeg = 57.295779513082320876;
  79321. if (i === impostor) {
  79322. var center = impostor.getObjectCenter();
  79323. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  79324. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  79325. //Can also use Array.prototype.push.apply
  79326. bodyConfig.pos.push(center.x);
  79327. bodyConfig.pos.push(center.y);
  79328. bodyConfig.pos.push(center.z);
  79329. bodyConfig.posShape.push(0, 0, 0);
  79330. //tmp solution
  79331. bodyConfig.rot.push(rot.x * radToDeg);
  79332. bodyConfig.rot.push(rot.y * radToDeg);
  79333. bodyConfig.rot.push(rot.z * radToDeg);
  79334. bodyConfig.rotShape.push(0, 0, 0);
  79335. }
  79336. else {
  79337. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  79338. bodyConfig.posShape.push(localPosition.x);
  79339. bodyConfig.posShape.push(localPosition.y);
  79340. bodyConfig.posShape.push(localPosition.z);
  79341. bodyConfig.pos.push(0, 0, 0);
  79342. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  79343. bodyConfig.rot.push(0);
  79344. bodyConfig.rot.push(0);
  79345. bodyConfig.rot.push(0);
  79346. bodyConfig.rotShape.push(rot.x * radToDeg);
  79347. bodyConfig.rotShape.push(rot.y * radToDeg);
  79348. bodyConfig.rotShape.push(rot.z * radToDeg);
  79349. }
  79350. // register mesh
  79351. switch (i.type) {
  79352. case BABYLON.PhysicsImpostor.ParticleImpostor:
  79353. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  79354. case BABYLON.PhysicsImpostor.SphereImpostor:
  79355. var radiusX = extendSize.x;
  79356. var radiusY = extendSize.y;
  79357. var radiusZ = extendSize.z;
  79358. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  79359. bodyConfig.type.push('sphere');
  79360. //due to the way oimo works with compounds, add 3 times
  79361. bodyConfig.size.push(size);
  79362. bodyConfig.size.push(size);
  79363. bodyConfig.size.push(size);
  79364. break;
  79365. case BABYLON.PhysicsImpostor.CylinderImpostor:
  79366. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  79367. var sizeY = checkWithEpsilon_1(extendSize.y);
  79368. bodyConfig.type.push('cylinder');
  79369. bodyConfig.size.push(sizeX);
  79370. bodyConfig.size.push(sizeY);
  79371. //due to the way oimo works with compounds, add one more value.
  79372. bodyConfig.size.push(sizeY);
  79373. break;
  79374. case BABYLON.PhysicsImpostor.PlaneImpostor:
  79375. case BABYLON.PhysicsImpostor.BoxImpostor:
  79376. default:
  79377. var sizeX = checkWithEpsilon_1(extendSize.x);
  79378. var sizeY = checkWithEpsilon_1(extendSize.y);
  79379. var sizeZ = checkWithEpsilon_1(extendSize.z);
  79380. bodyConfig.type.push('box');
  79381. //if (i === impostor) {
  79382. bodyConfig.size.push(sizeX);
  79383. bodyConfig.size.push(sizeY);
  79384. bodyConfig.size.push(sizeZ);
  79385. //} else {
  79386. // bodyConfig.size.push(0,0,0);
  79387. //}
  79388. break;
  79389. }
  79390. //actually not needed, but hey...
  79391. i.object.rotationQuaternion = oldQuaternion;
  79392. });
  79393. impostor.physicsBody = this.world.add(bodyConfig);
  79394. }
  79395. else {
  79396. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  79397. }
  79398. impostor.setDeltaPosition(this._tmpPositionVector);
  79399. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  79400. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  79401. };
  79402. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  79403. //impostor.physicsBody.dispose();
  79404. //Same as : (older oimo versions)
  79405. this.world.removeRigidBody(impostor.physicsBody);
  79406. };
  79407. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  79408. var mainBody = impostorJoint.mainImpostor.physicsBody;
  79409. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  79410. if (!mainBody || !connectedBody) {
  79411. return;
  79412. }
  79413. var jointData = impostorJoint.joint.jointData;
  79414. var options = jointData.nativeParams || {};
  79415. var type;
  79416. var nativeJointData = {
  79417. body1: mainBody,
  79418. body2: connectedBody,
  79419. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  79420. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  79421. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  79422. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  79423. min: options.min,
  79424. max: options.max,
  79425. collision: options.collision || jointData.collision,
  79426. spring: options.spring,
  79427. //supporting older version of Oimo
  79428. world: this.world
  79429. };
  79430. switch (impostorJoint.joint.type) {
  79431. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  79432. type = "jointBall";
  79433. break;
  79434. case BABYLON.PhysicsJoint.SpringJoint:
  79435. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  79436. var springData = jointData;
  79437. nativeJointData.min = springData.length || nativeJointData.min;
  79438. //Max should also be set, just make sure it is at least min
  79439. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  79440. case BABYLON.PhysicsJoint.DistanceJoint:
  79441. type = "jointDistance";
  79442. nativeJointData.max = jointData.maxDistance;
  79443. break;
  79444. case BABYLON.PhysicsJoint.PrismaticJoint:
  79445. type = "jointPrisme";
  79446. break;
  79447. case BABYLON.PhysicsJoint.SliderJoint:
  79448. type = "jointSlide";
  79449. break;
  79450. case BABYLON.PhysicsJoint.WheelJoint:
  79451. type = "jointWheel";
  79452. break;
  79453. case BABYLON.PhysicsJoint.HingeJoint:
  79454. default:
  79455. type = "jointHinge";
  79456. break;
  79457. }
  79458. nativeJointData.type = type;
  79459. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  79460. };
  79461. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  79462. //Bug in Oimo prevents us from disposing a joint in the playground
  79463. //joint.joint.physicsJoint.dispose();
  79464. //So we will bruteforce it!
  79465. try {
  79466. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  79467. }
  79468. catch (e) {
  79469. BABYLON.Tools.Warn(e);
  79470. }
  79471. };
  79472. OimoJSPlugin.prototype.isSupported = function () {
  79473. return this.BJSOIMO !== undefined;
  79474. };
  79475. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79476. if (!impostor.physicsBody.sleeping) {
  79477. //TODO check that
  79478. /*if (impostor.physicsBody.shapes.next) {
  79479. var parentShape = this._getLastShape(impostor.physicsBody);
  79480. impostor.object.position.copyFrom(parentShape.position);
  79481. console.log(parentShape.position);
  79482. } else {*/
  79483. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  79484. //}
  79485. if (impostor.object.rotationQuaternion) {
  79486. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  79487. }
  79488. }
  79489. };
  79490. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79491. var body = impostor.physicsBody;
  79492. body.position.copy(newPosition);
  79493. body.orientation.copy(newRotation);
  79494. body.syncShapes();
  79495. body.awake();
  79496. };
  79497. /*private _getLastShape(body: any): any {
  79498. var lastShape = body.shapes;
  79499. while (lastShape.next) {
  79500. lastShape = lastShape.next;
  79501. }
  79502. return lastShape;
  79503. }*/
  79504. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79505. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  79506. };
  79507. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79508. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  79509. };
  79510. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79511. var v = impostor.physicsBody.linearVelocity;
  79512. if (!v) {
  79513. return null;
  79514. }
  79515. return new BABYLON.Vector3(v.x, v.y, v.z);
  79516. };
  79517. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79518. var v = impostor.physicsBody.angularVelocity;
  79519. if (!v) {
  79520. return null;
  79521. }
  79522. return new BABYLON.Vector3(v.x, v.y, v.z);
  79523. };
  79524. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79525. var staticBody = mass === 0;
  79526. //this will actually set the body's density and not its mass.
  79527. //But this is how oimo treats the mass variable.
  79528. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  79529. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  79530. };
  79531. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  79532. return impostor.physicsBody.shapes.density;
  79533. };
  79534. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  79535. return impostor.physicsBody.shapes.friction;
  79536. };
  79537. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79538. impostor.physicsBody.shapes.friction = friction;
  79539. };
  79540. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79541. return impostor.physicsBody.shapes.restitution;
  79542. };
  79543. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79544. impostor.physicsBody.shapes.restitution = restitution;
  79545. };
  79546. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  79547. impostor.physicsBody.sleep();
  79548. };
  79549. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  79550. impostor.physicsBody.awake();
  79551. };
  79552. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79553. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  79554. if (minDistance !== void 0) {
  79555. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  79556. }
  79557. };
  79558. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79559. //TODO separate rotational and transational motors.
  79560. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79561. if (motor) {
  79562. motor.setMotor(speed, maxForce);
  79563. }
  79564. };
  79565. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  79566. //TODO separate rotational and transational motors.
  79567. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79568. if (motor) {
  79569. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  79570. }
  79571. };
  79572. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79573. var body = impostor.physicsBody;
  79574. mesh.position.x = body.position.x;
  79575. mesh.position.y = body.position.y;
  79576. mesh.position.z = body.position.z;
  79577. if (mesh.rotationQuaternion) {
  79578. mesh.rotationQuaternion.x = body.orientation.x;
  79579. mesh.rotationQuaternion.y = body.orientation.y;
  79580. mesh.rotationQuaternion.z = body.orientation.z;
  79581. mesh.rotationQuaternion.w = body.orientation.s;
  79582. }
  79583. };
  79584. OimoJSPlugin.prototype.getRadius = function (impostor) {
  79585. return impostor.physicsBody.shapes.radius;
  79586. };
  79587. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79588. var shape = impostor.physicsBody.shapes;
  79589. result.x = shape.halfWidth * 2;
  79590. result.y = shape.halfHeight * 2;
  79591. result.z = shape.halfDepth * 2;
  79592. };
  79593. OimoJSPlugin.prototype.dispose = function () {
  79594. this.world.clear();
  79595. };
  79596. return OimoJSPlugin;
  79597. }());
  79598. BABYLON.OimoJSPlugin = OimoJSPlugin;
  79599. })(BABYLON || (BABYLON = {}));
  79600. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  79601. "use strict";
  79602. var BABYLON;
  79603. (function (BABYLON) {
  79604. /*
  79605. * Based on jsTGALoader - Javascript loader for TGA file
  79606. * By Vincent Thibault
  79607. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  79608. */
  79609. var TGATools = /** @class */ (function () {
  79610. function TGATools() {
  79611. }
  79612. TGATools.GetTGAHeader = function (data) {
  79613. var offset = 0;
  79614. var header = {
  79615. id_length: data[offset++],
  79616. colormap_type: data[offset++],
  79617. image_type: data[offset++],
  79618. colormap_index: data[offset++] | data[offset++] << 8,
  79619. colormap_length: data[offset++] | data[offset++] << 8,
  79620. colormap_size: data[offset++],
  79621. origin: [
  79622. data[offset++] | data[offset++] << 8,
  79623. data[offset++] | data[offset++] << 8
  79624. ],
  79625. width: data[offset++] | data[offset++] << 8,
  79626. height: data[offset++] | data[offset++] << 8,
  79627. pixel_size: data[offset++],
  79628. flags: data[offset++]
  79629. };
  79630. return header;
  79631. };
  79632. TGATools.UploadContent = function (gl, data) {
  79633. // Not enough data to contain header ?
  79634. if (data.length < 19) {
  79635. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  79636. return;
  79637. }
  79638. // Read Header
  79639. var offset = 18;
  79640. var header = TGATools.GetTGAHeader(data);
  79641. // Assume it's a valid Targa file.
  79642. if (header.id_length + offset > data.length) {
  79643. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  79644. return;
  79645. }
  79646. // Skip not needed data
  79647. offset += header.id_length;
  79648. var use_rle = false;
  79649. var use_pal = false;
  79650. var use_grey = false;
  79651. // Get some informations.
  79652. switch (header.image_type) {
  79653. case TGATools._TYPE_RLE_INDEXED:
  79654. use_rle = true;
  79655. case TGATools._TYPE_INDEXED:
  79656. use_pal = true;
  79657. break;
  79658. case TGATools._TYPE_RLE_RGB:
  79659. use_rle = true;
  79660. case TGATools._TYPE_RGB:
  79661. // use_rgb = true;
  79662. break;
  79663. case TGATools._TYPE_RLE_GREY:
  79664. use_rle = true;
  79665. case TGATools._TYPE_GREY:
  79666. use_grey = true;
  79667. break;
  79668. }
  79669. var pixel_data;
  79670. // var numAlphaBits = header.flags & 0xf;
  79671. var pixel_size = header.pixel_size >> 3;
  79672. var pixel_total = header.width * header.height * pixel_size;
  79673. // Read palettes
  79674. var palettes;
  79675. if (use_pal) {
  79676. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  79677. }
  79678. // Read LRE
  79679. if (use_rle) {
  79680. pixel_data = new Uint8Array(pixel_total);
  79681. var c, count, i;
  79682. var localOffset = 0;
  79683. var pixels = new Uint8Array(pixel_size);
  79684. while (offset < pixel_total && localOffset < pixel_total) {
  79685. c = data[offset++];
  79686. count = (c & 0x7f) + 1;
  79687. // RLE pixels
  79688. if (c & 0x80) {
  79689. // Bind pixel tmp array
  79690. for (i = 0; i < pixel_size; ++i) {
  79691. pixels[i] = data[offset++];
  79692. }
  79693. // Copy pixel array
  79694. for (i = 0; i < count; ++i) {
  79695. pixel_data.set(pixels, localOffset + i * pixel_size);
  79696. }
  79697. localOffset += pixel_size * count;
  79698. }
  79699. else {
  79700. count *= pixel_size;
  79701. for (i = 0; i < count; ++i) {
  79702. pixel_data[localOffset + i] = data[offset++];
  79703. }
  79704. localOffset += count;
  79705. }
  79706. }
  79707. }
  79708. else {
  79709. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  79710. }
  79711. // Load to texture
  79712. var x_start, y_start, x_step, y_step, y_end, x_end;
  79713. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  79714. default:
  79715. case TGATools._ORIGIN_UL:
  79716. x_start = 0;
  79717. x_step = 1;
  79718. x_end = header.width;
  79719. y_start = 0;
  79720. y_step = 1;
  79721. y_end = header.height;
  79722. break;
  79723. case TGATools._ORIGIN_BL:
  79724. x_start = 0;
  79725. x_step = 1;
  79726. x_end = header.width;
  79727. y_start = header.height - 1;
  79728. y_step = -1;
  79729. y_end = -1;
  79730. break;
  79731. case TGATools._ORIGIN_UR:
  79732. x_start = header.width - 1;
  79733. x_step = -1;
  79734. x_end = -1;
  79735. y_start = 0;
  79736. y_step = 1;
  79737. y_end = header.height;
  79738. break;
  79739. case TGATools._ORIGIN_BR:
  79740. x_start = header.width - 1;
  79741. x_step = -1;
  79742. x_end = -1;
  79743. y_start = header.height - 1;
  79744. y_step = -1;
  79745. y_end = -1;
  79746. break;
  79747. }
  79748. // Load the specify method
  79749. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  79750. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  79751. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  79752. };
  79753. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79754. var image = pixel_data, colormap = palettes;
  79755. var width = header.width, height = header.height;
  79756. var color, i = 0, x, y;
  79757. var imageData = new Uint8Array(width * height * 4);
  79758. for (y = y_start; y !== y_end; y += y_step) {
  79759. for (x = x_start; x !== x_end; x += x_step, i++) {
  79760. color = image[i];
  79761. imageData[(x + width * y) * 4 + 3] = 255;
  79762. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  79763. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  79764. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  79765. }
  79766. }
  79767. return imageData;
  79768. };
  79769. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79770. var image = pixel_data;
  79771. var width = header.width, height = header.height;
  79772. var color, i = 0, x, y;
  79773. var imageData = new Uint8Array(width * height * 4);
  79774. for (y = y_start; y !== y_end; y += y_step) {
  79775. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79776. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  79777. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  79778. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  79779. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  79780. imageData[(x + width * y) * 4 + 0] = r;
  79781. imageData[(x + width * y) * 4 + 1] = g;
  79782. imageData[(x + width * y) * 4 + 2] = b;
  79783. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  79784. }
  79785. }
  79786. return imageData;
  79787. };
  79788. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79789. var image = pixel_data;
  79790. var width = header.width, height = header.height;
  79791. var i = 0, x, y;
  79792. var imageData = new Uint8Array(width * height * 4);
  79793. for (y = y_start; y !== y_end; y += y_step) {
  79794. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  79795. imageData[(x + width * y) * 4 + 3] = 255;
  79796. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79797. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79798. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79799. }
  79800. }
  79801. return imageData;
  79802. };
  79803. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79804. var image = pixel_data;
  79805. var width = header.width, height = header.height;
  79806. var i = 0, x, y;
  79807. var imageData = new Uint8Array(width * height * 4);
  79808. for (y = y_start; y !== y_end; y += y_step) {
  79809. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  79810. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79811. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79812. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79813. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  79814. }
  79815. }
  79816. return imageData;
  79817. };
  79818. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79819. var image = pixel_data;
  79820. var width = header.width, height = header.height;
  79821. var color, i = 0, x, y;
  79822. var imageData = new Uint8Array(width * height * 4);
  79823. for (y = y_start; y !== y_end; y += y_step) {
  79824. for (x = x_start; x !== x_end; x += x_step, i++) {
  79825. color = image[i];
  79826. imageData[(x + width * y) * 4 + 0] = color;
  79827. imageData[(x + width * y) * 4 + 1] = color;
  79828. imageData[(x + width * y) * 4 + 2] = color;
  79829. imageData[(x + width * y) * 4 + 3] = 255;
  79830. }
  79831. }
  79832. return imageData;
  79833. };
  79834. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79835. var image = pixel_data;
  79836. var width = header.width, height = header.height;
  79837. var i = 0, x, y;
  79838. var imageData = new Uint8Array(width * height * 4);
  79839. for (y = y_start; y !== y_end; y += y_step) {
  79840. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79841. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  79842. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  79843. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79844. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  79845. }
  79846. }
  79847. return imageData;
  79848. };
  79849. //private static _TYPE_NO_DATA = 0;
  79850. TGATools._TYPE_INDEXED = 1;
  79851. TGATools._TYPE_RGB = 2;
  79852. TGATools._TYPE_GREY = 3;
  79853. TGATools._TYPE_RLE_INDEXED = 9;
  79854. TGATools._TYPE_RLE_RGB = 10;
  79855. TGATools._TYPE_RLE_GREY = 11;
  79856. TGATools._ORIGIN_MASK = 0x30;
  79857. TGATools._ORIGIN_SHIFT = 0x04;
  79858. TGATools._ORIGIN_BL = 0x00;
  79859. TGATools._ORIGIN_BR = 0x01;
  79860. TGATools._ORIGIN_UL = 0x02;
  79861. TGATools._ORIGIN_UR = 0x03;
  79862. return TGATools;
  79863. }());
  79864. BABYLON.TGATools = TGATools;
  79865. })(BABYLON || (BABYLON = {}));
  79866. //# sourceMappingURL=babylon.tga.js.map
  79867. "use strict";
  79868. var BABYLON;
  79869. (function (BABYLON) {
  79870. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  79871. // All values and structures referenced from:
  79872. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  79873. var DDS_MAGIC = 0x20534444;
  79874. var
  79875. //DDSD_CAPS = 0x1,
  79876. //DDSD_HEIGHT = 0x2,
  79877. //DDSD_WIDTH = 0x4,
  79878. //DDSD_PITCH = 0x8,
  79879. //DDSD_PIXELFORMAT = 0x1000,
  79880. DDSD_MIPMAPCOUNT = 0x20000;
  79881. //DDSD_LINEARSIZE = 0x80000,
  79882. //DDSD_DEPTH = 0x800000;
  79883. // var DDSCAPS_COMPLEX = 0x8,
  79884. // DDSCAPS_MIPMAP = 0x400000,
  79885. // DDSCAPS_TEXTURE = 0x1000;
  79886. var DDSCAPS2_CUBEMAP = 0x200;
  79887. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  79888. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  79889. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  79890. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  79891. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  79892. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  79893. // DDSCAPS2_VOLUME = 0x200000;
  79894. var
  79895. //DDPF_ALPHAPIXELS = 0x1,
  79896. //DDPF_ALPHA = 0x2,
  79897. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  79898. //DDPF_YUV = 0x200,
  79899. DDPF_LUMINANCE = 0x20000;
  79900. function FourCCToInt32(value) {
  79901. return value.charCodeAt(0) +
  79902. (value.charCodeAt(1) << 8) +
  79903. (value.charCodeAt(2) << 16) +
  79904. (value.charCodeAt(3) << 24);
  79905. }
  79906. function Int32ToFourCC(value) {
  79907. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  79908. }
  79909. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  79910. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  79911. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  79912. var FOURCC_DX10 = FourCCToInt32("DX10");
  79913. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  79914. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  79915. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  79916. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  79917. var headerLengthInt = 31; // The header length in 32 bit ints
  79918. // Offsets into the header array
  79919. var off_magic = 0;
  79920. var off_size = 1;
  79921. var off_flags = 2;
  79922. var off_height = 3;
  79923. var off_width = 4;
  79924. var off_mipmapCount = 7;
  79925. var off_pfFlags = 20;
  79926. var off_pfFourCC = 21;
  79927. var off_RGBbpp = 22;
  79928. var off_RMask = 23;
  79929. var off_GMask = 24;
  79930. var off_BMask = 25;
  79931. var off_AMask = 26;
  79932. // var off_caps1 = 27;
  79933. var off_caps2 = 28;
  79934. // var off_caps3 = 29;
  79935. // var off_caps4 = 30;
  79936. var off_dxgiFormat = 32;
  79937. ;
  79938. var DDSTools = /** @class */ (function () {
  79939. function DDSTools() {
  79940. }
  79941. DDSTools.GetDDSInfo = function (arrayBuffer) {
  79942. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79943. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  79944. var mipmapCount = 1;
  79945. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  79946. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79947. }
  79948. var fourCC = header[off_pfFourCC];
  79949. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  79950. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79951. switch (fourCC) {
  79952. case FOURCC_D3DFMT_R16G16B16A16F:
  79953. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79954. break;
  79955. case FOURCC_D3DFMT_R32G32B32A32F:
  79956. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79957. break;
  79958. case FOURCC_DX10:
  79959. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  79960. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79961. break;
  79962. }
  79963. }
  79964. return {
  79965. width: header[off_width],
  79966. height: header[off_height],
  79967. mipmapCount: mipmapCount,
  79968. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  79969. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  79970. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  79971. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  79972. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  79973. dxgiFormat: dxgiFormat,
  79974. textureType: textureType
  79975. };
  79976. };
  79977. DDSTools._ToHalfFloat = function (value) {
  79978. if (!DDSTools._FloatView) {
  79979. DDSTools._FloatView = new Float32Array(1);
  79980. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  79981. }
  79982. DDSTools._FloatView[0] = value;
  79983. var x = DDSTools._Int32View[0];
  79984. var bits = (x >> 16) & 0x8000; /* Get the sign */
  79985. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  79986. var e = (x >> 23) & 0xff; /* Using int is faster here */
  79987. /* If zero, or denormal, or exponent underflows too much for a denormal
  79988. * half, return signed zero. */
  79989. if (e < 103) {
  79990. return bits;
  79991. }
  79992. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  79993. if (e > 142) {
  79994. bits |= 0x7c00;
  79995. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  79996. * not Inf, so make sure we set one mantissa bit too. */
  79997. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  79998. return bits;
  79999. }
  80000. /* If exponent underflows but not too much, return a denormal */
  80001. if (e < 113) {
  80002. m |= 0x0800;
  80003. /* Extra rounding may overflow and set mantissa to 0 and exponent
  80004. * to 1, which is OK. */
  80005. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  80006. return bits;
  80007. }
  80008. bits |= ((e - 112) << 10) | (m >> 1);
  80009. bits += m & 1;
  80010. return bits;
  80011. };
  80012. DDSTools._FromHalfFloat = function (value) {
  80013. var s = (value & 0x8000) >> 15;
  80014. var e = (value & 0x7C00) >> 10;
  80015. var f = value & 0x03FF;
  80016. if (e === 0) {
  80017. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  80018. }
  80019. else if (e == 0x1F) {
  80020. return f ? NaN : ((s ? -1 : 1) * Infinity);
  80021. }
  80022. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  80023. };
  80024. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80025. var destArray = new Float32Array(dataLength);
  80026. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80027. var index = 0;
  80028. for (var y = 0; y < height; y++) {
  80029. for (var x = 0; x < width; x++) {
  80030. var srcPos = (x + y * width) * 4;
  80031. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  80032. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  80033. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  80034. if (DDSTools.StoreLODInAlphaChannel) {
  80035. destArray[index + 3] = lod;
  80036. }
  80037. else {
  80038. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  80039. }
  80040. index += 4;
  80041. }
  80042. }
  80043. return destArray;
  80044. };
  80045. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80046. if (DDSTools.StoreLODInAlphaChannel) {
  80047. var destArray = new Uint16Array(dataLength);
  80048. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80049. var index = 0;
  80050. for (var y = 0; y < height; y++) {
  80051. for (var x = 0; x < width; x++) {
  80052. var srcPos = (x + y * width) * 4;
  80053. destArray[index] = srcData[srcPos];
  80054. destArray[index + 1] = srcData[srcPos + 1];
  80055. destArray[index + 2] = srcData[srcPos + 2];
  80056. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  80057. index += 4;
  80058. }
  80059. }
  80060. return destArray;
  80061. }
  80062. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  80063. };
  80064. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80065. if (DDSTools.StoreLODInAlphaChannel) {
  80066. var destArray = new Float32Array(dataLength);
  80067. var srcData = new Float32Array(arrayBuffer, dataOffset);
  80068. var index = 0;
  80069. for (var y = 0; y < height; y++) {
  80070. for (var x = 0; x < width; x++) {
  80071. var srcPos = (x + y * width) * 4;
  80072. destArray[index] = srcData[srcPos];
  80073. destArray[index + 1] = srcData[srcPos + 1];
  80074. destArray[index + 2] = srcData[srcPos + 2];
  80075. destArray[index + 3] = lod;
  80076. index += 4;
  80077. }
  80078. }
  80079. return destArray;
  80080. }
  80081. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  80082. };
  80083. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80084. var destArray = new Uint8Array(dataLength);
  80085. var srcData = new Float32Array(arrayBuffer, dataOffset);
  80086. var index = 0;
  80087. for (var y = 0; y < height; y++) {
  80088. for (var x = 0; x < width; x++) {
  80089. var srcPos = (x + y * width) * 4;
  80090. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  80091. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  80092. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  80093. if (DDSTools.StoreLODInAlphaChannel) {
  80094. destArray[index + 3] = lod;
  80095. }
  80096. else {
  80097. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  80098. }
  80099. index += 4;
  80100. }
  80101. }
  80102. return destArray;
  80103. };
  80104. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80105. var destArray = new Uint8Array(dataLength);
  80106. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80107. var index = 0;
  80108. for (var y = 0; y < height; y++) {
  80109. for (var x = 0; x < width; x++) {
  80110. var srcPos = (x + y * width) * 4;
  80111. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  80112. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  80113. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  80114. if (DDSTools.StoreLODInAlphaChannel) {
  80115. destArray[index + 3] = lod;
  80116. }
  80117. else {
  80118. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  80119. }
  80120. index += 4;
  80121. }
  80122. }
  80123. return destArray;
  80124. };
  80125. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  80126. var byteArray = new Uint8Array(dataLength);
  80127. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80128. var index = 0;
  80129. for (var y = 0; y < height; y++) {
  80130. for (var x = 0; x < width; x++) {
  80131. var srcPos = (x + y * width) * 4;
  80132. byteArray[index] = srcData[srcPos + rOffset];
  80133. byteArray[index + 1] = srcData[srcPos + gOffset];
  80134. byteArray[index + 2] = srcData[srcPos + bOffset];
  80135. byteArray[index + 3] = srcData[srcPos + aOffset];
  80136. index += 4;
  80137. }
  80138. }
  80139. return byteArray;
  80140. };
  80141. DDSTools._ExtractLongWordOrder = function (value) {
  80142. if (value === 0 || value === 255 || value === -16777216) {
  80143. return 0;
  80144. }
  80145. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  80146. };
  80147. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  80148. var byteArray = new Uint8Array(dataLength);
  80149. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80150. var index = 0;
  80151. for (var y = 0; y < height; y++) {
  80152. for (var x = 0; x < width; x++) {
  80153. var srcPos = (x + y * width) * 3;
  80154. byteArray[index] = srcData[srcPos + rOffset];
  80155. byteArray[index + 1] = srcData[srcPos + gOffset];
  80156. byteArray[index + 2] = srcData[srcPos + bOffset];
  80157. index += 3;
  80158. }
  80159. }
  80160. return byteArray;
  80161. };
  80162. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  80163. var byteArray = new Uint8Array(dataLength);
  80164. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80165. var index = 0;
  80166. for (var y = 0; y < height; y++) {
  80167. for (var x = 0; x < width; x++) {
  80168. var srcPos = (x + y * width);
  80169. byteArray[index] = srcData[srcPos];
  80170. index++;
  80171. }
  80172. }
  80173. return byteArray;
  80174. };
  80175. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  80176. if (lodIndex === void 0) { lodIndex = -1; }
  80177. var ext = engine.getCaps().s3tc;
  80178. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  80179. var fourCC, width, height, dataLength = 0, dataOffset;
  80180. var byteArray, mipmapCount, mip;
  80181. var internalFormat = 0;
  80182. var format = 0;
  80183. var blockBytes = 1;
  80184. if (header[off_magic] !== DDS_MAGIC) {
  80185. BABYLON.Tools.Error("Invalid magic number in DDS header");
  80186. return;
  80187. }
  80188. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  80189. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  80190. return;
  80191. }
  80192. if (info.isCompressed && !ext) {
  80193. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  80194. return;
  80195. }
  80196. var bpp = header[off_RGBbpp];
  80197. dataOffset = header[off_size] + 4;
  80198. var computeFormats = false;
  80199. if (info.isFourCC) {
  80200. fourCC = header[off_pfFourCC];
  80201. switch (fourCC) {
  80202. case FOURCC_DXT1:
  80203. blockBytes = 8;
  80204. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  80205. break;
  80206. case FOURCC_DXT3:
  80207. blockBytes = 16;
  80208. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  80209. break;
  80210. case FOURCC_DXT5:
  80211. blockBytes = 16;
  80212. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  80213. break;
  80214. case FOURCC_D3DFMT_R16G16B16A16F:
  80215. computeFormats = true;
  80216. break;
  80217. case FOURCC_D3DFMT_R32G32B32A32F:
  80218. computeFormats = true;
  80219. break;
  80220. case FOURCC_DX10:
  80221. // There is an additionnal header so dataOffset need to be changed
  80222. dataOffset += 5 * 4; // 5 uints
  80223. var supported = false;
  80224. switch (info.dxgiFormat) {
  80225. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  80226. computeFormats = true;
  80227. supported = true;
  80228. break;
  80229. case DXGI_FORMAT_B8G8R8X8_UNORM:
  80230. info.isRGB = true;
  80231. info.isFourCC = false;
  80232. bpp = 32;
  80233. supported = true;
  80234. break;
  80235. }
  80236. if (supported) {
  80237. break;
  80238. }
  80239. default:
  80240. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  80241. return;
  80242. }
  80243. }
  80244. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  80245. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  80246. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  80247. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  80248. if (computeFormats) {
  80249. format = engine._getWebGLTextureType(info.textureType);
  80250. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80251. }
  80252. mipmapCount = 1;
  80253. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  80254. mipmapCount = Math.max(1, header[off_mipmapCount]);
  80255. }
  80256. for (var face = 0; face < faces; face++) {
  80257. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  80258. width = header[off_width];
  80259. height = header[off_height];
  80260. for (mip = 0; mip < mipmapCount; ++mip) {
  80261. if (lodIndex === -1 || lodIndex === mip) {
  80262. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  80263. var i = (lodIndex === -1) ? mip : 0;
  80264. if (!info.isCompressed && info.isFourCC) {
  80265. dataLength = width * height * 4;
  80266. var floatArray = null;
  80267. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  80268. if (bpp === 128) {
  80269. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80270. }
  80271. else if (bpp === 64) {
  80272. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80273. }
  80274. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80275. format = engine._getWebGLTextureType(info.textureType);
  80276. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80277. }
  80278. else {
  80279. if (bpp === 128) {
  80280. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80281. }
  80282. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  80283. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80284. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80285. format = engine._getWebGLTextureType(info.textureType);
  80286. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80287. }
  80288. else {
  80289. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80290. }
  80291. }
  80292. if (floatArray) {
  80293. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  80294. }
  80295. }
  80296. else if (info.isRGB) {
  80297. if (bpp === 24) {
  80298. dataLength = width * height * 3;
  80299. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  80300. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  80301. }
  80302. else {
  80303. dataLength = width * height * 4;
  80304. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  80305. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  80306. }
  80307. }
  80308. else if (info.isLuminance) {
  80309. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  80310. var unpaddedRowSize = width;
  80311. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  80312. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  80313. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  80314. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  80315. }
  80316. else {
  80317. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  80318. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  80319. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  80320. }
  80321. }
  80322. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  80323. width *= 0.5;
  80324. height *= 0.5;
  80325. width = Math.max(1.0, width);
  80326. height = Math.max(1.0, height);
  80327. }
  80328. if (currentFace !== undefined) {
  80329. // Loading a single face
  80330. break;
  80331. }
  80332. }
  80333. };
  80334. DDSTools.StoreLODInAlphaChannel = false;
  80335. return DDSTools;
  80336. }());
  80337. BABYLON.DDSTools = DDSTools;
  80338. })(BABYLON || (BABYLON = {}));
  80339. //# sourceMappingURL=babylon.dds.js.map
  80340. "use strict";
  80341. var BABYLON;
  80342. (function (BABYLON) {
  80343. /**
  80344. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  80345. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  80346. */
  80347. var KhronosTextureContainer = /** @class */ (function () {
  80348. /**
  80349. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  80350. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  80351. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  80352. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  80353. */
  80354. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  80355. this.arrayBuffer = arrayBuffer;
  80356. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  80357. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  80358. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  80359. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  80360. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  80361. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  80362. BABYLON.Tools.Error("texture missing KTX identifier");
  80363. return;
  80364. }
  80365. // load the reset of the header in native 32 bit int
  80366. var header = new Int32Array(this.arrayBuffer, 12, 13);
  80367. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  80368. var oppositeEndianess = header[0] === 0x01020304;
  80369. // read all the header elements in order they exist in the file, without modification (sans endainness)
  80370. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  80371. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  80372. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  80373. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  80374. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  80375. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  80376. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  80377. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  80378. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  80379. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  80380. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  80381. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  80382. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  80383. if (this.glType !== 0) {
  80384. BABYLON.Tools.Error("only compressed formats currently supported");
  80385. return;
  80386. }
  80387. else {
  80388. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  80389. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  80390. }
  80391. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  80392. BABYLON.Tools.Error("only 2D textures currently supported");
  80393. return;
  80394. }
  80395. if (this.numberOfArrayElements !== 0) {
  80396. BABYLON.Tools.Error("texture arrays not currently supported");
  80397. return;
  80398. }
  80399. if (this.numberOfFaces !== facesExpected) {
  80400. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  80401. return;
  80402. }
  80403. // we now have a completely validated file, so could use existence of loadType as success
  80404. // would need to make this more elaborate & adjust checks above to support more than one load type
  80405. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  80406. }
  80407. // not as fast hardware based, but will probably never need to use
  80408. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  80409. return ((val & 0xFF) << 24)
  80410. | ((val & 0xFF00) << 8)
  80411. | ((val >> 8) & 0xFF00)
  80412. | ((val >> 24) & 0xFF);
  80413. };
  80414. /**
  80415. * It is assumed that the texture has already been created & is currently bound
  80416. */
  80417. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  80418. switch (this.loadType) {
  80419. case KhronosTextureContainer.COMPRESSED_2D:
  80420. this._upload2DCompressedLevels(gl, loadMipmaps);
  80421. break;
  80422. case KhronosTextureContainer.TEX_2D:
  80423. case KhronosTextureContainer.COMPRESSED_3D:
  80424. case KhronosTextureContainer.TEX_3D:
  80425. }
  80426. };
  80427. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  80428. // initialize width & height for level 1
  80429. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  80430. var width = this.pixelWidth;
  80431. var height = this.pixelHeight;
  80432. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  80433. for (var level = 0; level < mipmapCount; level++) {
  80434. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  80435. for (var face = 0; face < this.numberOfFaces; face++) {
  80436. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  80437. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  80438. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  80439. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  80440. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  80441. }
  80442. width = Math.max(1.0, width * 0.5);
  80443. height = Math.max(1.0, height * 0.5);
  80444. }
  80445. };
  80446. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  80447. // load types
  80448. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  80449. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  80450. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  80451. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  80452. return KhronosTextureContainer;
  80453. }());
  80454. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  80455. })(BABYLON || (BABYLON = {}));
  80456. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  80457. "use strict";
  80458. var BABYLON;
  80459. (function (BABYLON) {
  80460. var Debug = /** @class */ (function () {
  80461. function Debug() {
  80462. }
  80463. Debug.AxesViewer = /** @class */ (function () {
  80464. function AxesViewer(scene, scaleLines) {
  80465. if (scaleLines === void 0) { scaleLines = 1; }
  80466. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80467. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80468. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80469. this.scaleLines = 1;
  80470. this.scaleLines = scaleLines;
  80471. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  80472. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  80473. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  80474. this._xmesh.renderingGroupId = 2;
  80475. this._ymesh.renderingGroupId = 2;
  80476. this._zmesh.renderingGroupId = 2;
  80477. this._xmesh.material.checkReadyOnlyOnce = true;
  80478. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  80479. this._ymesh.material.checkReadyOnlyOnce = true;
  80480. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  80481. this._zmesh.material.checkReadyOnlyOnce = true;
  80482. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  80483. this.scene = scene;
  80484. }
  80485. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  80486. var scaleLines = this.scaleLines;
  80487. if (this._xmesh) {
  80488. this._xmesh.position.copyFrom(position);
  80489. }
  80490. if (this._ymesh) {
  80491. this._ymesh.position.copyFrom(position);
  80492. }
  80493. if (this._zmesh) {
  80494. this._zmesh.position.copyFrom(position);
  80495. }
  80496. var point2 = this._xline[1];
  80497. point2.x = xaxis.x * scaleLines;
  80498. point2.y = xaxis.y * scaleLines;
  80499. point2.z = xaxis.z * scaleLines;
  80500. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  80501. point2 = this._yline[1];
  80502. point2.x = yaxis.x * scaleLines;
  80503. point2.y = yaxis.y * scaleLines;
  80504. point2.z = yaxis.z * scaleLines;
  80505. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  80506. point2 = this._zline[1];
  80507. point2.x = zaxis.x * scaleLines;
  80508. point2.y = zaxis.y * scaleLines;
  80509. point2.z = zaxis.z * scaleLines;
  80510. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  80511. };
  80512. AxesViewer.prototype.dispose = function () {
  80513. if (this._xmesh) {
  80514. this._xmesh.dispose();
  80515. }
  80516. if (this._ymesh) {
  80517. this._ymesh.dispose();
  80518. }
  80519. if (this._zmesh) {
  80520. this._zmesh.dispose();
  80521. }
  80522. this._xmesh = null;
  80523. this._ymesh = null;
  80524. this._zmesh = null;
  80525. this.scene = null;
  80526. };
  80527. return AxesViewer;
  80528. }());
  80529. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  80530. __extends(BoneAxesViewer, _super);
  80531. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  80532. if (scaleLines === void 0) { scaleLines = 1; }
  80533. var _this = _super.call(this, scene, scaleLines) || this;
  80534. _this.pos = BABYLON.Vector3.Zero();
  80535. _this.xaxis = BABYLON.Vector3.Zero();
  80536. _this.yaxis = BABYLON.Vector3.Zero();
  80537. _this.zaxis = BABYLON.Vector3.Zero();
  80538. _this.mesh = mesh;
  80539. _this.bone = bone;
  80540. return _this;
  80541. }
  80542. BoneAxesViewer.prototype.update = function () {
  80543. if (!this.mesh || !this.bone) {
  80544. return;
  80545. }
  80546. var bone = this.bone;
  80547. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  80548. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  80549. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  80550. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  80551. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  80552. };
  80553. BoneAxesViewer.prototype.dispose = function () {
  80554. if (this.mesh) {
  80555. this.mesh = null;
  80556. this.bone = null;
  80557. _super.prototype.dispose.call(this);
  80558. }
  80559. };
  80560. return BoneAxesViewer;
  80561. }(Debug.AxesViewer));
  80562. Debug.PhysicsViewer = /** @class */ (function () {
  80563. function PhysicsViewer(scene) {
  80564. this._impostors = [];
  80565. this._meshes = [];
  80566. this._numMeshes = 0;
  80567. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80568. var physicEngine = this._scene.getPhysicsEngine();
  80569. if (physicEngine) {
  80570. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  80571. }
  80572. }
  80573. PhysicsViewer.prototype._updateDebugMeshes = function () {
  80574. var plugin = this._physicsEnginePlugin;
  80575. for (var i = 0; i < this._numMeshes; i++) {
  80576. var impostor = this._impostors[i];
  80577. if (!impostor) {
  80578. continue;
  80579. }
  80580. if (impostor.isDisposed) {
  80581. this.hideImpostor(this._impostors[i--]);
  80582. }
  80583. else {
  80584. var mesh = this._meshes[i];
  80585. if (mesh && plugin) {
  80586. plugin.syncMeshWithImpostor(mesh, impostor);
  80587. }
  80588. }
  80589. }
  80590. };
  80591. PhysicsViewer.prototype.showImpostor = function (impostor) {
  80592. if (!this._scene) {
  80593. return;
  80594. }
  80595. for (var i = 0; i < this._numMeshes; i++) {
  80596. if (this._impostors[i] == impostor) {
  80597. return;
  80598. }
  80599. }
  80600. var debugMesh = this._getDebugMesh(impostor, this._scene);
  80601. if (debugMesh) {
  80602. this._impostors[this._numMeshes] = impostor;
  80603. this._meshes[this._numMeshes] = debugMesh;
  80604. if (this._numMeshes === 0) {
  80605. this._renderFunction = this._updateDebugMeshes.bind(this);
  80606. this._scene.registerBeforeRender(this._renderFunction);
  80607. }
  80608. this._numMeshes++;
  80609. }
  80610. };
  80611. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  80612. if (!impostor || !this._scene) {
  80613. return;
  80614. }
  80615. var removed = false;
  80616. for (var i = 0; i < this._numMeshes; i++) {
  80617. if (this._impostors[i] == impostor) {
  80618. var mesh = this._meshes[i];
  80619. if (!mesh) {
  80620. continue;
  80621. }
  80622. this._scene.removeMesh(mesh);
  80623. mesh.dispose();
  80624. this._numMeshes--;
  80625. if (this._numMeshes > 0) {
  80626. this._meshes[i] = this._meshes[this._numMeshes];
  80627. this._impostors[i] = this._impostors[this._numMeshes];
  80628. this._meshes[this._numMeshes] = null;
  80629. this._impostors[this._numMeshes] = null;
  80630. }
  80631. else {
  80632. this._meshes[0] = null;
  80633. this._impostors[0] = null;
  80634. }
  80635. removed = true;
  80636. break;
  80637. }
  80638. }
  80639. if (removed && this._numMeshes === 0) {
  80640. this._scene.unregisterBeforeRender(this._renderFunction);
  80641. }
  80642. };
  80643. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  80644. if (!this._debugMaterial) {
  80645. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  80646. this._debugMaterial.wireframe = true;
  80647. }
  80648. return this._debugMaterial;
  80649. };
  80650. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  80651. if (!this._debugBoxMesh) {
  80652. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  80653. this._debugBoxMesh.renderingGroupId = 1;
  80654. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80655. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  80656. scene.removeMesh(this._debugBoxMesh);
  80657. }
  80658. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  80659. };
  80660. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  80661. if (!this._debugSphereMesh) {
  80662. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  80663. this._debugSphereMesh.renderingGroupId = 1;
  80664. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80665. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  80666. scene.removeMesh(this._debugSphereMesh);
  80667. }
  80668. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  80669. };
  80670. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  80671. var mesh = null;
  80672. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  80673. mesh = this._getDebugBoxMesh(scene);
  80674. impostor.getBoxSizeToRef(mesh.scaling);
  80675. }
  80676. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  80677. mesh = this._getDebugSphereMesh(scene);
  80678. var radius = impostor.getRadius();
  80679. mesh.scaling.x = radius * 2;
  80680. mesh.scaling.y = radius * 2;
  80681. mesh.scaling.z = radius * 2;
  80682. }
  80683. return mesh;
  80684. };
  80685. PhysicsViewer.prototype.dispose = function () {
  80686. for (var i = 0; i < this._numMeshes; i++) {
  80687. this.hideImpostor(this._impostors[i]);
  80688. }
  80689. if (this._debugBoxMesh) {
  80690. this._debugBoxMesh.dispose();
  80691. }
  80692. if (this._debugSphereMesh) {
  80693. this._debugSphereMesh.dispose();
  80694. }
  80695. if (this._debugMaterial) {
  80696. this._debugMaterial.dispose();
  80697. }
  80698. this._impostors.length = 0;
  80699. this._scene = null;
  80700. this._physicsEnginePlugin = null;
  80701. };
  80702. return PhysicsViewer;
  80703. }());
  80704. Debug.SkeletonViewer = /** @class */ (function () {
  80705. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  80706. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  80707. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  80708. this.skeleton = skeleton;
  80709. this.mesh = mesh;
  80710. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  80711. this.renderingGroupId = renderingGroupId;
  80712. this.color = BABYLON.Color3.White();
  80713. this._debugLines = new Array();
  80714. this._isEnabled = false;
  80715. this._scene = scene;
  80716. this.update();
  80717. this._renderFunction = this.update.bind(this);
  80718. }
  80719. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  80720. get: function () {
  80721. return this._isEnabled;
  80722. },
  80723. set: function (value) {
  80724. if (this._isEnabled === value) {
  80725. return;
  80726. }
  80727. this._isEnabled = value;
  80728. if (value) {
  80729. this._scene.registerBeforeRender(this._renderFunction);
  80730. }
  80731. else {
  80732. this._scene.unregisterBeforeRender(this._renderFunction);
  80733. }
  80734. },
  80735. enumerable: true,
  80736. configurable: true
  80737. });
  80738. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  80739. if (x === void 0) { x = 0; }
  80740. if (y === void 0) { y = 0; }
  80741. if (z === void 0) { z = 0; }
  80742. var tmat = BABYLON.Tmp.Matrix[0];
  80743. var parentBone = bone.getParent();
  80744. tmat.copyFrom(bone.getLocalMatrix());
  80745. if (x !== 0 || y !== 0 || z !== 0) {
  80746. var tmat2 = BABYLON.Tmp.Matrix[1];
  80747. BABYLON.Matrix.IdentityToRef(tmat2);
  80748. tmat2.m[12] = x;
  80749. tmat2.m[13] = y;
  80750. tmat2.m[14] = z;
  80751. tmat2.multiplyToRef(tmat, tmat);
  80752. }
  80753. if (parentBone) {
  80754. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  80755. }
  80756. tmat.multiplyToRef(meshMat, tmat);
  80757. position.x = tmat.m[12];
  80758. position.y = tmat.m[13];
  80759. position.z = tmat.m[14];
  80760. };
  80761. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  80762. var len = bones.length;
  80763. var meshPos = this.mesh.position;
  80764. for (var i = 0; i < len; i++) {
  80765. var bone = bones[i];
  80766. var points = this._debugLines[i];
  80767. if (!points) {
  80768. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80769. this._debugLines[i] = points;
  80770. }
  80771. this._getBonePosition(points[0], bone, meshMat);
  80772. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  80773. points[0].subtractInPlace(meshPos);
  80774. points[1].subtractInPlace(meshPos);
  80775. }
  80776. };
  80777. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  80778. var len = bones.length;
  80779. var boneNum = 0;
  80780. var meshPos = this.mesh.position;
  80781. for (var i = len - 1; i >= 0; i--) {
  80782. var childBone = bones[i];
  80783. var parentBone = childBone.getParent();
  80784. if (!parentBone) {
  80785. continue;
  80786. }
  80787. var points = this._debugLines[boneNum];
  80788. if (!points) {
  80789. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80790. this._debugLines[boneNum] = points;
  80791. }
  80792. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  80793. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  80794. points[0].subtractInPlace(meshPos);
  80795. points[1].subtractInPlace(meshPos);
  80796. boneNum++;
  80797. }
  80798. };
  80799. SkeletonViewer.prototype.update = function () {
  80800. if (this.autoUpdateBonesMatrices) {
  80801. this.skeleton.computeAbsoluteTransforms();
  80802. }
  80803. if (this.skeleton.bones[0].length === undefined) {
  80804. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80805. }
  80806. else {
  80807. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80808. }
  80809. if (!this._debugMesh) {
  80810. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  80811. this._debugMesh.renderingGroupId = this.renderingGroupId;
  80812. }
  80813. else {
  80814. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  80815. }
  80816. this._debugMesh.position.copyFrom(this.mesh.position);
  80817. this._debugMesh.color = this.color;
  80818. };
  80819. SkeletonViewer.prototype.dispose = function () {
  80820. if (this._debugMesh) {
  80821. this.isEnabled = false;
  80822. this._debugMesh.dispose();
  80823. this._debugMesh = null;
  80824. }
  80825. };
  80826. return SkeletonViewer;
  80827. }());
  80828. return Debug;
  80829. }());
  80830. BABYLON.Debug = Debug;
  80831. })(BABYLON || (BABYLON = {}));
  80832. //# sourceMappingURL=babylon.debugModules.js.map
  80833. "use strict";
  80834. var BABYLON;
  80835. (function (BABYLON) {
  80836. var RayHelper = /** @class */ (function () {
  80837. function RayHelper(ray) {
  80838. this.ray = ray;
  80839. }
  80840. RayHelper.CreateAndShow = function (ray, scene, color) {
  80841. var helper = new RayHelper(ray);
  80842. helper.show(scene, color);
  80843. return helper;
  80844. };
  80845. RayHelper.prototype.show = function (scene, color) {
  80846. if (!this._renderFunction && this.ray) {
  80847. var ray = this.ray;
  80848. this._renderFunction = this._render.bind(this);
  80849. this._scene = scene;
  80850. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  80851. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  80852. if (this._renderFunction) {
  80853. this._scene.registerBeforeRender(this._renderFunction);
  80854. }
  80855. }
  80856. if (color && this._renderLine) {
  80857. this._renderLine.color.copyFrom(color);
  80858. }
  80859. };
  80860. RayHelper.prototype.hide = function () {
  80861. if (this._renderFunction && this._scene) {
  80862. this._scene.unregisterBeforeRender(this._renderFunction);
  80863. this._scene = null;
  80864. this._renderFunction = null;
  80865. if (this._renderLine) {
  80866. this._renderLine.dispose();
  80867. this._renderLine = null;
  80868. }
  80869. this._renderPoints = [];
  80870. }
  80871. };
  80872. RayHelper.prototype._render = function () {
  80873. var ray = this.ray;
  80874. if (!ray) {
  80875. return;
  80876. }
  80877. var point = this._renderPoints[1];
  80878. var len = Math.min(ray.length, 1000000);
  80879. point.copyFrom(ray.direction);
  80880. point.scaleInPlace(len);
  80881. point.addInPlace(ray.origin);
  80882. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  80883. };
  80884. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  80885. this._attachedToMesh = mesh;
  80886. var ray = this.ray;
  80887. if (!ray) {
  80888. return;
  80889. }
  80890. if (!ray.direction) {
  80891. ray.direction = BABYLON.Vector3.Zero();
  80892. }
  80893. if (!ray.origin) {
  80894. ray.origin = BABYLON.Vector3.Zero();
  80895. }
  80896. if (length) {
  80897. ray.length = length;
  80898. }
  80899. if (!meshSpaceOrigin) {
  80900. meshSpaceOrigin = BABYLON.Vector3.Zero();
  80901. }
  80902. if (!meshSpaceDirection) {
  80903. // -1 so that this will work with Mesh.lookAt
  80904. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  80905. }
  80906. if (!this._meshSpaceDirection) {
  80907. this._meshSpaceDirection = meshSpaceDirection.clone();
  80908. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  80909. }
  80910. else {
  80911. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  80912. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  80913. }
  80914. if (!this._updateToMeshFunction) {
  80915. this._updateToMeshFunction = this._updateToMesh.bind(this);
  80916. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  80917. }
  80918. this._updateToMesh();
  80919. };
  80920. RayHelper.prototype.detachFromMesh = function () {
  80921. if (this._attachedToMesh) {
  80922. if (this._updateToMeshFunction) {
  80923. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  80924. }
  80925. this._attachedToMesh = null;
  80926. this._updateToMeshFunction = null;
  80927. }
  80928. };
  80929. RayHelper.prototype._updateToMesh = function () {
  80930. var ray = this.ray;
  80931. if (!this._attachedToMesh || !ray) {
  80932. return;
  80933. }
  80934. if (this._attachedToMesh._isDisposed) {
  80935. this.detachFromMesh();
  80936. return;
  80937. }
  80938. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  80939. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  80940. };
  80941. RayHelper.prototype.dispose = function () {
  80942. this.hide();
  80943. this.detachFromMesh();
  80944. this.ray = null;
  80945. };
  80946. return RayHelper;
  80947. }());
  80948. BABYLON.RayHelper = RayHelper;
  80949. })(BABYLON || (BABYLON = {}));
  80950. //# sourceMappingURL=babylon.rayHelper.js.map
  80951. "use strict";
  80952. var BABYLON;
  80953. (function (BABYLON) {
  80954. // load the inspector using require, if not present in the global namespace.
  80955. var DebugLayer = /** @class */ (function () {
  80956. function DebugLayer(scene) {
  80957. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80958. this._scene = scene;
  80959. // load inspector using require, if it doesn't exist on the global namespace.
  80960. }
  80961. /** Creates the inspector window. */
  80962. DebugLayer.prototype._createInspector = function (config) {
  80963. if (config === void 0) { config = {}; }
  80964. var popup = config.popup || false;
  80965. var initialTab = config.initialTab || 0;
  80966. var parentElement = config.parentElement || null;
  80967. if (!this._inspector) {
  80968. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80969. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  80970. } // else nothing to do,; instance is already existing
  80971. };
  80972. DebugLayer.prototype.isVisible = function () {
  80973. if (!this._inspector) {
  80974. return false;
  80975. }
  80976. return true;
  80977. };
  80978. DebugLayer.prototype.hide = function () {
  80979. if (this._inspector) {
  80980. try {
  80981. this._inspector.dispose();
  80982. }
  80983. catch (e) {
  80984. // If the inspector has been removed directly from the inspector tool
  80985. }
  80986. this._inspector = null;
  80987. }
  80988. };
  80989. DebugLayer.prototype.show = function (config) {
  80990. if (config === void 0) { config = {}; }
  80991. if (typeof this.BJSINSPECTOR == 'undefined') {
  80992. // Load inspector and add it to the DOM
  80993. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  80994. }
  80995. else {
  80996. // Otherwise creates the inspector
  80997. this._createInspector(config);
  80998. }
  80999. };
  81000. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  81001. return DebugLayer;
  81002. }());
  81003. BABYLON.DebugLayer = DebugLayer;
  81004. })(BABYLON || (BABYLON = {}));
  81005. //# sourceMappingURL=babylon.debugLayer.js.map
  81006. "use strict";
  81007. var BABYLON;
  81008. (function (BABYLON) {
  81009. var BoundingBoxRenderer = /** @class */ (function () {
  81010. function BoundingBoxRenderer(scene) {
  81011. this.frontColor = new BABYLON.Color3(1, 1, 1);
  81012. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  81013. this.showBackLines = true;
  81014. this.renderList = new BABYLON.SmartArray(32);
  81015. this._vertexBuffers = {};
  81016. this._scene = scene;
  81017. }
  81018. BoundingBoxRenderer.prototype._prepareRessources = function () {
  81019. if (this._colorShader) {
  81020. return;
  81021. }
  81022. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  81023. attributes: [BABYLON.VertexBuffer.PositionKind],
  81024. uniforms: ["world", "viewProjection", "color"]
  81025. });
  81026. var engine = this._scene.getEngine();
  81027. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  81028. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  81029. this._createIndexBuffer();
  81030. };
  81031. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  81032. var engine = this._scene.getEngine();
  81033. 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]);
  81034. };
  81035. BoundingBoxRenderer.prototype._rebuild = function () {
  81036. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81037. if (vb) {
  81038. vb._rebuild();
  81039. }
  81040. this._createIndexBuffer();
  81041. };
  81042. BoundingBoxRenderer.prototype.reset = function () {
  81043. this.renderList.reset();
  81044. };
  81045. BoundingBoxRenderer.prototype.render = function () {
  81046. if (this.renderList.length === 0) {
  81047. return;
  81048. }
  81049. this._prepareRessources();
  81050. if (!this._colorShader.isReady()) {
  81051. return;
  81052. }
  81053. var engine = this._scene.getEngine();
  81054. engine.setDepthWrite(false);
  81055. this._colorShader._preBind();
  81056. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  81057. var boundingBox = this.renderList.data[boundingBoxIndex];
  81058. var min = boundingBox.minimum;
  81059. var max = boundingBox.maximum;
  81060. var diff = max.subtract(min);
  81061. var median = min.add(diff.scale(0.5));
  81062. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  81063. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  81064. .multiply(boundingBox.getWorldMatrix());
  81065. // VBOs
  81066. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  81067. if (this.showBackLines) {
  81068. // Back
  81069. engine.setDepthFunctionToGreaterOrEqual();
  81070. this._scene.resetCachedMaterial();
  81071. this._colorShader.setColor4("color", this.backColor.toColor4());
  81072. this._colorShader.bind(worldMatrix);
  81073. // Draw order
  81074. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81075. }
  81076. // Front
  81077. engine.setDepthFunctionToLess();
  81078. this._scene.resetCachedMaterial();
  81079. this._colorShader.setColor4("color", this.frontColor.toColor4());
  81080. this._colorShader.bind(worldMatrix);
  81081. // Draw order
  81082. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81083. }
  81084. this._colorShader.unbind();
  81085. engine.setDepthFunctionToLessOrEqual();
  81086. engine.setDepthWrite(true);
  81087. };
  81088. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  81089. this._prepareRessources();
  81090. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  81091. return;
  81092. }
  81093. var engine = this._scene.getEngine();
  81094. engine.setDepthWrite(false);
  81095. engine.setColorWrite(false);
  81096. this._colorShader._preBind();
  81097. var boundingBox = mesh._boundingInfo.boundingBox;
  81098. var min = boundingBox.minimum;
  81099. var max = boundingBox.maximum;
  81100. var diff = max.subtract(min);
  81101. var median = min.add(diff.scale(0.5));
  81102. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  81103. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  81104. .multiply(boundingBox.getWorldMatrix());
  81105. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  81106. engine.setDepthFunctionToLess();
  81107. this._scene.resetCachedMaterial();
  81108. this._colorShader.bind(worldMatrix);
  81109. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81110. this._colorShader.unbind();
  81111. engine.setDepthFunctionToLessOrEqual();
  81112. engine.setDepthWrite(true);
  81113. engine.setColorWrite(true);
  81114. };
  81115. BoundingBoxRenderer.prototype.dispose = function () {
  81116. if (!this._colorShader) {
  81117. return;
  81118. }
  81119. this.renderList.dispose();
  81120. this._colorShader.dispose();
  81121. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81122. if (buffer) {
  81123. buffer.dispose();
  81124. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81125. }
  81126. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81127. };
  81128. return BoundingBoxRenderer;
  81129. }());
  81130. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  81131. })(BABYLON || (BABYLON = {}));
  81132. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  81133. "use strict";
  81134. var BABYLON;
  81135. (function (BABYLON) {
  81136. var MorphTarget = /** @class */ (function () {
  81137. function MorphTarget(name, influence) {
  81138. if (influence === void 0) { influence = 0; }
  81139. this.name = name;
  81140. this.animations = new Array();
  81141. this._positions = null;
  81142. this._normals = null;
  81143. this._tangents = null;
  81144. this.onInfluenceChanged = new BABYLON.Observable();
  81145. this.influence = influence;
  81146. }
  81147. Object.defineProperty(MorphTarget.prototype, "influence", {
  81148. get: function () {
  81149. return this._influence;
  81150. },
  81151. set: function (influence) {
  81152. if (this._influence === influence) {
  81153. return;
  81154. }
  81155. var previous = this._influence;
  81156. this._influence = influence;
  81157. if (this.onInfluenceChanged.hasObservers) {
  81158. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  81159. }
  81160. },
  81161. enumerable: true,
  81162. configurable: true
  81163. });
  81164. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  81165. get: function () {
  81166. return !!this._positions;
  81167. },
  81168. enumerable: true,
  81169. configurable: true
  81170. });
  81171. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  81172. get: function () {
  81173. return !!this._normals;
  81174. },
  81175. enumerable: true,
  81176. configurable: true
  81177. });
  81178. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  81179. get: function () {
  81180. return !!this._tangents;
  81181. },
  81182. enumerable: true,
  81183. configurable: true
  81184. });
  81185. MorphTarget.prototype.setPositions = function (data) {
  81186. this._positions = data;
  81187. };
  81188. MorphTarget.prototype.getPositions = function () {
  81189. return this._positions;
  81190. };
  81191. MorphTarget.prototype.setNormals = function (data) {
  81192. this._normals = data;
  81193. };
  81194. MorphTarget.prototype.getNormals = function () {
  81195. return this._normals;
  81196. };
  81197. MorphTarget.prototype.setTangents = function (data) {
  81198. this._tangents = data;
  81199. };
  81200. MorphTarget.prototype.getTangents = function () {
  81201. return this._tangents;
  81202. };
  81203. /**
  81204. * Serializes the current target into a Serialization object.
  81205. * Returns the serialized object.
  81206. */
  81207. MorphTarget.prototype.serialize = function () {
  81208. var serializationObject = {};
  81209. serializationObject.name = this.name;
  81210. serializationObject.influence = this.influence;
  81211. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  81212. if (this.hasNormals) {
  81213. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  81214. }
  81215. if (this.hasTangents) {
  81216. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  81217. }
  81218. // Animations
  81219. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  81220. return serializationObject;
  81221. };
  81222. // Statics
  81223. MorphTarget.Parse = function (serializationObject) {
  81224. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  81225. result.setPositions(serializationObject.positions);
  81226. if (serializationObject.normals) {
  81227. result.setNormals(serializationObject.normals);
  81228. }
  81229. if (serializationObject.tangents) {
  81230. result.setTangents(serializationObject.tangents);
  81231. }
  81232. // Animations
  81233. if (serializationObject.animations) {
  81234. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  81235. var parsedAnimation = serializationObject.animations[animationIndex];
  81236. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  81237. }
  81238. }
  81239. return result;
  81240. };
  81241. MorphTarget.FromMesh = function (mesh, name, influence) {
  81242. if (!name) {
  81243. name = mesh.name;
  81244. }
  81245. var result = new MorphTarget(name, influence);
  81246. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  81247. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  81248. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  81249. }
  81250. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  81251. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  81252. }
  81253. return result;
  81254. };
  81255. return MorphTarget;
  81256. }());
  81257. BABYLON.MorphTarget = MorphTarget;
  81258. })(BABYLON || (BABYLON = {}));
  81259. //# sourceMappingURL=babylon.morphTarget.js.map
  81260. "use strict";
  81261. var BABYLON;
  81262. (function (BABYLON) {
  81263. var MorphTargetManager = /** @class */ (function () {
  81264. function MorphTargetManager(scene) {
  81265. if (scene === void 0) { scene = null; }
  81266. this._targets = new Array();
  81267. this._targetObservable = new Array();
  81268. this._activeTargets = new BABYLON.SmartArray(16);
  81269. this._supportsNormals = false;
  81270. this._supportsTangents = false;
  81271. this._vertexCount = 0;
  81272. this._uniqueId = 0;
  81273. this._tempInfluences = new Array();
  81274. if (!scene) {
  81275. scene = BABYLON.Engine.LastCreatedScene;
  81276. }
  81277. this._scene = scene;
  81278. if (this._scene) {
  81279. this._scene.morphTargetManagers.push(this);
  81280. this._uniqueId = this._scene.getUniqueId();
  81281. }
  81282. }
  81283. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  81284. get: function () {
  81285. return this._uniqueId;
  81286. },
  81287. enumerable: true,
  81288. configurable: true
  81289. });
  81290. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  81291. get: function () {
  81292. return this._vertexCount;
  81293. },
  81294. enumerable: true,
  81295. configurable: true
  81296. });
  81297. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  81298. get: function () {
  81299. return this._supportsNormals;
  81300. },
  81301. enumerable: true,
  81302. configurable: true
  81303. });
  81304. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  81305. get: function () {
  81306. return this._supportsTangents;
  81307. },
  81308. enumerable: true,
  81309. configurable: true
  81310. });
  81311. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  81312. get: function () {
  81313. return this._targets.length;
  81314. },
  81315. enumerable: true,
  81316. configurable: true
  81317. });
  81318. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  81319. get: function () {
  81320. return this._activeTargets.length;
  81321. },
  81322. enumerable: true,
  81323. configurable: true
  81324. });
  81325. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  81326. get: function () {
  81327. return this._influences;
  81328. },
  81329. enumerable: true,
  81330. configurable: true
  81331. });
  81332. MorphTargetManager.prototype.getActiveTarget = function (index) {
  81333. return this._activeTargets.data[index];
  81334. };
  81335. MorphTargetManager.prototype.getTarget = function (index) {
  81336. return this._targets[index];
  81337. };
  81338. MorphTargetManager.prototype.addTarget = function (target) {
  81339. var _this = this;
  81340. this._targets.push(target);
  81341. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  81342. _this._syncActiveTargets(needUpdate);
  81343. }));
  81344. this._syncActiveTargets(true);
  81345. };
  81346. MorphTargetManager.prototype.removeTarget = function (target) {
  81347. var index = this._targets.indexOf(target);
  81348. if (index >= 0) {
  81349. this._targets.splice(index, 1);
  81350. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  81351. this._syncActiveTargets(true);
  81352. }
  81353. };
  81354. /**
  81355. * Serializes the current manager into a Serialization object.
  81356. * Returns the serialized object.
  81357. */
  81358. MorphTargetManager.prototype.serialize = function () {
  81359. var serializationObject = {};
  81360. serializationObject.id = this.uniqueId;
  81361. serializationObject.targets = [];
  81362. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81363. var target = _a[_i];
  81364. serializationObject.targets.push(target.serialize());
  81365. }
  81366. return serializationObject;
  81367. };
  81368. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  81369. var influenceCount = 0;
  81370. this._activeTargets.reset();
  81371. this._supportsNormals = true;
  81372. this._supportsTangents = true;
  81373. this._vertexCount = 0;
  81374. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81375. var target = _a[_i];
  81376. this._activeTargets.push(target);
  81377. this._tempInfluences[influenceCount++] = target.influence;
  81378. var positions = target.getPositions();
  81379. if (positions) {
  81380. this._supportsNormals = this._supportsNormals && target.hasNormals;
  81381. this._supportsTangents = this._supportsTangents && target.hasTangents;
  81382. var vertexCount = positions.length / 3;
  81383. if (this._vertexCount === 0) {
  81384. this._vertexCount = vertexCount;
  81385. }
  81386. else if (this._vertexCount !== vertexCount) {
  81387. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  81388. return;
  81389. }
  81390. }
  81391. }
  81392. if (!this._influences || this._influences.length !== influenceCount) {
  81393. this._influences = new Float32Array(influenceCount);
  81394. }
  81395. for (var index = 0; index < influenceCount; index++) {
  81396. this._influences[index] = this._tempInfluences[index];
  81397. }
  81398. if (needUpdate && this._scene) {
  81399. // Flag meshes as dirty to resync with the active targets
  81400. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  81401. var mesh = _c[_b];
  81402. if (mesh.morphTargetManager === this) {
  81403. mesh._syncGeometryWithMorphTargetManager();
  81404. }
  81405. }
  81406. }
  81407. };
  81408. // Statics
  81409. MorphTargetManager.Parse = function (serializationObject, scene) {
  81410. var result = new MorphTargetManager(scene);
  81411. result._uniqueId = serializationObject.id;
  81412. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  81413. var targetData = _a[_i];
  81414. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  81415. }
  81416. return result;
  81417. };
  81418. return MorphTargetManager;
  81419. }());
  81420. BABYLON.MorphTargetManager = MorphTargetManager;
  81421. })(BABYLON || (BABYLON = {}));
  81422. //# sourceMappingURL=babylon.morphTargetManager.js.map
  81423. "use strict";
  81424. var BABYLON;
  81425. (function (BABYLON) {
  81426. var Octree = /** @class */ (function () {
  81427. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  81428. if (maxDepth === void 0) { maxDepth = 2; }
  81429. this.maxDepth = maxDepth;
  81430. this.dynamicContent = new Array();
  81431. this._maxBlockCapacity = maxBlockCapacity || 64;
  81432. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  81433. this._creationFunc = creationFunc;
  81434. }
  81435. // Methods
  81436. Octree.prototype.update = function (worldMin, worldMax, entries) {
  81437. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  81438. };
  81439. Octree.prototype.addMesh = function (entry) {
  81440. for (var index = 0; index < this.blocks.length; index++) {
  81441. var block = this.blocks[index];
  81442. block.addEntry(entry);
  81443. }
  81444. };
  81445. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  81446. this._selectionContent.reset();
  81447. for (var index = 0; index < this.blocks.length; index++) {
  81448. var block = this.blocks[index];
  81449. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  81450. }
  81451. if (allowDuplicate) {
  81452. this._selectionContent.concat(this.dynamicContent);
  81453. }
  81454. else {
  81455. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81456. }
  81457. return this._selectionContent;
  81458. };
  81459. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  81460. this._selectionContent.reset();
  81461. for (var index = 0; index < this.blocks.length; index++) {
  81462. var block = this.blocks[index];
  81463. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  81464. }
  81465. if (allowDuplicate) {
  81466. this._selectionContent.concat(this.dynamicContent);
  81467. }
  81468. else {
  81469. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81470. }
  81471. return this._selectionContent;
  81472. };
  81473. Octree.prototype.intersectsRay = function (ray) {
  81474. this._selectionContent.reset();
  81475. for (var index = 0; index < this.blocks.length; index++) {
  81476. var block = this.blocks[index];
  81477. block.intersectsRay(ray, this._selectionContent);
  81478. }
  81479. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81480. return this._selectionContent;
  81481. };
  81482. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  81483. target.blocks = new Array();
  81484. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  81485. // Segmenting space
  81486. for (var x = 0; x < 2; x++) {
  81487. for (var y = 0; y < 2; y++) {
  81488. for (var z = 0; z < 2; z++) {
  81489. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  81490. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  81491. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  81492. block.addEntries(entries);
  81493. target.blocks.push(block);
  81494. }
  81495. }
  81496. }
  81497. };
  81498. Octree.CreationFuncForMeshes = function (entry, block) {
  81499. var boundingInfo = entry.getBoundingInfo();
  81500. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81501. block.entries.push(entry);
  81502. }
  81503. };
  81504. Octree.CreationFuncForSubMeshes = function (entry, block) {
  81505. var boundingInfo = entry.getBoundingInfo();
  81506. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81507. block.entries.push(entry);
  81508. }
  81509. };
  81510. return Octree;
  81511. }());
  81512. BABYLON.Octree = Octree;
  81513. })(BABYLON || (BABYLON = {}));
  81514. //# sourceMappingURL=babylon.octree.js.map
  81515. "use strict";
  81516. var BABYLON;
  81517. (function (BABYLON) {
  81518. var OctreeBlock = /** @class */ (function () {
  81519. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  81520. this.entries = new Array();
  81521. this._boundingVectors = new Array();
  81522. this._capacity = capacity;
  81523. this._depth = depth;
  81524. this._maxDepth = maxDepth;
  81525. this._creationFunc = creationFunc;
  81526. this._minPoint = minPoint;
  81527. this._maxPoint = maxPoint;
  81528. this._boundingVectors.push(minPoint.clone());
  81529. this._boundingVectors.push(maxPoint.clone());
  81530. this._boundingVectors.push(minPoint.clone());
  81531. this._boundingVectors[2].x = maxPoint.x;
  81532. this._boundingVectors.push(minPoint.clone());
  81533. this._boundingVectors[3].y = maxPoint.y;
  81534. this._boundingVectors.push(minPoint.clone());
  81535. this._boundingVectors[4].z = maxPoint.z;
  81536. this._boundingVectors.push(maxPoint.clone());
  81537. this._boundingVectors[5].z = minPoint.z;
  81538. this._boundingVectors.push(maxPoint.clone());
  81539. this._boundingVectors[6].x = minPoint.x;
  81540. this._boundingVectors.push(maxPoint.clone());
  81541. this._boundingVectors[7].y = minPoint.y;
  81542. }
  81543. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  81544. // Property
  81545. get: function () {
  81546. return this._capacity;
  81547. },
  81548. enumerable: true,
  81549. configurable: true
  81550. });
  81551. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  81552. get: function () {
  81553. return this._minPoint;
  81554. },
  81555. enumerable: true,
  81556. configurable: true
  81557. });
  81558. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  81559. get: function () {
  81560. return this._maxPoint;
  81561. },
  81562. enumerable: true,
  81563. configurable: true
  81564. });
  81565. // Methods
  81566. OctreeBlock.prototype.addEntry = function (entry) {
  81567. if (this.blocks) {
  81568. for (var index = 0; index < this.blocks.length; index++) {
  81569. var block = this.blocks[index];
  81570. block.addEntry(entry);
  81571. }
  81572. return;
  81573. }
  81574. this._creationFunc(entry, this);
  81575. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  81576. this.createInnerBlocks();
  81577. }
  81578. };
  81579. OctreeBlock.prototype.addEntries = function (entries) {
  81580. for (var index = 0; index < entries.length; index++) {
  81581. var mesh = entries[index];
  81582. this.addEntry(mesh);
  81583. }
  81584. };
  81585. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  81586. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  81587. if (this.blocks) {
  81588. for (var index = 0; index < this.blocks.length; index++) {
  81589. var block = this.blocks[index];
  81590. block.select(frustumPlanes, selection, allowDuplicate);
  81591. }
  81592. return;
  81593. }
  81594. if (allowDuplicate) {
  81595. selection.concat(this.entries);
  81596. }
  81597. else {
  81598. selection.concatWithNoDuplicate(this.entries);
  81599. }
  81600. }
  81601. };
  81602. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  81603. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  81604. if (this.blocks) {
  81605. for (var index = 0; index < this.blocks.length; index++) {
  81606. var block = this.blocks[index];
  81607. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  81608. }
  81609. return;
  81610. }
  81611. if (allowDuplicate) {
  81612. selection.concat(this.entries);
  81613. }
  81614. else {
  81615. selection.concatWithNoDuplicate(this.entries);
  81616. }
  81617. }
  81618. };
  81619. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  81620. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  81621. if (this.blocks) {
  81622. for (var index = 0; index < this.blocks.length; index++) {
  81623. var block = this.blocks[index];
  81624. block.intersectsRay(ray, selection);
  81625. }
  81626. return;
  81627. }
  81628. selection.concatWithNoDuplicate(this.entries);
  81629. }
  81630. };
  81631. OctreeBlock.prototype.createInnerBlocks = function () {
  81632. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  81633. };
  81634. return OctreeBlock;
  81635. }());
  81636. BABYLON.OctreeBlock = OctreeBlock;
  81637. })(BABYLON || (BABYLON = {}));
  81638. //# sourceMappingURL=babylon.octreeBlock.js.map
  81639. "use strict";
  81640. var BABYLON;
  81641. (function (BABYLON) {
  81642. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  81643. __extends(VRDistortionCorrectionPostProcess, _super);
  81644. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  81645. var _this = _super.call(this, name, "vrDistortionCorrection", [
  81646. 'LensCenter',
  81647. 'Scale',
  81648. 'ScaleIn',
  81649. 'HmdWarpParam'
  81650. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  81651. _this._isRightEye = isRightEye;
  81652. _this._distortionFactors = vrMetrics.distortionK;
  81653. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  81654. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  81655. _this.adaptScaleToCurrentViewport = true;
  81656. _this.onSizeChangedObservable.add(function () {
  81657. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  81658. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  81659. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  81660. });
  81661. _this.onApplyObservable.add(function (effect) {
  81662. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  81663. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  81664. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  81665. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  81666. });
  81667. return _this;
  81668. }
  81669. return VRDistortionCorrectionPostProcess;
  81670. }(BABYLON.PostProcess));
  81671. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  81672. })(BABYLON || (BABYLON = {}));
  81673. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  81674. "use strict";
  81675. var BABYLON;
  81676. (function (BABYLON) {
  81677. var AnaglyphPostProcess = /** @class */ (function (_super) {
  81678. __extends(AnaglyphPostProcess, _super);
  81679. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  81680. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  81681. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81682. _this.onApplyObservable.add(function (effect) {
  81683. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  81684. });
  81685. return _this;
  81686. }
  81687. return AnaglyphPostProcess;
  81688. }(BABYLON.PostProcess));
  81689. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  81690. })(BABYLON || (BABYLON = {}));
  81691. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  81692. "use strict";
  81693. var BABYLON;
  81694. (function (BABYLON) {
  81695. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  81696. __extends(StereoscopicInterlacePostProcess, _super);
  81697. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  81698. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  81699. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81700. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81701. _this.onSizeChangedObservable.add(function () {
  81702. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81703. });
  81704. _this.onApplyObservable.add(function (effect) {
  81705. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  81706. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  81707. });
  81708. return _this;
  81709. }
  81710. return StereoscopicInterlacePostProcess;
  81711. }(BABYLON.PostProcess));
  81712. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  81713. })(BABYLON || (BABYLON = {}));
  81714. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  81715. "use strict";
  81716. var BABYLON;
  81717. (function (BABYLON) {
  81718. /**
  81719. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  81720. * Screen rotation is taken into account.
  81721. */
  81722. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  81723. function FreeCameraDeviceOrientationInput() {
  81724. var _this = this;
  81725. this._screenOrientationAngle = 0;
  81726. this._screenQuaternion = new BABYLON.Quaternion();
  81727. this._alpha = 0;
  81728. this._beta = 0;
  81729. this._gamma = 0;
  81730. this._orientationChanged = function () {
  81731. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  81732. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  81733. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  81734. };
  81735. this._deviceOrientation = function (evt) {
  81736. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  81737. _this._beta = evt.beta !== null ? evt.beta : 0;
  81738. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  81739. };
  81740. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  81741. this._orientationChanged();
  81742. }
  81743. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  81744. get: function () {
  81745. return this._camera;
  81746. },
  81747. set: function (camera) {
  81748. this._camera = camera;
  81749. if (this._camera != null && !this._camera.rotationQuaternion) {
  81750. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  81751. }
  81752. },
  81753. enumerable: true,
  81754. configurable: true
  81755. });
  81756. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81757. window.addEventListener("orientationchange", this._orientationChanged);
  81758. window.addEventListener("deviceorientation", this._deviceOrientation);
  81759. //In certain cases, the attach control is called AFTER orientation was changed,
  81760. //So this is needed.
  81761. this._orientationChanged();
  81762. };
  81763. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  81764. window.removeEventListener("orientationchange", this._orientationChanged);
  81765. window.removeEventListener("deviceorientation", this._deviceOrientation);
  81766. };
  81767. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  81768. //if no device orientation provided, don't update the rotation.
  81769. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  81770. if (!this._alpha)
  81771. return;
  81772. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  81773. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  81774. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  81775. //Mirror on XY Plane
  81776. this._camera.rotationQuaternion.z *= -1;
  81777. this._camera.rotationQuaternion.w *= -1;
  81778. };
  81779. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  81780. return "FreeCameraDeviceOrientationInput";
  81781. };
  81782. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  81783. return "deviceOrientation";
  81784. };
  81785. return FreeCameraDeviceOrientationInput;
  81786. }());
  81787. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  81788. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  81789. })(BABYLON || (BABYLON = {}));
  81790. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  81791. "use strict";
  81792. var BABYLON;
  81793. (function (BABYLON) {
  81794. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  81795. function ArcRotateCameraVRDeviceOrientationInput() {
  81796. this.alphaCorrection = 1;
  81797. this.betaCorrection = 1;
  81798. this.gammaCorrection = 1;
  81799. this._alpha = 0;
  81800. this._gamma = 0;
  81801. this._dirty = false;
  81802. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  81803. }
  81804. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81805. this.camera.attachControl(element, noPreventDefault);
  81806. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  81807. };
  81808. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  81809. if (evt.alpha !== null) {
  81810. this._alpha = +evt.alpha | 0;
  81811. }
  81812. if (evt.gamma !== null) {
  81813. this._gamma = +evt.gamma | 0;
  81814. }
  81815. this._dirty = true;
  81816. };
  81817. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  81818. if (this._dirty) {
  81819. this._dirty = false;
  81820. if (this._gamma < 0) {
  81821. this._gamma = 180 + this._gamma;
  81822. }
  81823. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  81824. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  81825. }
  81826. };
  81827. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  81828. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  81829. };
  81830. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  81831. return "ArcRotateCameraVRDeviceOrientationInput";
  81832. };
  81833. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  81834. return "VRDeviceOrientation";
  81835. };
  81836. return ArcRotateCameraVRDeviceOrientationInput;
  81837. }());
  81838. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  81839. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  81840. })(BABYLON || (BABYLON = {}));
  81841. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  81842. "use strict";
  81843. var BABYLON;
  81844. (function (BABYLON) {
  81845. var VRCameraMetrics = /** @class */ (function () {
  81846. function VRCameraMetrics() {
  81847. this.compensateDistortion = true;
  81848. }
  81849. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  81850. get: function () {
  81851. return this.hResolution / (2 * this.vResolution);
  81852. },
  81853. enumerable: true,
  81854. configurable: true
  81855. });
  81856. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  81857. get: function () {
  81858. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  81859. },
  81860. enumerable: true,
  81861. configurable: true
  81862. });
  81863. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  81864. get: function () {
  81865. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81866. var h = (4 * meters) / this.hScreenSize;
  81867. return BABYLON.Matrix.Translation(h, 0, 0);
  81868. },
  81869. enumerable: true,
  81870. configurable: true
  81871. });
  81872. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  81873. get: function () {
  81874. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81875. var h = (4 * meters) / this.hScreenSize;
  81876. return BABYLON.Matrix.Translation(-h, 0, 0);
  81877. },
  81878. enumerable: true,
  81879. configurable: true
  81880. });
  81881. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  81882. get: function () {
  81883. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  81884. },
  81885. enumerable: true,
  81886. configurable: true
  81887. });
  81888. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  81889. get: function () {
  81890. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  81891. },
  81892. enumerable: true,
  81893. configurable: true
  81894. });
  81895. VRCameraMetrics.GetDefault = function () {
  81896. var result = new VRCameraMetrics();
  81897. result.hResolution = 1280;
  81898. result.vResolution = 800;
  81899. result.hScreenSize = 0.149759993;
  81900. result.vScreenSize = 0.0935999975;
  81901. result.vScreenCenter = 0.0467999987;
  81902. result.eyeToScreenDistance = 0.0410000011;
  81903. result.lensSeparationDistance = 0.0635000020;
  81904. result.interpupillaryDistance = 0.0640000030;
  81905. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  81906. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  81907. result.postProcessScaleFactor = 1.714605507808412;
  81908. result.lensCenterOffset = 0.151976421;
  81909. return result;
  81910. };
  81911. return VRCameraMetrics;
  81912. }());
  81913. BABYLON.VRCameraMetrics = VRCameraMetrics;
  81914. })(BABYLON || (BABYLON = {}));
  81915. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  81916. "use strict";
  81917. var BABYLON;
  81918. (function (BABYLON) {
  81919. /**
  81920. * This represents a WebVR camera.
  81921. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  81922. * @example http://doc.babylonjs.com/how_to/webvr_camera
  81923. */
  81924. var WebVRFreeCamera = /** @class */ (function (_super) {
  81925. __extends(WebVRFreeCamera, _super);
  81926. /**
  81927. * Instantiates a WebVRFreeCamera.
  81928. * @param name The name of the WebVRFreeCamera
  81929. * @param position The starting anchor position for the camera
  81930. * @param scene The scene the camera belongs to
  81931. * @param webVROptions a set of customizable options for the webVRCamera
  81932. */
  81933. function WebVRFreeCamera(name, position, scene, webVROptions) {
  81934. if (webVROptions === void 0) { webVROptions = {}; }
  81935. var _this = _super.call(this, name, position, scene) || this;
  81936. _this.webVROptions = webVROptions;
  81937. /**
  81938. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  81939. */
  81940. _this._vrDevice = null;
  81941. /**
  81942. * The rawPose of the vrDevice.
  81943. */
  81944. _this.rawPose = null;
  81945. _this._specsVersion = "1.1";
  81946. _this._attached = false;
  81947. _this._descendants = [];
  81948. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  81949. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  81950. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  81951. _this._standingMatrix = null;
  81952. /**
  81953. * Represents device position in babylon space.
  81954. */
  81955. _this.devicePosition = BABYLON.Vector3.Zero();
  81956. /**
  81957. * Represents device rotation in babylon space.
  81958. */
  81959. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  81960. /**
  81961. * The scale of the device to be used when translating from device space to babylon space.
  81962. */
  81963. _this.deviceScaleFactor = 1;
  81964. _this._deviceToWorld = BABYLON.Matrix.Identity();
  81965. _this._worldToDevice = BABYLON.Matrix.Identity();
  81966. /**
  81967. * References to the webVR controllers for the vrDevice.
  81968. */
  81969. _this.controllers = [];
  81970. /**
  81971. * Emits an event when a controller is attached.
  81972. */
  81973. _this.onControllersAttachedObservable = new BABYLON.Observable();
  81974. /**
  81975. * Emits an event when a controller's mesh has been loaded;
  81976. */
  81977. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81978. /**
  81979. * If the rig cameras be used as parent instead of this camera.
  81980. */
  81981. _this.rigParenting = true;
  81982. _this._defaultHeight = undefined;
  81983. _this._workingVector = BABYLON.Vector3.Zero();
  81984. _this._oneVector = BABYLON.Vector3.One();
  81985. _this._workingMatrix = BABYLON.Matrix.Identity();
  81986. _this._cache.position = BABYLON.Vector3.Zero();
  81987. if (webVROptions.defaultHeight) {
  81988. _this._defaultHeight = webVROptions.defaultHeight;
  81989. _this.position.y = _this._defaultHeight;
  81990. }
  81991. _this.minZ = 0.1;
  81992. //legacy support - the compensation boolean was removed.
  81993. if (arguments.length === 5) {
  81994. _this.webVROptions = arguments[4];
  81995. }
  81996. // default webVR options
  81997. if (_this.webVROptions.trackPosition == undefined) {
  81998. _this.webVROptions.trackPosition = true;
  81999. }
  82000. if (_this.webVROptions.controllerMeshes == undefined) {
  82001. _this.webVROptions.controllerMeshes = true;
  82002. }
  82003. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  82004. _this.webVROptions.defaultLightingOnControllers = true;
  82005. }
  82006. _this.rotationQuaternion = new BABYLON.Quaternion();
  82007. if (_this.webVROptions && _this.webVROptions.positionScale) {
  82008. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  82009. }
  82010. //enable VR
  82011. var engine = _this.getEngine();
  82012. _this._onVREnabled = function (success) { if (success) {
  82013. _this.initControllers();
  82014. } };
  82015. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  82016. engine.initWebVR().add(function (event) {
  82017. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  82018. return;
  82019. }
  82020. _this._vrDevice = event.vrDisplay;
  82021. //reset the rig parameters.
  82022. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  82023. if (_this._attached) {
  82024. _this.getEngine().enableVR();
  82025. }
  82026. });
  82027. if (typeof (VRFrameData) !== "undefined")
  82028. _this._frameData = new VRFrameData();
  82029. /**
  82030. * The idea behind the following lines:
  82031. * objects that have the camera as parent should actually have the rig cameras as a parent.
  82032. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  82033. * the second will not show it correctly.
  82034. *
  82035. * To solve this - each object that has the camera as parent will be added to a protected array.
  82036. * When the rig camera renders, it will take this array and set all of those to be its children.
  82037. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  82038. * Amazing!
  82039. */
  82040. scene.onBeforeCameraRenderObservable.add(function (camera) {
  82041. if (camera.parent === _this && _this.rigParenting) {
  82042. _this._descendants = _this.getDescendants(true, function (n) {
  82043. // don't take the cameras or the controllers!
  82044. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  82045. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  82046. return !isController && !isRigCamera;
  82047. });
  82048. _this._descendants.forEach(function (node) {
  82049. node.parent = camera;
  82050. });
  82051. }
  82052. });
  82053. scene.onAfterCameraRenderObservable.add(function (camera) {
  82054. if (camera.parent === _this && _this.rigParenting) {
  82055. _this._descendants.forEach(function (node) {
  82056. node.parent = _this;
  82057. });
  82058. }
  82059. });
  82060. return _this;
  82061. }
  82062. /**
  82063. * Gets the device distance from the ground in meters.
  82064. * @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.
  82065. */
  82066. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  82067. if (this._standingMatrix) {
  82068. // Add standing matrix offset to get real offset from ground in room
  82069. this._standingMatrix.getTranslationToRef(this._workingVector);
  82070. return this._deviceRoomPosition.y + this._workingVector.y;
  82071. }
  82072. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  82073. return this._defaultHeight || 0;
  82074. };
  82075. /**
  82076. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  82077. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  82078. */
  82079. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  82080. var _this = this;
  82081. if (callback === void 0) { callback = function (bool) { }; }
  82082. // Use standing matrix if available
  82083. this.getEngine().initWebVRAsync().then(function (result) {
  82084. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  82085. callback(false);
  82086. }
  82087. else {
  82088. _this._standingMatrix = new BABYLON.Matrix();
  82089. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  82090. if (!_this.getScene().useRightHandedSystem) {
  82091. [2, 6, 8, 9, 14].forEach(function (num) {
  82092. if (_this._standingMatrix) {
  82093. _this._standingMatrix.m[num] *= -1;
  82094. }
  82095. });
  82096. }
  82097. callback(true);
  82098. }
  82099. });
  82100. };
  82101. /**
  82102. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  82103. * @returns A promise with a boolean set to if the standing matrix is supported.
  82104. */
  82105. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  82106. var _this = this;
  82107. return new Promise(function (res, rej) {
  82108. _this.useStandingMatrix(function (supported) {
  82109. res(supported);
  82110. });
  82111. });
  82112. };
  82113. /**
  82114. * Disposes the camera
  82115. */
  82116. WebVRFreeCamera.prototype.dispose = function () {
  82117. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  82118. _super.prototype.dispose.call(this);
  82119. };
  82120. /**
  82121. * Gets a vrController by name.
  82122. * @param name The name of the controller to retreive
  82123. * @returns the controller matching the name specified or null if not found
  82124. */
  82125. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  82126. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  82127. var gp = _a[_i];
  82128. if (gp.hand === name) {
  82129. return gp;
  82130. }
  82131. }
  82132. return null;
  82133. };
  82134. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  82135. /**
  82136. * The controller corrisponding to the users left hand.
  82137. */
  82138. get: function () {
  82139. if (!this._leftController) {
  82140. this._leftController = this.getControllerByName("left");
  82141. }
  82142. return this._leftController;
  82143. },
  82144. enumerable: true,
  82145. configurable: true
  82146. });
  82147. ;
  82148. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  82149. /**
  82150. * The controller corrisponding to the users right hand.
  82151. */
  82152. get: function () {
  82153. if (!this._rightController) {
  82154. this._rightController = this.getControllerByName("right");
  82155. }
  82156. return this._rightController;
  82157. },
  82158. enumerable: true,
  82159. configurable: true
  82160. });
  82161. ;
  82162. /**
  82163. * Casts a ray forward from the vrCamera's gaze.
  82164. * @param length Length of the ray (default: 100)
  82165. * @returns the ray corrisponding to the gaze
  82166. */
  82167. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  82168. if (length === void 0) { length = 100; }
  82169. if (this.leftCamera) {
  82170. // Use left eye to avoid computation to compute center on every call
  82171. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  82172. }
  82173. else {
  82174. return _super.prototype.getForwardRay.call(this, length);
  82175. }
  82176. };
  82177. /**
  82178. * Updates the camera based on device's frame data
  82179. */
  82180. WebVRFreeCamera.prototype._checkInputs = function () {
  82181. if (this._vrDevice && this._vrDevice.isPresenting) {
  82182. this._vrDevice.getFrameData(this._frameData);
  82183. this.updateFromDevice(this._frameData.pose);
  82184. }
  82185. _super.prototype._checkInputs.call(this);
  82186. };
  82187. /**
  82188. * Updates the poseControlled values based on the input device pose.
  82189. * @param poseData Pose coming from the device
  82190. */
  82191. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  82192. if (poseData && poseData.orientation) {
  82193. this.rawPose = poseData;
  82194. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  82195. if (this.getScene().useRightHandedSystem) {
  82196. this._deviceRoomRotationQuaternion.z *= -1;
  82197. this._deviceRoomRotationQuaternion.w *= -1;
  82198. }
  82199. if (this.webVROptions.trackPosition && this.rawPose.position) {
  82200. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  82201. if (this.getScene().useRightHandedSystem) {
  82202. this._deviceRoomPosition.z *= -1;
  82203. }
  82204. }
  82205. }
  82206. };
  82207. /**
  82208. * WebVR's attach control will start broadcasting frames to the device.
  82209. * Note that in certain browsers (chrome for example) this function must be called
  82210. * within a user-interaction callback. Example:
  82211. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  82212. *
  82213. * @param element html element to attach the vrDevice to
  82214. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  82215. */
  82216. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  82217. _super.prototype.attachControl.call(this, element, noPreventDefault);
  82218. this._attached = true;
  82219. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  82220. if (this._vrDevice) {
  82221. this.getEngine().enableVR();
  82222. }
  82223. };
  82224. /**
  82225. * Detaches the camera from the html element and disables VR
  82226. *
  82227. * @param element html element to detach from
  82228. */
  82229. WebVRFreeCamera.prototype.detachControl = function (element) {
  82230. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  82231. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  82232. _super.prototype.detachControl.call(this, element);
  82233. this._attached = false;
  82234. this.getEngine().disableVR();
  82235. };
  82236. /**
  82237. * @returns the name of this class
  82238. */
  82239. WebVRFreeCamera.prototype.getClassName = function () {
  82240. return "WebVRFreeCamera";
  82241. };
  82242. /**
  82243. * Calls resetPose on the vrDisplay
  82244. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  82245. */
  82246. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  82247. //uses the vrDisplay's "resetPose()".
  82248. //pitch and roll won't be affected.
  82249. this._vrDevice.resetPose();
  82250. };
  82251. /**
  82252. * Updates the rig cameras (left and right eye)
  82253. */
  82254. WebVRFreeCamera.prototype._updateRigCameras = function () {
  82255. var camLeft = this._rigCameras[0];
  82256. var camRight = this._rigCameras[1];
  82257. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  82258. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  82259. camLeft.position.copyFrom(this._deviceRoomPosition);
  82260. camRight.position.copyFrom(this._deviceRoomPosition);
  82261. };
  82262. /**
  82263. * Updates the cached values of the camera
  82264. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  82265. */
  82266. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  82267. var _this = this;
  82268. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  82269. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  82270. if (!this.updateCacheCalled) {
  82271. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  82272. this.updateCacheCalled = true;
  82273. this.update();
  82274. }
  82275. // Set working vector to the device position in room space rotated by the new rotation
  82276. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  82277. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  82278. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  82279. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  82280. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  82281. // Add translation from anchor position
  82282. this._deviceToWorld.getTranslationToRef(this._workingVector);
  82283. this._workingVector.addInPlace(this.position);
  82284. this._workingVector.subtractInPlace(this._cache.position);
  82285. this._deviceToWorld.setTranslation(this._workingVector);
  82286. // Set an inverted matrix to be used when updating the camera
  82287. this._deviceToWorld.invertToRef(this._worldToDevice);
  82288. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  82289. this.controllers.forEach(function (controller) {
  82290. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  82291. controller.update();
  82292. });
  82293. }
  82294. if (!ignoreParentClass) {
  82295. _super.prototype._updateCache.call(this);
  82296. }
  82297. this.updateCacheCalled = false;
  82298. };
  82299. /**
  82300. * Updates the current device position and rotation in the babylon world
  82301. */
  82302. WebVRFreeCamera.prototype.update = function () {
  82303. // Get current device position in babylon world
  82304. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  82305. // Get current device rotation in babylon world
  82306. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  82307. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  82308. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  82309. _super.prototype.update.call(this);
  82310. };
  82311. /**
  82312. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  82313. * @returns an identity matrix
  82314. */
  82315. WebVRFreeCamera.prototype._getViewMatrix = function () {
  82316. return BABYLON.Matrix.Identity();
  82317. };
  82318. /**
  82319. * This function is called by the two RIG cameras.
  82320. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  82321. */
  82322. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  82323. var _this = this;
  82324. // Update the parent camera prior to using a child camera to avoid desynchronization
  82325. var parentCamera = this._cameraRigParams["parentCamera"];
  82326. parentCamera._updateCache();
  82327. //WebVR 1.1
  82328. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  82329. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  82330. if (!this.getScene().useRightHandedSystem) {
  82331. [2, 6, 8, 9, 14].forEach(function (num) {
  82332. _this._webvrViewMatrix.m[num] *= -1;
  82333. });
  82334. }
  82335. // update the camera rotation matrix
  82336. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  82337. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  82338. // Computing target and final matrix
  82339. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  82340. // should the view matrix be updated with scale and position offset?
  82341. if (parentCamera.deviceScaleFactor !== 1) {
  82342. this._webvrViewMatrix.invert();
  82343. // scale the position, if set
  82344. if (parentCamera.deviceScaleFactor) {
  82345. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  82346. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  82347. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  82348. }
  82349. this._webvrViewMatrix.invert();
  82350. }
  82351. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  82352. return this._webvrViewMatrix;
  82353. };
  82354. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  82355. var _this = this;
  82356. var parentCamera = this.parent;
  82357. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  82358. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  82359. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  82360. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  82361. //babylon compatible matrix
  82362. if (!this.getScene().useRightHandedSystem) {
  82363. [8, 9, 10, 11].forEach(function (num) {
  82364. _this._projectionMatrix.m[num] *= -1;
  82365. });
  82366. }
  82367. return this._projectionMatrix;
  82368. };
  82369. /**
  82370. * Initializes the controllers and their meshes
  82371. */
  82372. WebVRFreeCamera.prototype.initControllers = function () {
  82373. var _this = this;
  82374. this.controllers = [];
  82375. var manager = this.getScene().gamepadManager;
  82376. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  82377. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82378. var webVrController = gamepad;
  82379. if (webVrController.defaultModel) {
  82380. webVrController.defaultModel.setEnabled(false);
  82381. }
  82382. if (webVrController.hand === "right") {
  82383. _this._rightController = null;
  82384. }
  82385. if (webVrController.hand === "left") {
  82386. _this._leftController = null;
  82387. }
  82388. var controllerIndex = _this.controllers.indexOf(webVrController);
  82389. if (controllerIndex !== -1) {
  82390. _this.controllers.splice(controllerIndex, 1);
  82391. }
  82392. }
  82393. });
  82394. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  82395. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82396. var webVrController_1 = gamepad;
  82397. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  82398. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  82399. if (_this.webVROptions.controllerMeshes) {
  82400. if (webVrController_1.defaultModel) {
  82401. webVrController_1.defaultModel.setEnabled(true);
  82402. }
  82403. else {
  82404. // Load the meshes
  82405. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  82406. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  82407. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  82408. if (_this.webVROptions.defaultLightingOnControllers) {
  82409. if (!_this._lightOnControllers) {
  82410. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  82411. }
  82412. var activateLightOnSubMeshes_1 = function (mesh, light) {
  82413. var children = mesh.getChildren();
  82414. if (children.length !== 0) {
  82415. children.forEach(function (mesh) {
  82416. light.includedOnlyMeshes.push(mesh);
  82417. activateLightOnSubMeshes_1(mesh, light);
  82418. });
  82419. }
  82420. };
  82421. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  82422. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  82423. }
  82424. });
  82425. }
  82426. }
  82427. webVrController_1.attachToPoseControlledCamera(_this);
  82428. // since this is async - sanity check. Is the controller already stored?
  82429. if (_this.controllers.indexOf(webVrController_1) === -1) {
  82430. //add to the controllers array
  82431. _this.controllers.push(webVrController_1);
  82432. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  82433. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  82434. // So we're overriding setting left & right manually to be sure
  82435. var firstViveWandDetected = false;
  82436. for (var i = 0; i < _this.controllers.length; i++) {
  82437. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82438. if (!firstViveWandDetected) {
  82439. firstViveWandDetected = true;
  82440. _this.controllers[i].hand = "left";
  82441. }
  82442. else {
  82443. _this.controllers[i].hand = "right";
  82444. }
  82445. }
  82446. }
  82447. //did we find enough controllers? Great! let the developer know.
  82448. if (_this.controllers.length >= 2) {
  82449. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  82450. }
  82451. }
  82452. }
  82453. });
  82454. };
  82455. return WebVRFreeCamera;
  82456. }(BABYLON.FreeCamera));
  82457. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  82458. })(BABYLON || (BABYLON = {}));
  82459. //# sourceMappingURL=babylon.webVRCamera.js.map
  82460. "use strict";
  82461. var BABYLON;
  82462. (function (BABYLON) {
  82463. // We're mainly based on the logic defined into the FreeCamera code
  82464. /**
  82465. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  82466. * being tilted forward or back and left or right.
  82467. */
  82468. var DeviceOrientationCamera = /** @class */ (function (_super) {
  82469. __extends(DeviceOrientationCamera, _super);
  82470. /**
  82471. * Creates a new device orientation camera. @see DeviceOrientationCamera
  82472. * @param name The name of the camera
  82473. * @param position The start position camera
  82474. * @param scene The scene the camera belongs to
  82475. */
  82476. function DeviceOrientationCamera(name, position, scene) {
  82477. var _this = _super.call(this, name, position, scene) || this;
  82478. _this._quaternionCache = new BABYLON.Quaternion();
  82479. _this.inputs.addDeviceOrientation();
  82480. return _this;
  82481. }
  82482. /**
  82483. * Gets the current instance class name ("DeviceOrientationCamera").
  82484. * This helps avoiding instanceof at run time.
  82485. * @returns the class name
  82486. */
  82487. DeviceOrientationCamera.prototype.getClassName = function () {
  82488. return "DeviceOrientationCamera";
  82489. };
  82490. /**
  82491. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  82492. */
  82493. DeviceOrientationCamera.prototype._checkInputs = function () {
  82494. _super.prototype._checkInputs.call(this);
  82495. this._quaternionCache.copyFrom(this.rotationQuaternion);
  82496. if (this._initialQuaternion) {
  82497. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82498. }
  82499. };
  82500. /**
  82501. * Reset the camera to its default orientation on the specified axis only.
  82502. * @param axis The axis to reset
  82503. */
  82504. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  82505. var _this = this;
  82506. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  82507. //can only work if this camera has a rotation quaternion already.
  82508. if (!this.rotationQuaternion)
  82509. return;
  82510. if (!this._initialQuaternion) {
  82511. this._initialQuaternion = new BABYLON.Quaternion();
  82512. }
  82513. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  82514. ['x', 'y', 'z'].forEach(function (axisName) {
  82515. if (!axis[axisName]) {
  82516. _this._initialQuaternion[axisName] = 0;
  82517. }
  82518. else {
  82519. _this._initialQuaternion[axisName] *= -1;
  82520. }
  82521. });
  82522. this._initialQuaternion.normalize();
  82523. //force rotation update
  82524. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82525. };
  82526. return DeviceOrientationCamera;
  82527. }(BABYLON.FreeCamera));
  82528. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  82529. })(BABYLON || (BABYLON = {}));
  82530. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  82531. "use strict";
  82532. var BABYLON;
  82533. (function (BABYLON) {
  82534. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  82535. __extends(VRDeviceOrientationFreeCamera, _super);
  82536. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82537. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82538. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82539. var _this = _super.call(this, name, position, scene) || this;
  82540. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82541. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82542. return _this;
  82543. }
  82544. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  82545. return "VRDeviceOrientationFreeCamera";
  82546. };
  82547. return VRDeviceOrientationFreeCamera;
  82548. }(BABYLON.DeviceOrientationCamera));
  82549. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  82550. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  82551. __extends(VRDeviceOrientationGamepadCamera, _super);
  82552. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82553. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82554. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82555. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  82556. _this.inputs.addGamepad();
  82557. return _this;
  82558. }
  82559. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  82560. return "VRDeviceOrientationGamepadCamera";
  82561. };
  82562. return VRDeviceOrientationGamepadCamera;
  82563. }(VRDeviceOrientationFreeCamera));
  82564. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  82565. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  82566. __extends(VRDeviceOrientationArcRotateCamera, _super);
  82567. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  82568. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82569. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82570. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82571. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82572. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82573. _this.inputs.addVRDeviceOrientation();
  82574. return _this;
  82575. }
  82576. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  82577. return "VRDeviceOrientationArcRotateCamera";
  82578. };
  82579. return VRDeviceOrientationArcRotateCamera;
  82580. }(BABYLON.ArcRotateCamera));
  82581. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  82582. })(BABYLON || (BABYLON = {}));
  82583. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  82584. "use strict";
  82585. var BABYLON;
  82586. (function (BABYLON) {
  82587. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  82588. __extends(AnaglyphFreeCamera, _super);
  82589. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  82590. var _this = _super.call(this, name, position, scene) || this;
  82591. _this.interaxialDistance = interaxialDistance;
  82592. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82593. return _this;
  82594. }
  82595. AnaglyphFreeCamera.prototype.getClassName = function () {
  82596. return "AnaglyphFreeCamera";
  82597. };
  82598. return AnaglyphFreeCamera;
  82599. }(BABYLON.FreeCamera));
  82600. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  82601. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  82602. __extends(AnaglyphArcRotateCamera, _super);
  82603. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  82604. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82605. _this.interaxialDistance = interaxialDistance;
  82606. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82607. return _this;
  82608. }
  82609. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  82610. return "AnaglyphArcRotateCamera";
  82611. };
  82612. return AnaglyphArcRotateCamera;
  82613. }(BABYLON.ArcRotateCamera));
  82614. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  82615. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  82616. __extends(AnaglyphGamepadCamera, _super);
  82617. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  82618. var _this = _super.call(this, name, position, scene) || this;
  82619. _this.interaxialDistance = interaxialDistance;
  82620. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82621. return _this;
  82622. }
  82623. AnaglyphGamepadCamera.prototype.getClassName = function () {
  82624. return "AnaglyphGamepadCamera";
  82625. };
  82626. return AnaglyphGamepadCamera;
  82627. }(BABYLON.GamepadCamera));
  82628. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  82629. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  82630. __extends(AnaglyphUniversalCamera, _super);
  82631. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  82632. var _this = _super.call(this, name, position, scene) || this;
  82633. _this.interaxialDistance = interaxialDistance;
  82634. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82635. return _this;
  82636. }
  82637. AnaglyphUniversalCamera.prototype.getClassName = function () {
  82638. return "AnaglyphUniversalCamera";
  82639. };
  82640. return AnaglyphUniversalCamera;
  82641. }(BABYLON.UniversalCamera));
  82642. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  82643. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  82644. __extends(StereoscopicFreeCamera, _super);
  82645. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82646. var _this = _super.call(this, name, position, scene) || this;
  82647. _this.interaxialDistance = interaxialDistance;
  82648. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82649. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82650. return _this;
  82651. }
  82652. StereoscopicFreeCamera.prototype.getClassName = function () {
  82653. return "StereoscopicFreeCamera";
  82654. };
  82655. return StereoscopicFreeCamera;
  82656. }(BABYLON.FreeCamera));
  82657. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  82658. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  82659. __extends(StereoscopicArcRotateCamera, _super);
  82660. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  82661. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82662. _this.interaxialDistance = interaxialDistance;
  82663. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82664. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82665. return _this;
  82666. }
  82667. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  82668. return "StereoscopicArcRotateCamera";
  82669. };
  82670. return StereoscopicArcRotateCamera;
  82671. }(BABYLON.ArcRotateCamera));
  82672. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  82673. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  82674. __extends(StereoscopicGamepadCamera, _super);
  82675. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82676. var _this = _super.call(this, name, position, scene) || this;
  82677. _this.interaxialDistance = interaxialDistance;
  82678. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82679. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82680. return _this;
  82681. }
  82682. StereoscopicGamepadCamera.prototype.getClassName = function () {
  82683. return "StereoscopicGamepadCamera";
  82684. };
  82685. return StereoscopicGamepadCamera;
  82686. }(BABYLON.GamepadCamera));
  82687. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  82688. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  82689. __extends(StereoscopicUniversalCamera, _super);
  82690. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82691. var _this = _super.call(this, name, position, scene) || this;
  82692. _this.interaxialDistance = interaxialDistance;
  82693. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82694. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82695. return _this;
  82696. }
  82697. StereoscopicUniversalCamera.prototype.getClassName = function () {
  82698. return "StereoscopicUniversalCamera";
  82699. };
  82700. return StereoscopicUniversalCamera;
  82701. }(BABYLON.UniversalCamera));
  82702. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  82703. })(BABYLON || (BABYLON = {}));
  82704. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  82705. "use strict";
  82706. var BABYLON;
  82707. (function (BABYLON) {
  82708. var VRExperienceHelperGazer = /** @class */ (function () {
  82709. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  82710. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  82711. this.scene = scene;
  82712. this._pointerDownOnMeshAsked = false;
  82713. this._isActionableMesh = false;
  82714. this._teleportationRequestInitiated = false;
  82715. this._teleportationBackRequestInitiated = false;
  82716. this._dpadPressed = true;
  82717. this._activePointer = false;
  82718. this._id = VRExperienceHelperGazer._idCounter++;
  82719. // Gaze tracker
  82720. if (!gazeTrackerToClone) {
  82721. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  82722. this._gazeTracker.bakeCurrentTransformIntoVertices();
  82723. this._gazeTracker.isPickable = false;
  82724. this._gazeTracker.isVisible = false;
  82725. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  82726. targetMat.specularColor = BABYLON.Color3.Black();
  82727. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82728. targetMat.backFaceCulling = false;
  82729. this._gazeTracker.material = targetMat;
  82730. }
  82731. else {
  82732. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  82733. }
  82734. }
  82735. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  82736. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  82737. };
  82738. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  82739. this._pointerDownOnMeshAsked = true;
  82740. if (this._currentMeshSelected && this._currentHit) {
  82741. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  82742. }
  82743. };
  82744. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  82745. if (this._currentMeshSelected && this._currentHit) {
  82746. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  82747. }
  82748. this._pointerDownOnMeshAsked = false;
  82749. };
  82750. VRExperienceHelperGazer.prototype._activatePointer = function () {
  82751. this._activePointer = true;
  82752. };
  82753. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  82754. this._activePointer = false;
  82755. };
  82756. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  82757. };
  82758. VRExperienceHelperGazer.prototype.dispose = function () {
  82759. this._interactionsEnabled = false;
  82760. this._teleportationEnabled = false;
  82761. };
  82762. VRExperienceHelperGazer._idCounter = 0;
  82763. return VRExperienceHelperGazer;
  82764. }());
  82765. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  82766. __extends(VRExperienceHelperControllerGazer, _super);
  82767. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  82768. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  82769. _this.webVRController = webVRController;
  82770. // Laser pointer
  82771. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  82772. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  82773. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82774. laserPointerMaterial.alpha = 0.6;
  82775. _this._laserPointer.material = laserPointerMaterial;
  82776. _this._laserPointer.rotation.x = Math.PI / 2;
  82777. _this._laserPointer.position.z = -0.5;
  82778. _this._laserPointer.isVisible = false;
  82779. if (!webVRController.mesh) {
  82780. // Create an empty mesh that is used prior to loading the high quality model
  82781. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  82782. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  82783. preloadPointerPose.rotation.x = -0.7;
  82784. preloadMesh.addChild(preloadPointerPose);
  82785. webVRController.attachToMesh(preloadMesh);
  82786. }
  82787. _this._setLaserPointerParent(webVRController.mesh);
  82788. return _this;
  82789. }
  82790. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  82791. return this.webVRController.getForwardRay(length);
  82792. };
  82793. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  82794. _super.prototype._activatePointer.call(this);
  82795. this._laserPointer.isVisible = true;
  82796. };
  82797. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  82798. _super.prototype._deactivatePointer.call(this);
  82799. this._laserPointer.isVisible = false;
  82800. };
  82801. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  82802. this._laserPointer.material.emissiveColor = color;
  82803. };
  82804. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  82805. var makeNotPick = function (root) {
  82806. root.name += " laserPointer";
  82807. root.getChildMeshes().forEach(function (c) {
  82808. makeNotPick(c);
  82809. });
  82810. };
  82811. makeNotPick(mesh);
  82812. var childMeshes = mesh.getChildMeshes();
  82813. this.webVRController._pointingPoseNode = null;
  82814. for (var i = 0; i < childMeshes.length; i++) {
  82815. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  82816. mesh = childMeshes[i];
  82817. this.webVRController._pointingPoseNode = mesh;
  82818. break;
  82819. }
  82820. }
  82821. this._laserPointer.parent = mesh;
  82822. };
  82823. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  82824. this._laserPointer.scaling.y = distance;
  82825. this._laserPointer.position.z = -distance / 2;
  82826. };
  82827. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  82828. _super.prototype.dispose.call(this);
  82829. this._laserPointer.dispose();
  82830. };
  82831. return VRExperienceHelperControllerGazer;
  82832. }(VRExperienceHelperGazer));
  82833. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  82834. __extends(VRExperienceHelperCameraGazer, _super);
  82835. function VRExperienceHelperCameraGazer(getCamera, scene) {
  82836. var _this = _super.call(this, scene) || this;
  82837. _this.getCamera = getCamera;
  82838. return _this;
  82839. }
  82840. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  82841. var camera = this.getCamera();
  82842. if (camera) {
  82843. return camera.getForwardRay(length);
  82844. }
  82845. else {
  82846. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  82847. }
  82848. };
  82849. return VRExperienceHelperCameraGazer;
  82850. }(VRExperienceHelperGazer));
  82851. /**
  82852. * Helps to quickly add VR support to an existing scene.
  82853. * See http://doc.babylonjs.com/how_to/webvr_helper
  82854. */
  82855. var VRExperienceHelper = /** @class */ (function () {
  82856. /**
  82857. * Instantiates a VRExperienceHelper.
  82858. * Helps to quickly add VR support to an existing scene.
  82859. * @param scene The scene the VRExperienceHelper belongs to.
  82860. * @param webVROptions Options to modify the vr experience helper's behavior.
  82861. */
  82862. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  82863. if (webVROptions === void 0) { webVROptions = {}; }
  82864. var _this = this;
  82865. this.webVROptions = webVROptions;
  82866. // Can the system support WebVR, even if a headset isn't plugged in?
  82867. this._webVRsupported = false;
  82868. // If WebVR is supported, is a headset plugged in and are we ready to present?
  82869. this._webVRready = false;
  82870. // Are we waiting for the requestPresent callback to complete?
  82871. this._webVRrequesting = false;
  82872. // Are we presenting to the headset right now?
  82873. this._webVRpresenting = false;
  82874. // Are we presenting in the fullscreen fallback?
  82875. this._fullscreenVRpresenting = false;
  82876. /**
  82877. * Observable raised when entering VR.
  82878. */
  82879. this.onEnteringVRObservable = new BABYLON.Observable();
  82880. /**
  82881. * Observable raised when exiting VR.
  82882. */
  82883. this.onExitingVRObservable = new BABYLON.Observable();
  82884. /**
  82885. * Observable raised when controller mesh is loaded.
  82886. */
  82887. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  82888. this._useCustomVRButton = false;
  82889. this._teleportationRequested = false;
  82890. this._teleportActive = false;
  82891. this._floorMeshesCollection = [];
  82892. this._rotationAllowed = true;
  82893. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  82894. this._rotationRightAsked = false;
  82895. this._rotationLeftAsked = false;
  82896. this._isDefaultTeleportationTarget = true;
  82897. this._teleportationFillColor = "#444444";
  82898. this._teleportationBorderColor = "#FFFFFF";
  82899. this._rotationAngle = 0;
  82900. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  82901. this._padSensibilityUp = 0.65;
  82902. this._padSensibilityDown = 0.35;
  82903. this.leftController = null;
  82904. this.rightController = null;
  82905. /**
  82906. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  82907. */
  82908. this.onNewMeshSelected = new BABYLON.Observable();
  82909. /**
  82910. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  82911. */
  82912. this.onNewMeshPicked = new BABYLON.Observable();
  82913. /**
  82914. * Observable raised before camera teleportation
  82915. */
  82916. this.onBeforeCameraTeleport = new BABYLON.Observable();
  82917. /**
  82918. * Observable raised after camera teleportation
  82919. */
  82920. this.onAfterCameraTeleport = new BABYLON.Observable();
  82921. /**
  82922. * Observable raised when current selected mesh gets unselected
  82923. */
  82924. this.onSelectedMeshUnselected = new BABYLON.Observable();
  82925. /**
  82926. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  82927. */
  82928. this.teleportationEnabled = true;
  82929. this._teleportationInitialized = false;
  82930. this._interactionsEnabled = false;
  82931. this._interactionsRequested = false;
  82932. this._displayGaze = true;
  82933. this._displayLaserPointer = true;
  82934. this._onResize = function () {
  82935. _this.moveButtonToBottomRight();
  82936. if (_this._fullscreenVRpresenting && _this._webVRready) {
  82937. _this.exitVR();
  82938. }
  82939. };
  82940. this._onFullscreenChange = function () {
  82941. if (document.fullscreen !== undefined) {
  82942. _this._fullscreenVRpresenting = document.fullscreen;
  82943. }
  82944. else if (document.mozFullScreen !== undefined) {
  82945. _this._fullscreenVRpresenting = document.mozFullScreen;
  82946. }
  82947. else if (document.webkitIsFullScreen !== undefined) {
  82948. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  82949. }
  82950. else if (document.msIsFullScreen !== undefined) {
  82951. _this._fullscreenVRpresenting = document.msIsFullScreen;
  82952. }
  82953. if (!_this._fullscreenVRpresenting && _this._canvas) {
  82954. _this.exitVR();
  82955. if (!_this._useCustomVRButton) {
  82956. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  82957. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  82958. }
  82959. }
  82960. };
  82961. this.beforeRender = function () {
  82962. if (_this.leftController && _this.leftController._activePointer) {
  82963. _this._castRayAndSelectObject(_this.leftController);
  82964. }
  82965. if (_this.rightController && _this.rightController._activePointer) {
  82966. _this._castRayAndSelectObject(_this.rightController);
  82967. }
  82968. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  82969. _this._castRayAndSelectObject(_this._cameraGazer);
  82970. }
  82971. else {
  82972. _this._cameraGazer._gazeTracker.isVisible = false;
  82973. }
  82974. };
  82975. this._onNewGamepadConnected = function (gamepad) {
  82976. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  82977. if (gamepad.leftStick) {
  82978. gamepad.onleftstickchanged(function (stickValues) {
  82979. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  82980. // Listening to classic/xbox gamepad only if no VR controller is active
  82981. if ((!_this.leftController && !_this.rightController) ||
  82982. ((_this.leftController && !_this.leftController._activePointer) &&
  82983. (_this.rightController && !_this.rightController._activePointer))) {
  82984. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  82985. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  82986. }
  82987. }
  82988. });
  82989. }
  82990. if (gamepad.rightStick) {
  82991. gamepad.onrightstickchanged(function (stickValues) {
  82992. if (_this._teleportationInitialized) {
  82993. _this._checkRotate(stickValues, _this._cameraGazer);
  82994. }
  82995. });
  82996. }
  82997. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  82998. gamepad.onbuttondown(function (buttonPressed) {
  82999. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  83000. _this._cameraGazer._selectionPointerDown();
  83001. }
  83002. });
  83003. gamepad.onbuttonup(function (buttonPressed) {
  83004. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  83005. _this._cameraGazer._selectionPointerUp();
  83006. }
  83007. });
  83008. }
  83009. }
  83010. else {
  83011. var webVRController = gamepad;
  83012. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  83013. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  83014. _this.rightController = controller;
  83015. }
  83016. else {
  83017. _this.leftController = controller;
  83018. }
  83019. _this._tryEnableInteractionOnController(controller);
  83020. }
  83021. };
  83022. // 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
  83023. this._tryEnableInteractionOnController = function (controller) {
  83024. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  83025. _this._enableInteractionOnController(controller);
  83026. }
  83027. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  83028. _this._enableTeleportationOnController(controller);
  83029. }
  83030. };
  83031. this._onNewGamepadDisconnected = function (gamepad) {
  83032. if (gamepad instanceof BABYLON.WebVRController) {
  83033. if (gamepad.hand === "left" && _this.leftController != null) {
  83034. _this.leftController.dispose();
  83035. _this.leftController = null;
  83036. }
  83037. if (gamepad.hand === "right" && _this.rightController != null) {
  83038. _this.rightController.dispose();
  83039. _this.rightController = null;
  83040. }
  83041. }
  83042. };
  83043. this._workingVector = BABYLON.Vector3.Zero();
  83044. this._workingQuaternion = BABYLON.Quaternion.Identity();
  83045. this._workingMatrix = BABYLON.Matrix.Identity();
  83046. this._scene = scene;
  83047. this._canvas = scene.getEngine().getRenderingCanvas();
  83048. // Parse options
  83049. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  83050. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  83051. }
  83052. if (webVROptions.createDeviceOrientationCamera === undefined) {
  83053. webVROptions.createDeviceOrientationCamera = true;
  83054. }
  83055. if (webVROptions.defaultHeight === undefined) {
  83056. webVROptions.defaultHeight = 1.7;
  83057. }
  83058. if (webVROptions.useCustomVRButton) {
  83059. this._useCustomVRButton = true;
  83060. if (webVROptions.customVRButton) {
  83061. this._btnVR = webVROptions.customVRButton;
  83062. }
  83063. }
  83064. if (webVROptions.rayLength) {
  83065. this._rayLength = webVROptions.rayLength;
  83066. }
  83067. this._defaultHeight = webVROptions.defaultHeight;
  83068. if (webVROptions.positionScale) {
  83069. this._rayLength *= webVROptions.positionScale;
  83070. this._defaultHeight *= webVROptions.positionScale;
  83071. }
  83072. // Set position
  83073. if (this._scene.activeCamera) {
  83074. this._position = this._scene.activeCamera.position.clone();
  83075. }
  83076. else {
  83077. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  83078. }
  83079. // Set non-vr camera
  83080. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  83081. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  83082. // Copy data from existing camera
  83083. if (this._scene.activeCamera) {
  83084. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  83085. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  83086. // Set rotation from previous camera
  83087. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  83088. var targetCamera = this._scene.activeCamera;
  83089. if (targetCamera.rotationQuaternion) {
  83090. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  83091. }
  83092. else {
  83093. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  83094. }
  83095. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  83096. }
  83097. }
  83098. this._scene.activeCamera = this._deviceOrientationCamera;
  83099. if (this._canvas) {
  83100. this._scene.activeCamera.attachControl(this._canvas);
  83101. }
  83102. }
  83103. else {
  83104. this._existingCamera = this._scene.activeCamera;
  83105. }
  83106. // Create VR cameras
  83107. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  83108. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  83109. }
  83110. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  83111. this._webVRCamera.useStandingMatrix();
  83112. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  83113. // Create default button
  83114. if (!this._useCustomVRButton) {
  83115. this._btnVR = document.createElement("BUTTON");
  83116. this._btnVR.className = "babylonVRicon";
  83117. this._btnVR.id = "babylonVRiconbtn";
  83118. this._btnVR.title = "Click to switch to VR";
  83119. 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) }";
  83120. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  83121. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  83122. // css += ".babylonVRicon.vrdisplaysupported { }";
  83123. // css += ".babylonVRicon.vrdisplayready { }";
  83124. // css += ".babylonVRicon.vrdisplayrequesting { }";
  83125. var style = document.createElement('style');
  83126. style.appendChild(document.createTextNode(css));
  83127. document.getElementsByTagName('head')[0].appendChild(style);
  83128. this.moveButtonToBottomRight();
  83129. }
  83130. // VR button click event
  83131. if (this._btnVR) {
  83132. this._btnVR.addEventListener("click", function () {
  83133. if (!_this.isInVRMode) {
  83134. _this.enterVR();
  83135. }
  83136. else {
  83137. _this.exitVR();
  83138. }
  83139. });
  83140. }
  83141. // Window events
  83142. window.addEventListener("resize", this._onResize);
  83143. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  83144. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  83145. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  83146. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  83147. // Display vr button when headset is connected
  83148. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  83149. this.displayVRButton();
  83150. }
  83151. else {
  83152. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  83153. if (e.vrDisplay) {
  83154. _this.displayVRButton();
  83155. }
  83156. });
  83157. }
  83158. // Exiting VR mode using 'ESC' key on desktop
  83159. this._onKeyDown = function (event) {
  83160. if (event.keyCode === 27 && _this.isInVRMode) {
  83161. _this.exitVR();
  83162. }
  83163. };
  83164. document.addEventListener("keydown", this._onKeyDown);
  83165. // Exiting VR mode double tapping the touch screen
  83166. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  83167. if (_this.isInVRMode) {
  83168. _this.exitVR();
  83169. if (_this._fullscreenVRpresenting) {
  83170. _this._scene.getEngine().switchFullscreen(true);
  83171. }
  83172. }
  83173. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  83174. // Listen for WebVR display changes
  83175. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  83176. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  83177. this._onVRRequestPresentStart = function () {
  83178. _this._webVRrequesting = true;
  83179. _this.updateButtonVisibility();
  83180. };
  83181. this._onVRRequestPresentComplete = function (success) {
  83182. _this._webVRrequesting = false;
  83183. _this.updateButtonVisibility();
  83184. };
  83185. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  83186. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  83187. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  83188. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83189. scene.onDisposeObservable.add(function () {
  83190. _this.dispose();
  83191. });
  83192. // Gamepad connection events
  83193. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  83194. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  83195. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  83196. this.updateButtonVisibility();
  83197. //create easing functions
  83198. this._circleEase = new BABYLON.CircleEase();
  83199. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83200. }
  83201. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  83202. /** Return this.onEnteringVRObservable
  83203. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  83204. */
  83205. get: function () {
  83206. return this.onEnteringVRObservable;
  83207. },
  83208. enumerable: true,
  83209. configurable: true
  83210. });
  83211. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  83212. /** Return this.onExitingVRObservable
  83213. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  83214. */
  83215. get: function () {
  83216. return this.onExitingVRObservable;
  83217. },
  83218. enumerable: true,
  83219. configurable: true
  83220. });
  83221. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  83222. /** Return this.onControllerMeshLoadedObservable
  83223. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  83224. */
  83225. get: function () {
  83226. return this.onControllerMeshLoadedObservable;
  83227. },
  83228. enumerable: true,
  83229. configurable: true
  83230. });
  83231. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  83232. /**
  83233. * The mesh used to display where the user is going to teleport.
  83234. */
  83235. get: function () {
  83236. return this._teleportationTarget;
  83237. },
  83238. /**
  83239. * Sets the mesh to be used to display where the user is going to teleport.
  83240. */
  83241. set: function (value) {
  83242. if (value) {
  83243. value.name = "teleportationTarget";
  83244. this._isDefaultTeleportationTarget = false;
  83245. this._teleportationTarget = value;
  83246. }
  83247. },
  83248. enumerable: true,
  83249. configurable: true
  83250. });
  83251. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  83252. /**
  83253. * The mesh used to display where the user is selecting,
  83254. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  83255. * See http://doc.babylonjs.com/resources/baking_transformations
  83256. */
  83257. get: function () {
  83258. return this._cameraGazer._gazeTracker;
  83259. },
  83260. set: function (value) {
  83261. if (value) {
  83262. this._cameraGazer._gazeTracker = value;
  83263. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  83264. this._cameraGazer._gazeTracker.isPickable = false;
  83265. this._cameraGazer._gazeTracker.isVisible = false;
  83266. this._cameraGazer._gazeTracker.name = "gazeTracker";
  83267. if (this.leftController) {
  83268. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  83269. }
  83270. if (this.rightController) {
  83271. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  83272. }
  83273. }
  83274. },
  83275. enumerable: true,
  83276. configurable: true
  83277. });
  83278. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  83279. /**
  83280. * If the ray of the gaze should be displayed.
  83281. */
  83282. get: function () {
  83283. return this._displayGaze;
  83284. },
  83285. /**
  83286. * Sets if the ray of the gaze should be displayed.
  83287. */
  83288. set: function (value) {
  83289. this._displayGaze = value;
  83290. if (!value) {
  83291. this._cameraGazer._gazeTracker.isVisible = false;
  83292. if (this.leftController) {
  83293. this.leftController._gazeTracker.isVisible = false;
  83294. }
  83295. if (this.rightController) {
  83296. this.rightController._gazeTracker.isVisible = false;
  83297. }
  83298. }
  83299. },
  83300. enumerable: true,
  83301. configurable: true
  83302. });
  83303. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  83304. /**
  83305. * If the ray of the LaserPointer should be displayed.
  83306. */
  83307. get: function () {
  83308. return this._displayLaserPointer;
  83309. },
  83310. /**
  83311. * Sets if the ray of the LaserPointer should be displayed.
  83312. */
  83313. set: function (value) {
  83314. this._displayLaserPointer = value;
  83315. if (!value) {
  83316. if (this.rightController) {
  83317. this.rightController._deactivatePointer();
  83318. this.rightController._gazeTracker.isVisible = false;
  83319. }
  83320. if (this.leftController) {
  83321. this.leftController._deactivatePointer();
  83322. this.leftController._gazeTracker.isVisible = false;
  83323. }
  83324. }
  83325. else {
  83326. if (this.rightController) {
  83327. this.rightController._activatePointer();
  83328. }
  83329. else if (this.leftController) {
  83330. this.leftController._activatePointer();
  83331. }
  83332. }
  83333. },
  83334. enumerable: true,
  83335. configurable: true
  83336. });
  83337. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  83338. /**
  83339. * The deviceOrientationCamera used as the camera when not in VR.
  83340. */
  83341. get: function () {
  83342. return this._deviceOrientationCamera;
  83343. },
  83344. enumerable: true,
  83345. configurable: true
  83346. });
  83347. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  83348. /**
  83349. * Based on the current WebVR support, returns the current VR camera used.
  83350. */
  83351. get: function () {
  83352. if (this._webVRready) {
  83353. return this._webVRCamera;
  83354. }
  83355. else {
  83356. return this._scene.activeCamera;
  83357. }
  83358. },
  83359. enumerable: true,
  83360. configurable: true
  83361. });
  83362. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  83363. /**
  83364. * The webVRCamera which is used when in VR.
  83365. */
  83366. get: function () {
  83367. return this._webVRCamera;
  83368. },
  83369. enumerable: true,
  83370. configurable: true
  83371. });
  83372. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  83373. /**
  83374. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  83375. */
  83376. get: function () {
  83377. return this._vrDeviceOrientationCamera;
  83378. },
  83379. enumerable: true,
  83380. configurable: true
  83381. });
  83382. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  83383. get: function () {
  83384. var result = this._cameraGazer._teleportationRequestInitiated
  83385. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  83386. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  83387. return result;
  83388. },
  83389. enumerable: true,
  83390. configurable: true
  83391. });
  83392. // Raised when one of the controller has loaded successfully its associated default mesh
  83393. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  83394. if (this.leftController && this.leftController.webVRController == webVRController) {
  83395. if (webVRController.mesh) {
  83396. this.leftController._setLaserPointerParent(webVRController.mesh);
  83397. }
  83398. }
  83399. if (this.rightController && this.rightController.webVRController == webVRController) {
  83400. if (webVRController.mesh) {
  83401. this.rightController._setLaserPointerParent(webVRController.mesh);
  83402. }
  83403. }
  83404. try {
  83405. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  83406. }
  83407. catch (err) {
  83408. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  83409. }
  83410. };
  83411. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  83412. /**
  83413. * Gets a value indicating if we are currently in VR mode.
  83414. */
  83415. get: function () {
  83416. return this._webVRpresenting || this._fullscreenVRpresenting;
  83417. },
  83418. enumerable: true,
  83419. configurable: true
  83420. });
  83421. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  83422. var vrDisplay = this._scene.getEngine().getVRDevice();
  83423. if (vrDisplay) {
  83424. var wasPresenting = this._webVRpresenting;
  83425. // A VR display is connected
  83426. this._webVRpresenting = vrDisplay.isPresenting;
  83427. if (wasPresenting && !this._webVRpresenting)
  83428. this.exitVR();
  83429. }
  83430. else {
  83431. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  83432. }
  83433. this.updateButtonVisibility();
  83434. };
  83435. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  83436. this._webVRsupported = eventArgs.vrSupported;
  83437. this._webVRready = !!eventArgs.vrDisplay;
  83438. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  83439. this.updateButtonVisibility();
  83440. };
  83441. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  83442. if (this._canvas && !this._useCustomVRButton) {
  83443. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  83444. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  83445. }
  83446. };
  83447. VRExperienceHelper.prototype.displayVRButton = function () {
  83448. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  83449. document.body.appendChild(this._btnVR);
  83450. this._btnVRDisplayed = true;
  83451. }
  83452. };
  83453. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  83454. if (!this._btnVR || this._useCustomVRButton) {
  83455. return;
  83456. }
  83457. this._btnVR.className = "babylonVRicon";
  83458. if (this.isInVRMode) {
  83459. this._btnVR.className += " vrdisplaypresenting";
  83460. }
  83461. else {
  83462. if (this._webVRready)
  83463. this._btnVR.className += " vrdisplayready";
  83464. if (this._webVRsupported)
  83465. this._btnVR.className += " vrdisplaysupported";
  83466. if (this._webVRrequesting)
  83467. this._btnVR.className += " vrdisplayrequesting";
  83468. }
  83469. };
  83470. /**
  83471. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  83472. * Otherwise, will use the fullscreen API.
  83473. */
  83474. VRExperienceHelper.prototype.enterVR = function () {
  83475. if (this.onEnteringVRObservable) {
  83476. try {
  83477. this.onEnteringVRObservable.notifyObservers(this);
  83478. }
  83479. catch (err) {
  83480. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  83481. }
  83482. }
  83483. if (this._scene.activeCamera) {
  83484. this._position = this._scene.activeCamera.position.clone();
  83485. // make sure that we return to the last active camera
  83486. this._existingCamera = this._scene.activeCamera;
  83487. }
  83488. if (this._webVRrequesting)
  83489. return;
  83490. // If WebVR is supported and a headset is connected
  83491. if (this._webVRready) {
  83492. if (!this._webVRpresenting) {
  83493. this._webVRCamera.position = this._position;
  83494. this._scene.activeCamera = this._webVRCamera;
  83495. }
  83496. }
  83497. else if (this._vrDeviceOrientationCamera) {
  83498. this._vrDeviceOrientationCamera.position = this._position;
  83499. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  83500. this._scene.getEngine().switchFullscreen(true);
  83501. this.updateButtonVisibility();
  83502. }
  83503. if (this._scene.activeCamera && this._canvas) {
  83504. this._scene.activeCamera.attachControl(this._canvas);
  83505. }
  83506. if (this._interactionsEnabled) {
  83507. this._scene.registerBeforeRender(this.beforeRender);
  83508. }
  83509. };
  83510. /**
  83511. * Attempt to exit VR, or fullscreen.
  83512. */
  83513. VRExperienceHelper.prototype.exitVR = function () {
  83514. if (this.onExitingVRObservable) {
  83515. try {
  83516. this.onExitingVRObservable.notifyObservers(this);
  83517. }
  83518. catch (err) {
  83519. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  83520. }
  83521. }
  83522. if (this._webVRpresenting) {
  83523. this._scene.getEngine().disableVR();
  83524. }
  83525. if (this._scene.activeCamera) {
  83526. this._position = this._scene.activeCamera.position.clone();
  83527. }
  83528. if (this._deviceOrientationCamera) {
  83529. this._deviceOrientationCamera.position = this._position;
  83530. this._scene.activeCamera = this._deviceOrientationCamera;
  83531. if (this._canvas) {
  83532. this._scene.activeCamera.attachControl(this._canvas);
  83533. }
  83534. }
  83535. else if (this._existingCamera) {
  83536. this._existingCamera.position = this._position;
  83537. this._scene.activeCamera = this._existingCamera;
  83538. }
  83539. this.updateButtonVisibility();
  83540. if (this._interactionsEnabled) {
  83541. this._scene.unregisterBeforeRender(this.beforeRender);
  83542. }
  83543. };
  83544. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  83545. /**
  83546. * The position of the vr experience helper.
  83547. */
  83548. get: function () {
  83549. return this._position;
  83550. },
  83551. /**
  83552. * Sets the position of the vr experience helper.
  83553. */
  83554. set: function (value) {
  83555. this._position = value;
  83556. if (this._scene.activeCamera) {
  83557. this._scene.activeCamera.position = value;
  83558. }
  83559. },
  83560. enumerable: true,
  83561. configurable: true
  83562. });
  83563. /**
  83564. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  83565. */
  83566. VRExperienceHelper.prototype.enableInteractions = function () {
  83567. var _this = this;
  83568. if (!this._interactionsEnabled) {
  83569. this._interactionsRequested = true;
  83570. if (this.leftController) {
  83571. this._enableInteractionOnController(this.leftController);
  83572. }
  83573. if (this.rightController) {
  83574. this._enableInteractionOnController(this.rightController);
  83575. }
  83576. this.raySelectionPredicate = function (mesh) {
  83577. return mesh.isVisible;
  83578. };
  83579. this.meshSelectionPredicate = function (mesh) {
  83580. return true;
  83581. };
  83582. this._raySelectionPredicate = function (mesh) {
  83583. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  83584. && mesh.name.indexOf("teleportationTarget") === -1
  83585. && mesh.name.indexOf("torusTeleportation") === -1
  83586. && mesh.name.indexOf("laserPointer") === -1)) {
  83587. return _this.raySelectionPredicate(mesh);
  83588. }
  83589. return false;
  83590. };
  83591. this._interactionsEnabled = true;
  83592. }
  83593. };
  83594. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  83595. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  83596. if (this._floorMeshesCollection[i].id === mesh.id) {
  83597. return true;
  83598. }
  83599. }
  83600. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  83601. return true;
  83602. }
  83603. return false;
  83604. };
  83605. /**
  83606. * Adds a floor mesh to be used for teleportation.
  83607. * @param floorMesh the mesh to be used for teleportation.
  83608. */
  83609. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  83610. if (!this._floorMeshesCollection) {
  83611. return;
  83612. }
  83613. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  83614. return;
  83615. }
  83616. this._floorMeshesCollection.push(floorMesh);
  83617. };
  83618. /**
  83619. * Removes a floor mesh from being used for teleportation.
  83620. * @param floorMesh the mesh to be removed.
  83621. */
  83622. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  83623. if (!this._floorMeshesCollection) {
  83624. return;
  83625. }
  83626. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  83627. if (meshIndex !== -1) {
  83628. this._floorMeshesCollection.splice(meshIndex, 1);
  83629. }
  83630. };
  83631. /**
  83632. * Enables interactions and teleportation using the VR controllers and gaze.
  83633. * @param vrTeleportationOptions options to modify teleportation behavior.
  83634. */
  83635. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  83636. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  83637. if (!this._teleportationInitialized) {
  83638. this._teleportationRequested = true;
  83639. this.enableInteractions();
  83640. if (vrTeleportationOptions.floorMeshName) {
  83641. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  83642. }
  83643. if (vrTeleportationOptions.floorMeshes) {
  83644. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  83645. }
  83646. if (this.leftController != null) {
  83647. this._enableTeleportationOnController(this.leftController);
  83648. }
  83649. if (this.rightController != null) {
  83650. this._enableTeleportationOnController(this.rightController);
  83651. }
  83652. // Creates an image processing post process for the vignette not relying
  83653. // on the main scene configuration for image processing to reduce setup and spaces
  83654. // (gamma/linear) conflicts.
  83655. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  83656. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  83657. imageProcessingConfiguration.vignetteEnabled = true;
  83658. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  83659. this._webVRCamera.detachPostProcess(this._postProcessMove);
  83660. this._teleportationInitialized = true;
  83661. if (this._isDefaultTeleportationTarget) {
  83662. this._createTeleportationCircles();
  83663. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  83664. }
  83665. }
  83666. };
  83667. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  83668. var _this = this;
  83669. var controllerMesh = controller.webVRController.mesh;
  83670. if (controllerMesh) {
  83671. controller._interactionsEnabled = true;
  83672. controller._activatePointer();
  83673. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  83674. // Enabling / disabling laserPointer
  83675. if (_this._displayLaserPointer && stateObject.value === 1) {
  83676. if (controller._activePointer) {
  83677. controller._deactivatePointer();
  83678. }
  83679. else {
  83680. controller._activatePointer();
  83681. }
  83682. if (_this.displayGaze) {
  83683. controller._gazeTracker.isVisible = controller._activePointer;
  83684. }
  83685. }
  83686. });
  83687. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  83688. if (!controller._pointerDownOnMeshAsked) {
  83689. if (stateObject.value > _this._padSensibilityUp) {
  83690. controller._selectionPointerDown();
  83691. }
  83692. }
  83693. else if (stateObject.value < _this._padSensibilityDown) {
  83694. controller._selectionPointerUp();
  83695. }
  83696. });
  83697. }
  83698. };
  83699. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  83700. // Dont teleport if another gaze already requested teleportation
  83701. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  83702. return;
  83703. }
  83704. if (!gazer._teleportationRequestInitiated) {
  83705. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  83706. gazer._activatePointer();
  83707. gazer._teleportationRequestInitiated = true;
  83708. }
  83709. }
  83710. else {
  83711. // Listening to the proper controller values changes to confirm teleportation
  83712. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  83713. if (this._teleportActive) {
  83714. this._teleportCamera(this._haloCenter);
  83715. }
  83716. gazer._teleportationRequestInitiated = false;
  83717. }
  83718. }
  83719. };
  83720. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  83721. // Only rotate when user is not currently selecting a teleportation location
  83722. if (gazer._teleportationRequestInitiated) {
  83723. return;
  83724. }
  83725. if (!this._rotationLeftAsked) {
  83726. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  83727. this._rotationLeftAsked = true;
  83728. if (this._rotationAllowed) {
  83729. this._rotateCamera(false);
  83730. }
  83731. }
  83732. }
  83733. else {
  83734. if (stateObject.x > -this._padSensibilityDown) {
  83735. this._rotationLeftAsked = false;
  83736. }
  83737. }
  83738. if (!this._rotationRightAsked) {
  83739. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  83740. this._rotationRightAsked = true;
  83741. if (this._rotationAllowed) {
  83742. this._rotateCamera(true);
  83743. }
  83744. }
  83745. }
  83746. else {
  83747. if (stateObject.x < this._padSensibilityDown) {
  83748. this._rotationRightAsked = false;
  83749. }
  83750. }
  83751. };
  83752. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  83753. // Only teleport backwards when user is not currently selecting a teleportation location
  83754. if (gazer._teleportationRequestInitiated) {
  83755. return;
  83756. }
  83757. // Teleport backwards
  83758. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  83759. if (!gazer._teleportationBackRequestInitiated) {
  83760. if (!this.currentVRCamera) {
  83761. return;
  83762. }
  83763. // Get rotation and position of the current camera
  83764. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  83765. var position = this.currentVRCamera.position;
  83766. // If the camera has device position, use that instead
  83767. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  83768. rotation = this.currentVRCamera.deviceRotationQuaternion;
  83769. position = this.currentVRCamera.devicePosition;
  83770. }
  83771. // Get matrix with only the y rotation of the device rotation
  83772. rotation.toEulerAnglesToRef(this._workingVector);
  83773. this._workingVector.z = 0;
  83774. this._workingVector.x = 0;
  83775. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  83776. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  83777. // Rotate backwards ray by device rotation to cast at the ground behind the user
  83778. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  83779. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  83780. var ray = new BABYLON.Ray(position, this._workingVector);
  83781. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  83782. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  83783. this._teleportCamera(hit.pickedPoint);
  83784. }
  83785. gazer._teleportationBackRequestInitiated = true;
  83786. }
  83787. }
  83788. else {
  83789. gazer._teleportationBackRequestInitiated = false;
  83790. }
  83791. };
  83792. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  83793. var _this = this;
  83794. var controllerMesh = controller.webVRController.mesh;
  83795. if (controllerMesh) {
  83796. if (!controller._interactionsEnabled) {
  83797. this._enableInteractionOnController(controller);
  83798. }
  83799. controller._interactionsEnabled = true;
  83800. controller._teleportationEnabled = true;
  83801. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  83802. controller._dpadPressed = false;
  83803. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  83804. controller._dpadPressed = stateObject.pressed;
  83805. if (!controller._dpadPressed) {
  83806. _this._rotationLeftAsked = false;
  83807. _this._rotationRightAsked = false;
  83808. controller._teleportationBackRequestInitiated = false;
  83809. }
  83810. });
  83811. }
  83812. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  83813. if (_this.teleportationEnabled) {
  83814. _this._checkTeleportBackwards(stateObject, controller);
  83815. _this._checkTeleportWithRay(stateObject, controller);
  83816. }
  83817. _this._checkRotate(stateObject, controller);
  83818. });
  83819. }
  83820. };
  83821. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  83822. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  83823. this._teleportationTarget.isPickable = false;
  83824. var length = 512;
  83825. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  83826. dynamicTexture.hasAlpha = true;
  83827. var context = dynamicTexture.getContext();
  83828. var centerX = length / 2;
  83829. var centerY = length / 2;
  83830. var radius = 200;
  83831. context.beginPath();
  83832. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  83833. context.fillStyle = this._teleportationFillColor;
  83834. context.fill();
  83835. context.lineWidth = 10;
  83836. context.strokeStyle = this._teleportationBorderColor;
  83837. context.stroke();
  83838. context.closePath();
  83839. dynamicTexture.update();
  83840. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  83841. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  83842. this._teleportationTarget.material = teleportationCircleMaterial;
  83843. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  83844. torus.isPickable = false;
  83845. torus.parent = this._teleportationTarget;
  83846. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  83847. var keys = [];
  83848. keys.push({
  83849. frame: 0,
  83850. value: 0
  83851. });
  83852. keys.push({
  83853. frame: 30,
  83854. value: 0.4
  83855. });
  83856. keys.push({
  83857. frame: 60,
  83858. value: 0
  83859. });
  83860. animationInnerCircle.setKeys(keys);
  83861. var easingFunction = new BABYLON.SineEase();
  83862. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83863. animationInnerCircle.setEasingFunction(easingFunction);
  83864. torus.animations = [];
  83865. torus.animations.push(animationInnerCircle);
  83866. this._scene.beginAnimation(torus, 0, 60, true);
  83867. this._hideTeleportationTarget();
  83868. };
  83869. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  83870. this._teleportActive = true;
  83871. if (this._teleportationInitialized) {
  83872. this._teleportationTarget.isVisible = true;
  83873. if (this._isDefaultTeleportationTarget) {
  83874. this._teleportationTarget.getChildren()[0].isVisible = true;
  83875. }
  83876. }
  83877. };
  83878. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  83879. this._teleportActive = false;
  83880. if (this._teleportationInitialized) {
  83881. this._teleportationTarget.isVisible = false;
  83882. if (this._isDefaultTeleportationTarget) {
  83883. this._teleportationTarget.getChildren()[0].isVisible = false;
  83884. }
  83885. }
  83886. };
  83887. VRExperienceHelper.prototype._rotateCamera = function (right) {
  83888. var _this = this;
  83889. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83890. return;
  83891. }
  83892. if (right) {
  83893. this._rotationAngle++;
  83894. }
  83895. else {
  83896. this._rotationAngle--;
  83897. }
  83898. this.currentVRCamera.animations = [];
  83899. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  83900. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83901. var animationRotationKeys = [];
  83902. animationRotationKeys.push({
  83903. frame: 0,
  83904. value: this.currentVRCamera.rotationQuaternion
  83905. });
  83906. animationRotationKeys.push({
  83907. frame: 6,
  83908. value: target
  83909. });
  83910. animationRotation.setKeys(animationRotationKeys);
  83911. animationRotation.setEasingFunction(this._circleEase);
  83912. this.currentVRCamera.animations.push(animationRotation);
  83913. this._postProcessMove.animations = [];
  83914. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83915. var vignetteWeightKeys = [];
  83916. vignetteWeightKeys.push({
  83917. frame: 0,
  83918. value: 0
  83919. });
  83920. vignetteWeightKeys.push({
  83921. frame: 3,
  83922. value: 4
  83923. });
  83924. vignetteWeightKeys.push({
  83925. frame: 6,
  83926. value: 0
  83927. });
  83928. animationPP.setKeys(vignetteWeightKeys);
  83929. animationPP.setEasingFunction(this._circleEase);
  83930. this._postProcessMove.animations.push(animationPP);
  83931. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83932. var vignetteStretchKeys = [];
  83933. vignetteStretchKeys.push({
  83934. frame: 0,
  83935. value: 0
  83936. });
  83937. vignetteStretchKeys.push({
  83938. frame: 3,
  83939. value: 10
  83940. });
  83941. vignetteStretchKeys.push({
  83942. frame: 6,
  83943. value: 0
  83944. });
  83945. animationPP2.setKeys(vignetteStretchKeys);
  83946. animationPP2.setEasingFunction(this._circleEase);
  83947. this._postProcessMove.animations.push(animationPP2);
  83948. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83949. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83950. this._postProcessMove.samples = 4;
  83951. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83952. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  83953. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83954. });
  83955. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  83956. };
  83957. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  83958. if (hit.pickedPoint) {
  83959. if (gazer._teleportationRequestInitiated) {
  83960. this._displayTeleportationTarget();
  83961. this._haloCenter.copyFrom(hit.pickedPoint);
  83962. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  83963. }
  83964. var pickNormal = hit.getNormal(true, false);
  83965. if (pickNormal) {
  83966. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83967. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83968. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  83969. }
  83970. this._teleportationTarget.position.y += 0.1;
  83971. }
  83972. };
  83973. VRExperienceHelper.prototype._teleportCamera = function (location) {
  83974. var _this = this;
  83975. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83976. return;
  83977. }
  83978. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  83979. // offset of the headset from the anchor.
  83980. if (this.webVRCamera.leftCamera) {
  83981. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  83982. this._workingVector.subtractInPlace(this.webVRCamera.position);
  83983. location.subtractToRef(this._workingVector, this._workingVector);
  83984. }
  83985. else {
  83986. this._workingVector.copyFrom(location);
  83987. }
  83988. // Add height to account for user's height offset
  83989. if (this.isInVRMode) {
  83990. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  83991. }
  83992. else {
  83993. this._workingVector.y += this._defaultHeight;
  83994. }
  83995. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  83996. // Create animation from the camera's position to the new location
  83997. this.currentVRCamera.animations = [];
  83998. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83999. var animationCameraTeleportationKeys = [{
  84000. frame: 0,
  84001. value: this.currentVRCamera.position
  84002. },
  84003. {
  84004. frame: 11,
  84005. value: this._workingVector
  84006. }
  84007. ];
  84008. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  84009. animationCameraTeleportation.setEasingFunction(this._circleEase);
  84010. this.currentVRCamera.animations.push(animationCameraTeleportation);
  84011. this._postProcessMove.animations = [];
  84012. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84013. var vignetteWeightKeys = [];
  84014. vignetteWeightKeys.push({
  84015. frame: 0,
  84016. value: 0
  84017. });
  84018. vignetteWeightKeys.push({
  84019. frame: 5,
  84020. value: 8
  84021. });
  84022. vignetteWeightKeys.push({
  84023. frame: 11,
  84024. value: 0
  84025. });
  84026. animationPP.setKeys(vignetteWeightKeys);
  84027. this._postProcessMove.animations.push(animationPP);
  84028. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84029. var vignetteStretchKeys = [];
  84030. vignetteStretchKeys.push({
  84031. frame: 0,
  84032. value: 0
  84033. });
  84034. vignetteStretchKeys.push({
  84035. frame: 5,
  84036. value: 10
  84037. });
  84038. vignetteStretchKeys.push({
  84039. frame: 11,
  84040. value: 0
  84041. });
  84042. animationPP2.setKeys(vignetteStretchKeys);
  84043. this._postProcessMove.animations.push(animationPP2);
  84044. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  84045. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  84046. this._webVRCamera.attachPostProcess(this._postProcessMove);
  84047. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  84048. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  84049. });
  84050. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  84051. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  84052. });
  84053. this._hideTeleportationTarget();
  84054. };
  84055. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  84056. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  84057. return;
  84058. }
  84059. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  84060. // Moving the gazeTracker on the mesh face targetted
  84061. if (hit && hit.pickedPoint) {
  84062. if (this._displayGaze) {
  84063. var multiplier = 1;
  84064. gazer._gazeTracker.isVisible = true;
  84065. if (gazer._isActionableMesh) {
  84066. multiplier = 3;
  84067. }
  84068. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  84069. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  84070. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  84071. var pickNormal = hit.getNormal();
  84072. // To avoid z-fighting
  84073. var deltaFighting = 0.002;
  84074. if (pickNormal) {
  84075. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  84076. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  84077. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  84078. }
  84079. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  84080. if (gazer._gazeTracker.position.x < 0) {
  84081. gazer._gazeTracker.position.x += deltaFighting;
  84082. }
  84083. else {
  84084. gazer._gazeTracker.position.x -= deltaFighting;
  84085. }
  84086. if (gazer._gazeTracker.position.y < 0) {
  84087. gazer._gazeTracker.position.y += deltaFighting;
  84088. }
  84089. else {
  84090. gazer._gazeTracker.position.y -= deltaFighting;
  84091. }
  84092. if (gazer._gazeTracker.position.z < 0) {
  84093. gazer._gazeTracker.position.z += deltaFighting;
  84094. }
  84095. else {
  84096. gazer._gazeTracker.position.z -= deltaFighting;
  84097. }
  84098. }
  84099. // Changing the size of the laser pointer based on the distance from the targetted point
  84100. gazer._updatePointerDistance(hit.distance);
  84101. }
  84102. else {
  84103. gazer._gazeTracker.isVisible = false;
  84104. }
  84105. if (hit && hit.pickedMesh) {
  84106. gazer._currentHit = hit;
  84107. if (gazer._pointerDownOnMeshAsked) {
  84108. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  84109. }
  84110. // The object selected is the floor, we're in a teleportation scenario
  84111. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  84112. // Moving the teleportation area to this targetted point
  84113. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  84114. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  84115. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84116. }
  84117. gazer._currentMeshSelected = null;
  84118. if (gazer._teleportationRequestInitiated) {
  84119. this._moveTeleportationSelectorTo(hit, gazer);
  84120. }
  84121. return;
  84122. }
  84123. // If not, we're in a selection scenario
  84124. //this._teleportationAllowed = false;
  84125. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  84126. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  84127. this.onNewMeshPicked.notifyObservers(hit);
  84128. gazer._currentMeshSelected = hit.pickedMesh;
  84129. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  84130. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  84131. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  84132. gazer._isActionableMesh = true;
  84133. }
  84134. else {
  84135. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84136. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84137. gazer._isActionableMesh = false;
  84138. }
  84139. try {
  84140. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  84141. }
  84142. catch (err) {
  84143. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  84144. }
  84145. }
  84146. else {
  84147. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84148. gazer._currentMeshSelected = null;
  84149. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84150. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84151. }
  84152. }
  84153. }
  84154. else {
  84155. gazer._currentHit = null;
  84156. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84157. gazer._currentMeshSelected = null;
  84158. //this._teleportationAllowed = false;
  84159. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84160. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84161. }
  84162. };
  84163. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  84164. if (mesh) {
  84165. this.onSelectedMeshUnselected.notifyObservers(mesh);
  84166. }
  84167. };
  84168. /**
  84169. * Sets the color of the laser ray from the vr controllers.
  84170. * @param color new color for the ray.
  84171. */
  84172. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  84173. if (this.leftController) {
  84174. this.leftController._setLaserPointerColor(color);
  84175. }
  84176. if (this.rightController) {
  84177. this.rightController._setLaserPointerColor(color);
  84178. }
  84179. };
  84180. /**
  84181. * Sets the color of the ray from the vr headsets gaze.
  84182. * @param color new color for the ray.
  84183. */
  84184. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  84185. if (!this._cameraGazer._gazeTracker.material) {
  84186. return;
  84187. }
  84188. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  84189. if (this.leftController) {
  84190. this.leftController._gazeTracker.material.emissiveColor = color;
  84191. }
  84192. if (this.rightController) {
  84193. this.rightController._gazeTracker.material.emissiveColor = color;
  84194. }
  84195. };
  84196. /**
  84197. * Exits VR and disposes of the vr experience helper
  84198. */
  84199. VRExperienceHelper.prototype.dispose = function () {
  84200. if (this.isInVRMode) {
  84201. this.exitVR();
  84202. }
  84203. if (this._postProcessMove) {
  84204. this._postProcessMove.dispose();
  84205. }
  84206. if (this._webVRCamera) {
  84207. this._webVRCamera.dispose();
  84208. }
  84209. if (this._vrDeviceOrientationCamera) {
  84210. this._vrDeviceOrientationCamera.dispose();
  84211. }
  84212. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  84213. document.body.removeChild(this._btnVR);
  84214. }
  84215. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  84216. this._deviceOrientationCamera.dispose();
  84217. }
  84218. if (this._cameraGazer) {
  84219. this._cameraGazer.dispose();
  84220. }
  84221. if (this.leftController) {
  84222. this.leftController.dispose();
  84223. }
  84224. if (this.rightController) {
  84225. this.rightController.dispose();
  84226. }
  84227. if (this._teleportationTarget) {
  84228. this._teleportationTarget.dispose();
  84229. }
  84230. this._floorMeshesCollection = [];
  84231. document.removeEventListener("keydown", this._onKeyDown);
  84232. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  84233. window.removeEventListener("resize", this._onResize);
  84234. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  84235. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  84236. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  84237. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  84238. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  84239. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  84240. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  84241. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  84242. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  84243. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  84244. this._scene.unregisterBeforeRender(this.beforeRender);
  84245. };
  84246. /**
  84247. * Gets the name of the VRExperienceHelper class
  84248. * @returns "VRExperienceHelper"
  84249. */
  84250. VRExperienceHelper.prototype.getClassName = function () {
  84251. return "VRExperienceHelper";
  84252. };
  84253. return VRExperienceHelper;
  84254. }());
  84255. BABYLON.VRExperienceHelper = VRExperienceHelper;
  84256. })(BABYLON || (BABYLON = {}));
  84257. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  84258. "use strict";
  84259. // Mainly based on these 2 articles :
  84260. // 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
  84261. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  84262. var BABYLON;
  84263. (function (BABYLON) {
  84264. var JoystickAxis;
  84265. (function (JoystickAxis) {
  84266. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  84267. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  84268. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  84269. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  84270. var VirtualJoystick = /** @class */ (function () {
  84271. function VirtualJoystick(leftJoystick) {
  84272. var _this = this;
  84273. if (leftJoystick) {
  84274. this._leftJoystick = true;
  84275. }
  84276. else {
  84277. this._leftJoystick = false;
  84278. }
  84279. VirtualJoystick._globalJoystickIndex++;
  84280. // By default left & right arrow keys are moving the X
  84281. // and up & down keys are moving the Y
  84282. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84283. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84284. this.reverseLeftRight = false;
  84285. this.reverseUpDown = false;
  84286. // collections of pointers
  84287. this._touches = new BABYLON.StringDictionary();
  84288. this.deltaPosition = BABYLON.Vector3.Zero();
  84289. this._joystickSensibility = 25;
  84290. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84291. this._onResize = function (evt) {
  84292. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  84293. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  84294. if (VirtualJoystick.vjCanvas) {
  84295. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  84296. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  84297. }
  84298. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  84299. };
  84300. // injecting a canvas element on top of the canvas 3D game
  84301. if (!VirtualJoystick.vjCanvas) {
  84302. window.addEventListener("resize", this._onResize, false);
  84303. VirtualJoystick.vjCanvas = document.createElement("canvas");
  84304. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  84305. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  84306. VirtualJoystick.vjCanvas.width = window.innerWidth;
  84307. VirtualJoystick.vjCanvas.height = window.innerHeight;
  84308. VirtualJoystick.vjCanvas.style.width = "100%";
  84309. VirtualJoystick.vjCanvas.style.height = "100%";
  84310. VirtualJoystick.vjCanvas.style.position = "absolute";
  84311. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  84312. VirtualJoystick.vjCanvas.style.top = "0px";
  84313. VirtualJoystick.vjCanvas.style.left = "0px";
  84314. VirtualJoystick.vjCanvas.style.zIndex = "5";
  84315. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  84316. // Support for jQuery PEP polyfill
  84317. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  84318. var context = VirtualJoystick.vjCanvas.getContext('2d');
  84319. if (!context) {
  84320. throw new Error("Unable to create canvas for virtual joystick");
  84321. }
  84322. VirtualJoystick.vjCanvasContext = context;
  84323. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  84324. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84325. document.body.appendChild(VirtualJoystick.vjCanvas);
  84326. }
  84327. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  84328. this.pressed = false;
  84329. // default joystick color
  84330. this._joystickColor = "cyan";
  84331. this._joystickPointerID = -1;
  84332. // current joystick position
  84333. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  84334. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  84335. // origin joystick position
  84336. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  84337. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  84338. this._onPointerDownHandlerRef = function (evt) {
  84339. _this._onPointerDown(evt);
  84340. };
  84341. this._onPointerMoveHandlerRef = function (evt) {
  84342. _this._onPointerMove(evt);
  84343. };
  84344. this._onPointerUpHandlerRef = function (evt) {
  84345. _this._onPointerUp(evt);
  84346. };
  84347. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  84348. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  84349. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  84350. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  84351. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  84352. evt.preventDefault(); // Disables system menu
  84353. }, false);
  84354. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84355. }
  84356. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  84357. this._joystickSensibility = newJoystickSensibility;
  84358. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84359. };
  84360. VirtualJoystick.prototype._onPointerDown = function (e) {
  84361. var positionOnScreenCondition;
  84362. e.preventDefault();
  84363. if (this._leftJoystick === true) {
  84364. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  84365. }
  84366. else {
  84367. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  84368. }
  84369. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  84370. // First contact will be dedicated to the virtual joystick
  84371. this._joystickPointerID = e.pointerId;
  84372. this._joystickPointerStartPos.x = e.clientX;
  84373. this._joystickPointerStartPos.y = e.clientY;
  84374. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  84375. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  84376. this._deltaJoystickVector.x = 0;
  84377. this._deltaJoystickVector.y = 0;
  84378. this.pressed = true;
  84379. this._touches.add(e.pointerId.toString(), e);
  84380. }
  84381. else {
  84382. // You can only trigger the action buttons with a joystick declared
  84383. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  84384. this._action();
  84385. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  84386. }
  84387. }
  84388. };
  84389. VirtualJoystick.prototype._onPointerMove = function (e) {
  84390. // If the current pointer is the one associated to the joystick (first touch contact)
  84391. if (this._joystickPointerID == e.pointerId) {
  84392. this._joystickPointerPos.x = e.clientX;
  84393. this._joystickPointerPos.y = e.clientY;
  84394. this._deltaJoystickVector = this._joystickPointerPos.clone();
  84395. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  84396. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  84397. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  84398. switch (this._axisTargetedByLeftAndRight) {
  84399. case JoystickAxis.X:
  84400. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  84401. break;
  84402. case JoystickAxis.Y:
  84403. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  84404. break;
  84405. case JoystickAxis.Z:
  84406. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  84407. break;
  84408. }
  84409. var directionUpDown = this.reverseUpDown ? 1 : -1;
  84410. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  84411. switch (this._axisTargetedByUpAndDown) {
  84412. case JoystickAxis.X:
  84413. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  84414. break;
  84415. case JoystickAxis.Y:
  84416. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  84417. break;
  84418. case JoystickAxis.Z:
  84419. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  84420. break;
  84421. }
  84422. }
  84423. else {
  84424. var data = this._touches.get(e.pointerId.toString());
  84425. if (data) {
  84426. data.x = e.clientX;
  84427. data.y = e.clientY;
  84428. }
  84429. }
  84430. };
  84431. VirtualJoystick.prototype._onPointerUp = function (e) {
  84432. if (this._joystickPointerID == e.pointerId) {
  84433. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  84434. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  84435. this._joystickPointerID = -1;
  84436. this.pressed = false;
  84437. }
  84438. else {
  84439. var touch = this._touches.get(e.pointerId.toString());
  84440. if (touch) {
  84441. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84442. }
  84443. }
  84444. this._deltaJoystickVector.x = 0;
  84445. this._deltaJoystickVector.y = 0;
  84446. this._touches.remove(e.pointerId.toString());
  84447. };
  84448. /**
  84449. * Change the color of the virtual joystick
  84450. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  84451. */
  84452. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  84453. this._joystickColor = newColor;
  84454. };
  84455. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  84456. this._action = action;
  84457. };
  84458. // Define which axis you'd like to control for left & right
  84459. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  84460. switch (axis) {
  84461. case JoystickAxis.X:
  84462. case JoystickAxis.Y:
  84463. case JoystickAxis.Z:
  84464. this._axisTargetedByLeftAndRight = axis;
  84465. break;
  84466. default:
  84467. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84468. break;
  84469. }
  84470. };
  84471. // Define which axis you'd like to control for up & down
  84472. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  84473. switch (axis) {
  84474. case JoystickAxis.X:
  84475. case JoystickAxis.Y:
  84476. case JoystickAxis.Z:
  84477. this._axisTargetedByUpAndDown = axis;
  84478. break;
  84479. default:
  84480. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84481. break;
  84482. }
  84483. };
  84484. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  84485. var _this = this;
  84486. if (this.pressed) {
  84487. this._touches.forEach(function (key, touch) {
  84488. if (touch.pointerId === _this._joystickPointerID) {
  84489. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  84490. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  84491. VirtualJoystick.vjCanvasContext.beginPath();
  84492. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84493. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84494. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  84495. VirtualJoystick.vjCanvasContext.stroke();
  84496. VirtualJoystick.vjCanvasContext.closePath();
  84497. VirtualJoystick.vjCanvasContext.beginPath();
  84498. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84499. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84500. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  84501. VirtualJoystick.vjCanvasContext.stroke();
  84502. VirtualJoystick.vjCanvasContext.closePath();
  84503. VirtualJoystick.vjCanvasContext.beginPath();
  84504. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84505. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  84506. VirtualJoystick.vjCanvasContext.stroke();
  84507. VirtualJoystick.vjCanvasContext.closePath();
  84508. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  84509. }
  84510. else {
  84511. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84512. VirtualJoystick.vjCanvasContext.beginPath();
  84513. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  84514. VirtualJoystick.vjCanvasContext.beginPath();
  84515. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  84516. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84517. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  84518. VirtualJoystick.vjCanvasContext.stroke();
  84519. VirtualJoystick.vjCanvasContext.closePath();
  84520. touch.prevX = touch.x;
  84521. touch.prevY = touch.y;
  84522. }
  84523. ;
  84524. });
  84525. }
  84526. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84527. };
  84528. VirtualJoystick.prototype.releaseCanvas = function () {
  84529. if (VirtualJoystick.vjCanvas) {
  84530. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  84531. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  84532. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  84533. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  84534. window.removeEventListener("resize", this._onResize);
  84535. document.body.removeChild(VirtualJoystick.vjCanvas);
  84536. VirtualJoystick.vjCanvas = null;
  84537. }
  84538. };
  84539. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  84540. VirtualJoystick._globalJoystickIndex = 0;
  84541. return VirtualJoystick;
  84542. }());
  84543. BABYLON.VirtualJoystick = VirtualJoystick;
  84544. })(BABYLON || (BABYLON = {}));
  84545. //# sourceMappingURL=babylon.virtualJoystick.js.map
  84546. "use strict";
  84547. var BABYLON;
  84548. (function (BABYLON) {
  84549. // We're mainly based on the logic defined into the FreeCamera code
  84550. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  84551. __extends(VirtualJoysticksCamera, _super);
  84552. function VirtualJoysticksCamera(name, position, scene) {
  84553. var _this = _super.call(this, name, position, scene) || this;
  84554. _this.inputs.addVirtualJoystick();
  84555. return _this;
  84556. }
  84557. VirtualJoysticksCamera.prototype.getClassName = function () {
  84558. return "VirtualJoysticksCamera";
  84559. };
  84560. return VirtualJoysticksCamera;
  84561. }(BABYLON.FreeCamera));
  84562. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  84563. })(BABYLON || (BABYLON = {}));
  84564. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  84565. "use strict";
  84566. var BABYLON;
  84567. (function (BABYLON) {
  84568. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  84569. function FreeCameraVirtualJoystickInput() {
  84570. }
  84571. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  84572. return this._leftjoystick;
  84573. };
  84574. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  84575. return this._rightjoystick;
  84576. };
  84577. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  84578. if (this._leftjoystick) {
  84579. var camera = this.camera;
  84580. var speed = camera._computeLocalCameraSpeed() * 50;
  84581. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  84582. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  84583. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  84584. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  84585. if (!this._leftjoystick.pressed) {
  84586. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  84587. }
  84588. if (!this._rightjoystick.pressed) {
  84589. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  84590. }
  84591. }
  84592. };
  84593. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  84594. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  84595. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  84596. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  84597. this._leftjoystick.setJoystickSensibility(0.15);
  84598. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  84599. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  84600. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  84601. this._rightjoystick.reverseUpDown = true;
  84602. this._rightjoystick.setJoystickSensibility(0.05);
  84603. this._rightjoystick.setJoystickColor("yellow");
  84604. };
  84605. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  84606. this._leftjoystick.releaseCanvas();
  84607. this._rightjoystick.releaseCanvas();
  84608. };
  84609. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  84610. return "FreeCameraVirtualJoystickInput";
  84611. };
  84612. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  84613. return "virtualJoystick";
  84614. };
  84615. return FreeCameraVirtualJoystickInput;
  84616. }());
  84617. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  84618. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  84619. })(BABYLON || (BABYLON = {}));
  84620. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  84621. "use strict";
  84622. var BABYLON;
  84623. (function (BABYLON) {
  84624. var SimplificationSettings = /** @class */ (function () {
  84625. function SimplificationSettings(quality, distance, optimizeMesh) {
  84626. this.quality = quality;
  84627. this.distance = distance;
  84628. this.optimizeMesh = optimizeMesh;
  84629. }
  84630. return SimplificationSettings;
  84631. }());
  84632. BABYLON.SimplificationSettings = SimplificationSettings;
  84633. var SimplificationQueue = /** @class */ (function () {
  84634. function SimplificationQueue() {
  84635. this.running = false;
  84636. this._simplificationArray = [];
  84637. }
  84638. SimplificationQueue.prototype.addTask = function (task) {
  84639. this._simplificationArray.push(task);
  84640. };
  84641. SimplificationQueue.prototype.executeNext = function () {
  84642. var task = this._simplificationArray.pop();
  84643. if (task) {
  84644. this.running = true;
  84645. this.runSimplification(task);
  84646. }
  84647. else {
  84648. this.running = false;
  84649. }
  84650. };
  84651. SimplificationQueue.prototype.runSimplification = function (task) {
  84652. var _this = this;
  84653. if (task.parallelProcessing) {
  84654. //parallel simplifier
  84655. task.settings.forEach(function (setting) {
  84656. var simplifier = _this.getSimplifier(task);
  84657. simplifier.simplify(setting, function (newMesh) {
  84658. task.mesh.addLODLevel(setting.distance, newMesh);
  84659. newMesh.isVisible = true;
  84660. //check if it is the last
  84661. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  84662. //all done, run the success callback.
  84663. task.successCallback();
  84664. }
  84665. _this.executeNext();
  84666. });
  84667. });
  84668. }
  84669. else {
  84670. //single simplifier.
  84671. var simplifier = this.getSimplifier(task);
  84672. var runDecimation = function (setting, callback) {
  84673. simplifier.simplify(setting, function (newMesh) {
  84674. task.mesh.addLODLevel(setting.distance, newMesh);
  84675. newMesh.isVisible = true;
  84676. //run the next quality level
  84677. callback();
  84678. });
  84679. };
  84680. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  84681. runDecimation(task.settings[loop.index], function () {
  84682. loop.executeNext();
  84683. });
  84684. }, function () {
  84685. //execution ended, run the success callback.
  84686. if (task.successCallback) {
  84687. task.successCallback();
  84688. }
  84689. _this.executeNext();
  84690. });
  84691. }
  84692. };
  84693. SimplificationQueue.prototype.getSimplifier = function (task) {
  84694. switch (task.simplificationType) {
  84695. case SimplificationType.QUADRATIC:
  84696. default:
  84697. return new QuadraticErrorSimplification(task.mesh);
  84698. }
  84699. };
  84700. return SimplificationQueue;
  84701. }());
  84702. BABYLON.SimplificationQueue = SimplificationQueue;
  84703. /**
  84704. * The implemented types of simplification.
  84705. * At the moment only Quadratic Error Decimation is implemented.
  84706. */
  84707. var SimplificationType;
  84708. (function (SimplificationType) {
  84709. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  84710. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  84711. var DecimationTriangle = /** @class */ (function () {
  84712. function DecimationTriangle(vertices) {
  84713. this.vertices = vertices;
  84714. this.error = new Array(4);
  84715. this.deleted = false;
  84716. this.isDirty = false;
  84717. this.deletePending = false;
  84718. this.borderFactor = 0;
  84719. }
  84720. return DecimationTriangle;
  84721. }());
  84722. BABYLON.DecimationTriangle = DecimationTriangle;
  84723. var DecimationVertex = /** @class */ (function () {
  84724. function DecimationVertex(position, id) {
  84725. this.position = position;
  84726. this.id = id;
  84727. this.isBorder = true;
  84728. this.q = new QuadraticMatrix();
  84729. this.triangleCount = 0;
  84730. this.triangleStart = 0;
  84731. this.originalOffsets = [];
  84732. }
  84733. DecimationVertex.prototype.updatePosition = function (newPosition) {
  84734. this.position.copyFrom(newPosition);
  84735. };
  84736. return DecimationVertex;
  84737. }());
  84738. BABYLON.DecimationVertex = DecimationVertex;
  84739. var QuadraticMatrix = /** @class */ (function () {
  84740. function QuadraticMatrix(data) {
  84741. this.data = new Array(10);
  84742. for (var i = 0; i < 10; ++i) {
  84743. if (data && data[i]) {
  84744. this.data[i] = data[i];
  84745. }
  84746. else {
  84747. this.data[i] = 0;
  84748. }
  84749. }
  84750. }
  84751. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  84752. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  84753. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  84754. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  84755. return det;
  84756. };
  84757. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  84758. for (var i = 0; i < 10; ++i) {
  84759. this.data[i] += matrix.data[i];
  84760. }
  84761. };
  84762. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  84763. for (var i = 0; i < 10; ++i) {
  84764. this.data[i] += data[i];
  84765. }
  84766. };
  84767. QuadraticMatrix.prototype.add = function (matrix) {
  84768. var m = new QuadraticMatrix();
  84769. for (var i = 0; i < 10; ++i) {
  84770. m.data[i] = this.data[i] + matrix.data[i];
  84771. }
  84772. return m;
  84773. };
  84774. QuadraticMatrix.FromData = function (a, b, c, d) {
  84775. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  84776. };
  84777. //returning an array to avoid garbage collection
  84778. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  84779. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  84780. };
  84781. return QuadraticMatrix;
  84782. }());
  84783. BABYLON.QuadraticMatrix = QuadraticMatrix;
  84784. var Reference = /** @class */ (function () {
  84785. function Reference(vertexId, triangleId) {
  84786. this.vertexId = vertexId;
  84787. this.triangleId = triangleId;
  84788. }
  84789. return Reference;
  84790. }());
  84791. BABYLON.Reference = Reference;
  84792. /**
  84793. * An implementation of the Quadratic Error simplification algorithm.
  84794. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  84795. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  84796. * @author RaananW
  84797. */
  84798. var QuadraticErrorSimplification = /** @class */ (function () {
  84799. function QuadraticErrorSimplification(_mesh) {
  84800. this._mesh = _mesh;
  84801. this.syncIterations = 5000;
  84802. this.aggressiveness = 7;
  84803. this.decimationIterations = 100;
  84804. this.boundingBoxEpsilon = BABYLON.Epsilon;
  84805. }
  84806. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  84807. var _this = this;
  84808. this.initDecimatedMesh();
  84809. //iterating through the submeshes array, one after the other.
  84810. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  84811. _this.initWithMesh(loop.index, function () {
  84812. _this.runDecimation(settings, loop.index, function () {
  84813. loop.executeNext();
  84814. });
  84815. }, settings.optimizeMesh);
  84816. }, function () {
  84817. setTimeout(function () {
  84818. successCallback(_this._reconstructedMesh);
  84819. }, 0);
  84820. });
  84821. };
  84822. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  84823. var _this = this;
  84824. var targetCount = ~~(this.triangles.length * settings.quality);
  84825. var deletedTriangles = 0;
  84826. var triangleCount = this.triangles.length;
  84827. var iterationFunction = function (iteration, callback) {
  84828. setTimeout(function () {
  84829. if (iteration % 5 === 0) {
  84830. _this.updateMesh(iteration === 0);
  84831. }
  84832. for (var i = 0; i < _this.triangles.length; ++i) {
  84833. _this.triangles[i].isDirty = false;
  84834. }
  84835. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  84836. var trianglesIterator = function (i) {
  84837. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  84838. var t = _this.triangles[tIdx];
  84839. if (!t)
  84840. return;
  84841. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  84842. return;
  84843. }
  84844. for (var j = 0; j < 3; ++j) {
  84845. if (t.error[j] < threshold) {
  84846. var deleted0 = [];
  84847. var deleted1 = [];
  84848. var v0 = t.vertices[j];
  84849. var v1 = t.vertices[(j + 1) % 3];
  84850. if (v0.isBorder || v1.isBorder)
  84851. continue;
  84852. var p = BABYLON.Vector3.Zero();
  84853. var n = BABYLON.Vector3.Zero();
  84854. var uv = BABYLON.Vector2.Zero();
  84855. var color = new BABYLON.Color4(0, 0, 0, 1);
  84856. _this.calculateError(v0, v1, p, n, uv, color);
  84857. var delTr = new Array();
  84858. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  84859. continue;
  84860. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  84861. continue;
  84862. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  84863. continue;
  84864. var uniqueArray = new Array();
  84865. delTr.forEach(function (deletedT) {
  84866. if (uniqueArray.indexOf(deletedT) === -1) {
  84867. deletedT.deletePending = true;
  84868. uniqueArray.push(deletedT);
  84869. }
  84870. });
  84871. if (uniqueArray.length % 2 !== 0) {
  84872. continue;
  84873. }
  84874. v0.q = v1.q.add(v0.q);
  84875. v0.updatePosition(p);
  84876. var tStart = _this.references.length;
  84877. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  84878. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  84879. var tCount = _this.references.length - tStart;
  84880. if (tCount <= v0.triangleCount) {
  84881. if (tCount) {
  84882. for (var c = 0; c < tCount; c++) {
  84883. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  84884. }
  84885. }
  84886. }
  84887. else {
  84888. v0.triangleStart = tStart;
  84889. }
  84890. v0.triangleCount = tCount;
  84891. break;
  84892. }
  84893. }
  84894. };
  84895. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  84896. }, 0);
  84897. };
  84898. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  84899. if (triangleCount - deletedTriangles <= targetCount)
  84900. loop.breakLoop();
  84901. else {
  84902. iterationFunction(loop.index, function () {
  84903. loop.executeNext();
  84904. });
  84905. }
  84906. }, function () {
  84907. setTimeout(function () {
  84908. //reconstruct this part of the mesh
  84909. _this.reconstructMesh(submeshIndex);
  84910. successCallback();
  84911. }, 0);
  84912. });
  84913. };
  84914. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  84915. var _this = this;
  84916. this.vertices = [];
  84917. this.triangles = [];
  84918. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84919. var indices = this._mesh.getIndices();
  84920. var submesh = this._mesh.subMeshes[submeshIndex];
  84921. var findInVertices = function (positionToSearch) {
  84922. if (optimizeMesh) {
  84923. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  84924. if (_this.vertices[ii].position.equals(positionToSearch)) {
  84925. return _this.vertices[ii];
  84926. }
  84927. }
  84928. }
  84929. return null;
  84930. };
  84931. var vertexReferences = [];
  84932. var vertexInit = function (i) {
  84933. if (!positionData) {
  84934. return;
  84935. }
  84936. var offset = i + submesh.verticesStart;
  84937. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  84938. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  84939. vertex.originalOffsets.push(offset);
  84940. if (vertex.id === _this.vertices.length) {
  84941. _this.vertices.push(vertex);
  84942. }
  84943. vertexReferences.push(vertex.id);
  84944. };
  84945. //var totalVertices = mesh.getTotalVertices();
  84946. var totalVertices = submesh.verticesCount;
  84947. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  84948. var indicesInit = function (i) {
  84949. if (!indices) {
  84950. return;
  84951. }
  84952. var offset = (submesh.indexStart / 3) + i;
  84953. var pos = (offset * 3);
  84954. var i0 = indices[pos + 0];
  84955. var i1 = indices[pos + 1];
  84956. var i2 = indices[pos + 2];
  84957. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  84958. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  84959. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  84960. var triangle = new DecimationTriangle([v0, v1, v2]);
  84961. triangle.originalOffset = pos;
  84962. _this.triangles.push(triangle);
  84963. };
  84964. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  84965. _this.init(callback);
  84966. });
  84967. });
  84968. };
  84969. QuadraticErrorSimplification.prototype.init = function (callback) {
  84970. var _this = this;
  84971. var triangleInit1 = function (i) {
  84972. var t = _this.triangles[i];
  84973. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  84974. for (var j = 0; j < 3; j++) {
  84975. 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))));
  84976. }
  84977. };
  84978. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  84979. var triangleInit2 = function (i) {
  84980. var t = _this.triangles[i];
  84981. for (var j = 0; j < 3; ++j) {
  84982. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  84983. }
  84984. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84985. };
  84986. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  84987. callback();
  84988. });
  84989. });
  84990. };
  84991. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  84992. var newTriangles = [];
  84993. var i;
  84994. for (i = 0; i < this.vertices.length; ++i) {
  84995. this.vertices[i].triangleCount = 0;
  84996. }
  84997. var t;
  84998. var j;
  84999. for (i = 0; i < this.triangles.length; ++i) {
  85000. if (!this.triangles[i].deleted) {
  85001. t = this.triangles[i];
  85002. for (j = 0; j < 3; ++j) {
  85003. t.vertices[j].triangleCount = 1;
  85004. }
  85005. newTriangles.push(t);
  85006. }
  85007. }
  85008. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  85009. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  85010. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  85011. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  85012. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  85013. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  85014. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  85015. var vertexCount = 0;
  85016. for (i = 0; i < this.vertices.length; ++i) {
  85017. var vertex = this.vertices[i];
  85018. vertex.id = vertexCount;
  85019. if (vertex.triangleCount) {
  85020. vertex.originalOffsets.forEach(function (originalOffset) {
  85021. if (!normalData) {
  85022. return;
  85023. }
  85024. newPositionData.push(vertex.position.x);
  85025. newPositionData.push(vertex.position.y);
  85026. newPositionData.push(vertex.position.z);
  85027. newNormalData.push(normalData[originalOffset * 3]);
  85028. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  85029. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  85030. if (uvs && uvs.length) {
  85031. newUVsData.push(uvs[(originalOffset * 2)]);
  85032. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  85033. }
  85034. else if (colorsData && colorsData.length) {
  85035. newColorsData.push(colorsData[(originalOffset * 4)]);
  85036. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  85037. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  85038. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  85039. }
  85040. ++vertexCount;
  85041. });
  85042. }
  85043. }
  85044. var startingIndex = this._reconstructedMesh.getTotalIndices();
  85045. var startingVertex = this._reconstructedMesh.getTotalVertices();
  85046. var submeshesArray = this._reconstructedMesh.subMeshes;
  85047. this._reconstructedMesh.subMeshes = [];
  85048. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  85049. var originalIndices = this._mesh.getIndices();
  85050. for (i = 0; i < newTriangles.length; ++i) {
  85051. t = newTriangles[i]; //now get the new referencing point for each vertex
  85052. [0, 1, 2].forEach(function (idx) {
  85053. var id = originalIndices[t.originalOffset + idx];
  85054. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  85055. if (offset < 0)
  85056. offset = 0;
  85057. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  85058. });
  85059. }
  85060. //overwriting the old vertex buffers and indices.
  85061. this._reconstructedMesh.setIndices(newIndicesArray);
  85062. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  85063. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  85064. if (newUVsData.length > 0)
  85065. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  85066. if (newColorsData.length > 0)
  85067. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  85068. //create submesh
  85069. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  85070. if (submeshIndex > 0) {
  85071. this._reconstructedMesh.subMeshes = [];
  85072. submeshesArray.forEach(function (submesh) {
  85073. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  85074. });
  85075. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  85076. }
  85077. };
  85078. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  85079. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  85080. this._reconstructedMesh.material = this._mesh.material;
  85081. this._reconstructedMesh.parent = this._mesh.parent;
  85082. this._reconstructedMesh.isVisible = false;
  85083. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  85084. };
  85085. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  85086. for (var i = 0; i < vertex1.triangleCount; ++i) {
  85087. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  85088. if (t.deleted)
  85089. continue;
  85090. var s = this.references[vertex1.triangleStart + i].vertexId;
  85091. var v1 = t.vertices[(s + 1) % 3];
  85092. var v2 = t.vertices[(s + 2) % 3];
  85093. if ((v1 === vertex2 || v2 === vertex2)) {
  85094. deletedArray[i] = true;
  85095. delTr.push(t);
  85096. continue;
  85097. }
  85098. var d1 = v1.position.subtract(point);
  85099. d1 = d1.normalize();
  85100. var d2 = v2.position.subtract(point);
  85101. d2 = d2.normalize();
  85102. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  85103. return true;
  85104. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  85105. deletedArray[i] = false;
  85106. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  85107. return true;
  85108. }
  85109. return false;
  85110. };
  85111. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  85112. var newDeleted = deletedTriangles;
  85113. for (var i = 0; i < vertex.triangleCount; ++i) {
  85114. var ref = this.references[vertex.triangleStart + i];
  85115. var t = this.triangles[ref.triangleId];
  85116. if (t.deleted)
  85117. continue;
  85118. if (deletedArray[i] && t.deletePending) {
  85119. t.deleted = true;
  85120. newDeleted++;
  85121. continue;
  85122. }
  85123. t.vertices[ref.vertexId] = origVertex;
  85124. t.isDirty = true;
  85125. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  85126. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  85127. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  85128. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  85129. this.references.push(ref);
  85130. }
  85131. return newDeleted;
  85132. };
  85133. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  85134. for (var i = 0; i < this.vertices.length; ++i) {
  85135. var vCount = [];
  85136. var vId = [];
  85137. var v = this.vertices[i];
  85138. var j;
  85139. for (j = 0; j < v.triangleCount; ++j) {
  85140. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  85141. for (var ii = 0; ii < 3; ii++) {
  85142. var ofs = 0;
  85143. var vv = triangle.vertices[ii];
  85144. while (ofs < vCount.length) {
  85145. if (vId[ofs] === vv.id)
  85146. break;
  85147. ++ofs;
  85148. }
  85149. if (ofs === vCount.length) {
  85150. vCount.push(1);
  85151. vId.push(vv.id);
  85152. }
  85153. else {
  85154. vCount[ofs]++;
  85155. }
  85156. }
  85157. }
  85158. for (j = 0; j < vCount.length; ++j) {
  85159. if (vCount[j] === 1) {
  85160. this.vertices[vId[j]].isBorder = true;
  85161. }
  85162. else {
  85163. this.vertices[vId[j]].isBorder = false;
  85164. }
  85165. }
  85166. }
  85167. };
  85168. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  85169. if (identifyBorders === void 0) { identifyBorders = false; }
  85170. var i;
  85171. if (!identifyBorders) {
  85172. var newTrianglesVector = [];
  85173. for (i = 0; i < this.triangles.length; ++i) {
  85174. if (!this.triangles[i].deleted) {
  85175. newTrianglesVector.push(this.triangles[i]);
  85176. }
  85177. }
  85178. this.triangles = newTrianglesVector;
  85179. }
  85180. for (i = 0; i < this.vertices.length; ++i) {
  85181. this.vertices[i].triangleCount = 0;
  85182. this.vertices[i].triangleStart = 0;
  85183. }
  85184. var t;
  85185. var j;
  85186. var v;
  85187. for (i = 0; i < this.triangles.length; ++i) {
  85188. t = this.triangles[i];
  85189. for (j = 0; j < 3; ++j) {
  85190. v = t.vertices[j];
  85191. v.triangleCount++;
  85192. }
  85193. }
  85194. var tStart = 0;
  85195. for (i = 0; i < this.vertices.length; ++i) {
  85196. this.vertices[i].triangleStart = tStart;
  85197. tStart += this.vertices[i].triangleCount;
  85198. this.vertices[i].triangleCount = 0;
  85199. }
  85200. var newReferences = new Array(this.triangles.length * 3);
  85201. for (i = 0; i < this.triangles.length; ++i) {
  85202. t = this.triangles[i];
  85203. for (j = 0; j < 3; ++j) {
  85204. v = t.vertices[j];
  85205. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  85206. v.triangleCount++;
  85207. }
  85208. }
  85209. this.references = newReferences;
  85210. if (identifyBorders) {
  85211. this.identifyBorder();
  85212. }
  85213. };
  85214. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  85215. var x = point.x;
  85216. var y = point.y;
  85217. var z = point.z;
  85218. 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
  85219. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  85220. };
  85221. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  85222. var q = vertex1.q.add(vertex2.q);
  85223. var border = vertex1.isBorder && vertex2.isBorder;
  85224. var error = 0;
  85225. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  85226. if (qDet !== 0 && !border) {
  85227. if (!pointResult) {
  85228. pointResult = BABYLON.Vector3.Zero();
  85229. }
  85230. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  85231. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  85232. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  85233. error = this.vertexError(q, pointResult);
  85234. }
  85235. else {
  85236. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  85237. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  85238. var error1 = this.vertexError(q, vertex1.position);
  85239. var error2 = this.vertexError(q, vertex2.position);
  85240. var error3 = this.vertexError(q, p3);
  85241. error = Math.min(error1, error2, error3);
  85242. if (error === error1) {
  85243. if (pointResult) {
  85244. pointResult.copyFrom(vertex1.position);
  85245. }
  85246. }
  85247. else if (error === error2) {
  85248. if (pointResult) {
  85249. pointResult.copyFrom(vertex2.position);
  85250. }
  85251. }
  85252. else {
  85253. if (pointResult) {
  85254. pointResult.copyFrom(p3);
  85255. }
  85256. }
  85257. }
  85258. return error;
  85259. };
  85260. return QuadraticErrorSimplification;
  85261. }());
  85262. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  85263. })(BABYLON || (BABYLON = {}));
  85264. //# sourceMappingURL=babylon.meshSimplification.js.map
  85265. "use strict";
  85266. var BABYLON;
  85267. (function (BABYLON) {
  85268. var MeshLODLevel = /** @class */ (function () {
  85269. function MeshLODLevel(distance, mesh) {
  85270. this.distance = distance;
  85271. this.mesh = mesh;
  85272. }
  85273. return MeshLODLevel;
  85274. }());
  85275. BABYLON.MeshLODLevel = MeshLODLevel;
  85276. })(BABYLON || (BABYLON = {}));
  85277. //# sourceMappingURL=babylon.meshLODLevel.js.map
  85278. "use strict";
  85279. var BABYLON;
  85280. (function (BABYLON) {
  85281. /**
  85282. * Defines the root class used to create scene optimization to use with SceneOptimizer
  85283. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85284. */
  85285. var SceneOptimization = /** @class */ (function () {
  85286. /**
  85287. * Creates the SceneOptimization object
  85288. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85289. * @param desc defines the description associated with the optimization
  85290. */
  85291. function SceneOptimization(
  85292. /**
  85293. * Defines the priority of this optimization (0 by default which means first in the list)
  85294. */
  85295. priority) {
  85296. if (priority === void 0) { priority = 0; }
  85297. this.priority = priority;
  85298. }
  85299. /**
  85300. * Gets a string describing the action executed by the current optimization
  85301. * @returns description string
  85302. */
  85303. SceneOptimization.prototype.getDescription = function () {
  85304. return "";
  85305. };
  85306. /**
  85307. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85308. * @param scene defines the current scene where to apply this optimization
  85309. * @param optimizer defines the current optimizer
  85310. * @returns true if everything that can be done was applied
  85311. */
  85312. SceneOptimization.prototype.apply = function (scene, optimizer) {
  85313. return true;
  85314. };
  85315. ;
  85316. return SceneOptimization;
  85317. }());
  85318. BABYLON.SceneOptimization = SceneOptimization;
  85319. /**
  85320. * Defines an optimization used to reduce the size of render target textures
  85321. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85322. */
  85323. var TextureOptimization = /** @class */ (function (_super) {
  85324. __extends(TextureOptimization, _super);
  85325. /**
  85326. * Creates the TextureOptimization object
  85327. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85328. * @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
  85329. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85330. */
  85331. function TextureOptimization(
  85332. /**
  85333. * Defines the priority of this optimization (0 by default which means first in the list)
  85334. */
  85335. priority,
  85336. /**
  85337. * 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
  85338. */
  85339. maximumSize,
  85340. /**
  85341. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85342. */
  85343. step) {
  85344. if (priority === void 0) { priority = 0; }
  85345. if (maximumSize === void 0) { maximumSize = 1024; }
  85346. if (step === void 0) { step = 0.5; }
  85347. var _this = _super.call(this, priority) || this;
  85348. _this.priority = priority;
  85349. _this.maximumSize = maximumSize;
  85350. _this.step = step;
  85351. return _this;
  85352. }
  85353. /**
  85354. * Gets a string describing the action executed by the current optimization
  85355. * @returns description string
  85356. */
  85357. TextureOptimization.prototype.getDescription = function () {
  85358. return "Reducing render target texture size to " + this.maximumSize;
  85359. };
  85360. /**
  85361. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85362. * @param scene defines the current scene where to apply this optimization
  85363. * @param optimizer defines the current optimizer
  85364. * @returns true if everything that can be done was applied
  85365. */
  85366. TextureOptimization.prototype.apply = function (scene, optimizer) {
  85367. var allDone = true;
  85368. for (var index = 0; index < scene.textures.length; index++) {
  85369. var texture = scene.textures[index];
  85370. if (!texture.canRescale || texture.getContext) {
  85371. continue;
  85372. }
  85373. var currentSize = texture.getSize();
  85374. var maxDimension = Math.max(currentSize.width, currentSize.height);
  85375. if (maxDimension > this.maximumSize) {
  85376. texture.scale(this.step);
  85377. allDone = false;
  85378. }
  85379. }
  85380. return allDone;
  85381. };
  85382. return TextureOptimization;
  85383. }(SceneOptimization));
  85384. BABYLON.TextureOptimization = TextureOptimization;
  85385. /**
  85386. * Defines an optimization used to increase or decrease the rendering resolution
  85387. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85388. */
  85389. var HardwareScalingOptimization = /** @class */ (function (_super) {
  85390. __extends(HardwareScalingOptimization, _super);
  85391. /**
  85392. * Creates the HardwareScalingOptimization object
  85393. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85394. * @param maximumScale defines the maximum scale to use (2 by default)
  85395. * @param step defines the step to use between two passes (0.5 by default)
  85396. */
  85397. function HardwareScalingOptimization(
  85398. /**
  85399. * Defines the priority of this optimization (0 by default which means first in the list)
  85400. */
  85401. priority,
  85402. /**
  85403. * Defines the maximum scale to use (2 by default)
  85404. */
  85405. maximumScale,
  85406. /**
  85407. * Defines the step to use between two passes (0.5 by default)
  85408. */
  85409. step) {
  85410. if (priority === void 0) { priority = 0; }
  85411. if (maximumScale === void 0) { maximumScale = 2; }
  85412. if (step === void 0) { step = 0.25; }
  85413. var _this = _super.call(this, priority) || this;
  85414. _this.priority = priority;
  85415. _this.maximumScale = maximumScale;
  85416. _this.step = step;
  85417. _this._currentScale = -1;
  85418. _this._directionOffset = 1;
  85419. return _this;
  85420. }
  85421. /**
  85422. * Gets a string describing the action executed by the current optimization
  85423. * @return description string
  85424. */
  85425. HardwareScalingOptimization.prototype.getDescription = function () {
  85426. return "Setting hardware scaling level to " + this._currentScale;
  85427. };
  85428. /**
  85429. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85430. * @param scene defines the current scene where to apply this optimization
  85431. * @param optimizer defines the current optimizer
  85432. * @returns true if everything that can be done was applied
  85433. */
  85434. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  85435. if (this._currentScale === -1) {
  85436. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  85437. if (this._currentScale > this.maximumScale) {
  85438. this._directionOffset = -1;
  85439. }
  85440. }
  85441. this._currentScale += this._directionOffset * this.step;
  85442. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  85443. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  85444. };
  85445. ;
  85446. return HardwareScalingOptimization;
  85447. }(SceneOptimization));
  85448. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  85449. /**
  85450. * Defines an optimization used to remove shadows
  85451. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85452. */
  85453. var ShadowsOptimization = /** @class */ (function (_super) {
  85454. __extends(ShadowsOptimization, _super);
  85455. function ShadowsOptimization() {
  85456. return _super !== null && _super.apply(this, arguments) || this;
  85457. }
  85458. /**
  85459. * Gets a string describing the action executed by the current optimization
  85460. * @return description string
  85461. */
  85462. ShadowsOptimization.prototype.getDescription = function () {
  85463. return "Turning shadows on/off";
  85464. };
  85465. /**
  85466. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85467. * @param scene defines the current scene where to apply this optimization
  85468. * @param optimizer defines the current optimizer
  85469. * @returns true if everything that can be done was applied
  85470. */
  85471. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  85472. scene.shadowsEnabled = optimizer.isInImprovementMode;
  85473. return true;
  85474. };
  85475. ;
  85476. return ShadowsOptimization;
  85477. }(SceneOptimization));
  85478. BABYLON.ShadowsOptimization = ShadowsOptimization;
  85479. /**
  85480. * Defines an optimization used to turn post-processes off
  85481. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85482. */
  85483. var PostProcessesOptimization = /** @class */ (function (_super) {
  85484. __extends(PostProcessesOptimization, _super);
  85485. function PostProcessesOptimization() {
  85486. return _super !== null && _super.apply(this, arguments) || this;
  85487. }
  85488. /**
  85489. * Gets a string describing the action executed by the current optimization
  85490. * @return description string
  85491. */
  85492. PostProcessesOptimization.prototype.getDescription = function () {
  85493. return "Turning post-processes on/off";
  85494. };
  85495. /**
  85496. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85497. * @param scene defines the current scene where to apply this optimization
  85498. * @param optimizer defines the current optimizer
  85499. * @returns true if everything that can be done was applied
  85500. */
  85501. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  85502. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  85503. return true;
  85504. };
  85505. ;
  85506. return PostProcessesOptimization;
  85507. }(SceneOptimization));
  85508. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  85509. /**
  85510. * Defines an optimization used to turn lens flares off
  85511. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85512. */
  85513. var LensFlaresOptimization = /** @class */ (function (_super) {
  85514. __extends(LensFlaresOptimization, _super);
  85515. function LensFlaresOptimization() {
  85516. return _super !== null && _super.apply(this, arguments) || this;
  85517. }
  85518. /**
  85519. * Gets a string describing the action executed by the current optimization
  85520. * @return description string
  85521. */
  85522. LensFlaresOptimization.prototype.getDescription = function () {
  85523. return "Turning lens flares on/off";
  85524. };
  85525. /**
  85526. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85527. * @param scene defines the current scene where to apply this optimization
  85528. * @param optimizer defines the current optimizer
  85529. * @returns true if everything that can be done was applied
  85530. */
  85531. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  85532. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  85533. return true;
  85534. };
  85535. ;
  85536. return LensFlaresOptimization;
  85537. }(SceneOptimization));
  85538. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  85539. /**
  85540. * Defines an optimization based on user defined callback.
  85541. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85542. */
  85543. var CustomOptimization = /** @class */ (function (_super) {
  85544. __extends(CustomOptimization, _super);
  85545. function CustomOptimization() {
  85546. return _super !== null && _super.apply(this, arguments) || this;
  85547. }
  85548. /**
  85549. * Gets a string describing the action executed by the current optimization
  85550. * @returns description string
  85551. */
  85552. CustomOptimization.prototype.getDescription = function () {
  85553. if (this.onGetDescription) {
  85554. return this.onGetDescription();
  85555. }
  85556. return "Running user defined callback";
  85557. };
  85558. /**
  85559. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85560. * @param scene defines the current scene where to apply this optimization
  85561. * @param optimizer defines the current optimizer
  85562. * @returns true if everything that can be done was applied
  85563. */
  85564. CustomOptimization.prototype.apply = function (scene, optimizer) {
  85565. if (this.onApply) {
  85566. return this.onApply(scene, optimizer);
  85567. }
  85568. return true;
  85569. };
  85570. ;
  85571. return CustomOptimization;
  85572. }(SceneOptimization));
  85573. BABYLON.CustomOptimization = CustomOptimization;
  85574. /**
  85575. * Defines an optimization used to turn particles off
  85576. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85577. */
  85578. var ParticlesOptimization = /** @class */ (function (_super) {
  85579. __extends(ParticlesOptimization, _super);
  85580. function ParticlesOptimization() {
  85581. return _super !== null && _super.apply(this, arguments) || this;
  85582. }
  85583. /**
  85584. * Gets a string describing the action executed by the current optimization
  85585. * @return description string
  85586. */
  85587. ParticlesOptimization.prototype.getDescription = function () {
  85588. return "Turning particles on/off";
  85589. };
  85590. /**
  85591. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85592. * @param scene defines the current scene where to apply this optimization
  85593. * @param optimizer defines the current optimizer
  85594. * @returns true if everything that can be done was applied
  85595. */
  85596. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  85597. scene.particlesEnabled = optimizer.isInImprovementMode;
  85598. return true;
  85599. };
  85600. ;
  85601. return ParticlesOptimization;
  85602. }(SceneOptimization));
  85603. BABYLON.ParticlesOptimization = ParticlesOptimization;
  85604. /**
  85605. * Defines an optimization used to turn render targets off
  85606. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85607. */
  85608. var RenderTargetsOptimization = /** @class */ (function (_super) {
  85609. __extends(RenderTargetsOptimization, _super);
  85610. function RenderTargetsOptimization() {
  85611. return _super !== null && _super.apply(this, arguments) || this;
  85612. }
  85613. /**
  85614. * Gets a string describing the action executed by the current optimization
  85615. * @return description string
  85616. */
  85617. RenderTargetsOptimization.prototype.getDescription = function () {
  85618. return "Turning render targets off";
  85619. };
  85620. /**
  85621. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85622. * @param scene defines the current scene where to apply this optimization
  85623. * @param optimizer defines the current optimizer
  85624. * @returns true if everything that can be done was applied
  85625. */
  85626. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  85627. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  85628. return true;
  85629. };
  85630. ;
  85631. return RenderTargetsOptimization;
  85632. }(SceneOptimization));
  85633. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  85634. /**
  85635. * Defines an optimization used to merge meshes with compatible materials
  85636. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85637. */
  85638. var MergeMeshesOptimization = /** @class */ (function (_super) {
  85639. __extends(MergeMeshesOptimization, _super);
  85640. function MergeMeshesOptimization() {
  85641. var _this = _super !== null && _super.apply(this, arguments) || this;
  85642. _this._canBeMerged = function (abstractMesh) {
  85643. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  85644. return false;
  85645. }
  85646. var mesh = abstractMesh;
  85647. if (!mesh.isVisible || !mesh.isEnabled()) {
  85648. return false;
  85649. }
  85650. if (mesh.instances.length > 0) {
  85651. return false;
  85652. }
  85653. if (mesh.skeleton || mesh.hasLODLevels) {
  85654. return false;
  85655. }
  85656. if (mesh.parent) {
  85657. return false;
  85658. }
  85659. return true;
  85660. };
  85661. return _this;
  85662. }
  85663. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  85664. /**
  85665. * Gets or sets a boolean which defines if optimization octree has to be updated
  85666. */
  85667. get: function () {
  85668. return MergeMeshesOptimization._UpdateSelectionTree;
  85669. },
  85670. /**
  85671. * Gets or sets a boolean which defines if optimization octree has to be updated
  85672. */
  85673. set: function (value) {
  85674. MergeMeshesOptimization._UpdateSelectionTree = value;
  85675. },
  85676. enumerable: true,
  85677. configurable: true
  85678. });
  85679. /**
  85680. * Gets a string describing the action executed by the current optimization
  85681. * @return description string
  85682. */
  85683. MergeMeshesOptimization.prototype.getDescription = function () {
  85684. return "Merging similar meshes together";
  85685. };
  85686. /**
  85687. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85688. * @param scene defines the current scene where to apply this optimization
  85689. * @param optimizer defines the current optimizer
  85690. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  85691. * @returns true if everything that can be done was applied
  85692. */
  85693. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  85694. var globalPool = scene.meshes.slice(0);
  85695. var globalLength = globalPool.length;
  85696. for (var index = 0; index < globalLength; index++) {
  85697. var currentPool = new Array();
  85698. var current = globalPool[index];
  85699. // Checks
  85700. if (!this._canBeMerged(current)) {
  85701. continue;
  85702. }
  85703. currentPool.push(current);
  85704. // Find compatible meshes
  85705. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  85706. var otherMesh = globalPool[subIndex];
  85707. if (!this._canBeMerged(otherMesh)) {
  85708. continue;
  85709. }
  85710. if (otherMesh.material !== current.material) {
  85711. continue;
  85712. }
  85713. if (otherMesh.checkCollisions !== current.checkCollisions) {
  85714. continue;
  85715. }
  85716. currentPool.push(otherMesh);
  85717. globalLength--;
  85718. globalPool.splice(subIndex, 1);
  85719. subIndex--;
  85720. }
  85721. if (currentPool.length < 2) {
  85722. continue;
  85723. }
  85724. // Merge meshes
  85725. BABYLON.Mesh.MergeMeshes(currentPool);
  85726. }
  85727. if (updateSelectionTree != undefined) {
  85728. if (updateSelectionTree) {
  85729. scene.createOrUpdateSelectionOctree();
  85730. }
  85731. }
  85732. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  85733. scene.createOrUpdateSelectionOctree();
  85734. }
  85735. return true;
  85736. };
  85737. ;
  85738. MergeMeshesOptimization._UpdateSelectionTree = false;
  85739. return MergeMeshesOptimization;
  85740. }(SceneOptimization));
  85741. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  85742. /**
  85743. * Defines a list of options used by SceneOptimizer
  85744. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85745. */
  85746. var SceneOptimizerOptions = /** @class */ (function () {
  85747. /**
  85748. * Creates a new list of options used by SceneOptimizer
  85749. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  85750. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  85751. */
  85752. function SceneOptimizerOptions(
  85753. /**
  85754. * Defines the target frame rate to reach (60 by default)
  85755. */
  85756. targetFrameRate,
  85757. /**
  85758. * Defines the interval between two checkes (2000ms by default)
  85759. */
  85760. trackerDuration) {
  85761. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  85762. if (trackerDuration === void 0) { trackerDuration = 2000; }
  85763. this.targetFrameRate = targetFrameRate;
  85764. this.trackerDuration = trackerDuration;
  85765. /**
  85766. * Gets the list of optimizations to apply
  85767. */
  85768. this.optimizations = new Array();
  85769. }
  85770. /**
  85771. * Add a new optimization
  85772. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  85773. * @returns the current SceneOptimizerOptions
  85774. */
  85775. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  85776. this.optimizations.push(optimization);
  85777. return this;
  85778. };
  85779. /**
  85780. * Add a new custom optimization
  85781. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  85782. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  85783. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85784. * @returns the current SceneOptimizerOptions
  85785. */
  85786. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  85787. if (priority === void 0) { priority = 0; }
  85788. var optimization = new CustomOptimization(priority);
  85789. optimization.onApply = onApply;
  85790. optimization.onGetDescription = onGetDescription;
  85791. this.optimizations.push(optimization);
  85792. return this;
  85793. };
  85794. /**
  85795. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  85796. * @param targetFrameRate defines the target frame rate (60 by default)
  85797. * @returns a SceneOptimizerOptions object
  85798. */
  85799. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  85800. var result = new SceneOptimizerOptions(targetFrameRate);
  85801. var priority = 0;
  85802. result.addOptimization(new MergeMeshesOptimization(priority));
  85803. result.addOptimization(new ShadowsOptimization(priority));
  85804. result.addOptimization(new LensFlaresOptimization(priority));
  85805. // Next priority
  85806. priority++;
  85807. result.addOptimization(new PostProcessesOptimization(priority));
  85808. result.addOptimization(new ParticlesOptimization(priority));
  85809. // Next priority
  85810. priority++;
  85811. result.addOptimization(new TextureOptimization(priority, 1024));
  85812. return result;
  85813. };
  85814. /**
  85815. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  85816. * @param targetFrameRate defines the target frame rate (60 by default)
  85817. * @returns a SceneOptimizerOptions object
  85818. */
  85819. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  85820. var result = new SceneOptimizerOptions(targetFrameRate);
  85821. var priority = 0;
  85822. result.addOptimization(new MergeMeshesOptimization(priority));
  85823. result.addOptimization(new ShadowsOptimization(priority));
  85824. result.addOptimization(new LensFlaresOptimization(priority));
  85825. // Next priority
  85826. priority++;
  85827. result.addOptimization(new PostProcessesOptimization(priority));
  85828. result.addOptimization(new ParticlesOptimization(priority));
  85829. // Next priority
  85830. priority++;
  85831. result.addOptimization(new TextureOptimization(priority, 512));
  85832. // Next priority
  85833. priority++;
  85834. result.addOptimization(new RenderTargetsOptimization(priority));
  85835. // Next priority
  85836. priority++;
  85837. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  85838. return result;
  85839. };
  85840. /**
  85841. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  85842. * @param targetFrameRate defines the target frame rate (60 by default)
  85843. * @returns a SceneOptimizerOptions object
  85844. */
  85845. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  85846. var result = new SceneOptimizerOptions(targetFrameRate);
  85847. var priority = 0;
  85848. result.addOptimization(new MergeMeshesOptimization(priority));
  85849. result.addOptimization(new ShadowsOptimization(priority));
  85850. result.addOptimization(new LensFlaresOptimization(priority));
  85851. // Next priority
  85852. priority++;
  85853. result.addOptimization(new PostProcessesOptimization(priority));
  85854. result.addOptimization(new ParticlesOptimization(priority));
  85855. // Next priority
  85856. priority++;
  85857. result.addOptimization(new TextureOptimization(priority, 256));
  85858. // Next priority
  85859. priority++;
  85860. result.addOptimization(new RenderTargetsOptimization(priority));
  85861. // Next priority
  85862. priority++;
  85863. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  85864. return result;
  85865. };
  85866. return SceneOptimizerOptions;
  85867. }());
  85868. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  85869. /**
  85870. * Class used to run optimizations in order to reach a target frame rate
  85871. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85872. */
  85873. var SceneOptimizer = /** @class */ (function () {
  85874. /**
  85875. * Creates a new SceneOptimizer
  85876. * @param scene defines the scene to work on
  85877. * @param options defines the options to use with the SceneOptimizer
  85878. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  85879. * @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)
  85880. */
  85881. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  85882. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  85883. if (improvementMode === void 0) { improvementMode = false; }
  85884. var _this = this;
  85885. this._isRunning = false;
  85886. this._currentPriorityLevel = 0;
  85887. this._targetFrameRate = 60;
  85888. this._trackerDuration = 2000;
  85889. this._currentFrameRate = 0;
  85890. this._improvementMode = false;
  85891. /**
  85892. * Defines an observable called when the optimizer reaches the target frame rate
  85893. */
  85894. this.onSuccessObservable = new BABYLON.Observable();
  85895. /**
  85896. * Defines an observable called when the optimizer enables an optimization
  85897. */
  85898. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  85899. /**
  85900. * Defines an observable called when the optimizer is not able to reach the target frame rate
  85901. */
  85902. this.onFailureObservable = new BABYLON.Observable();
  85903. if (!options) {
  85904. this._options = new SceneOptimizerOptions();
  85905. }
  85906. else {
  85907. this._options = options;
  85908. }
  85909. if (this._options.targetFrameRate) {
  85910. this._targetFrameRate = this._options.targetFrameRate;
  85911. }
  85912. if (this._options.trackerDuration) {
  85913. this._trackerDuration = this._options.trackerDuration;
  85914. }
  85915. if (autoGeneratePriorities) {
  85916. var priority = 0;
  85917. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  85918. var optim = _a[_i];
  85919. optim.priority = priority++;
  85920. }
  85921. }
  85922. this._improvementMode = improvementMode;
  85923. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85924. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  85925. _this._sceneDisposeObserver = null;
  85926. _this.dispose();
  85927. });
  85928. }
  85929. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  85930. /**
  85931. * Gets a boolean indicating if the optimizer is in improvement mode
  85932. */
  85933. get: function () {
  85934. return this._improvementMode;
  85935. },
  85936. enumerable: true,
  85937. configurable: true
  85938. });
  85939. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  85940. /**
  85941. * Gets the current priority level (0 at start)
  85942. */
  85943. get: function () {
  85944. return this._currentPriorityLevel;
  85945. },
  85946. enumerable: true,
  85947. configurable: true
  85948. });
  85949. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  85950. /**
  85951. * Gets the current frame rate checked by the SceneOptimizer
  85952. */
  85953. get: function () {
  85954. return this._currentFrameRate;
  85955. },
  85956. enumerable: true,
  85957. configurable: true
  85958. });
  85959. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  85960. /**
  85961. * Gets or sets the current target frame rate (60 by default)
  85962. */
  85963. get: function () {
  85964. return this._targetFrameRate;
  85965. },
  85966. /**
  85967. * Gets or sets the current target frame rate (60 by default)
  85968. */
  85969. set: function (value) {
  85970. this._targetFrameRate = value;
  85971. },
  85972. enumerable: true,
  85973. configurable: true
  85974. });
  85975. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  85976. /**
  85977. * Gets or sets the current interval between two checks (every 2000ms by default)
  85978. */
  85979. get: function () {
  85980. return this._trackerDuration;
  85981. },
  85982. /**
  85983. * Gets or sets the current interval between two checks (every 2000ms by default)
  85984. */
  85985. set: function (value) {
  85986. this._trackerDuration = value;
  85987. },
  85988. enumerable: true,
  85989. configurable: true
  85990. });
  85991. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  85992. /**
  85993. * Gets the list of active optimizations
  85994. */
  85995. get: function () {
  85996. return this._options.optimizations;
  85997. },
  85998. enumerable: true,
  85999. configurable: true
  86000. });
  86001. /**
  86002. * Stops the current optimizer
  86003. */
  86004. SceneOptimizer.prototype.stop = function () {
  86005. this._isRunning = false;
  86006. };
  86007. /**
  86008. * Reset the optimizer to initial step (current priority level = 0)
  86009. */
  86010. SceneOptimizer.prototype.reset = function () {
  86011. this._currentPriorityLevel = 0;
  86012. };
  86013. /**
  86014. * Start the optimizer. By default it will try to reach a specific framerate
  86015. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  86016. */
  86017. SceneOptimizer.prototype.start = function () {
  86018. var _this = this;
  86019. if (this._isRunning) {
  86020. return;
  86021. }
  86022. this._isRunning = true;
  86023. // Let's wait for the scene to be ready before running our check
  86024. this._scene.executeWhenReady(function () {
  86025. setTimeout(function () {
  86026. _this._checkCurrentState();
  86027. }, _this._trackerDuration);
  86028. });
  86029. };
  86030. SceneOptimizer.prototype._checkCurrentState = function () {
  86031. var _this = this;
  86032. if (!this._isRunning) {
  86033. return;
  86034. }
  86035. var scene = this._scene;
  86036. var options = this._options;
  86037. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  86038. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  86039. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  86040. this._isRunning = false;
  86041. this.onSuccessObservable.notifyObservers(this);
  86042. return;
  86043. }
  86044. // Apply current level of optimizations
  86045. var allDone = true;
  86046. var noOptimizationApplied = true;
  86047. for (var index = 0; index < options.optimizations.length; index++) {
  86048. var optimization = options.optimizations[index];
  86049. if (optimization.priority === this._currentPriorityLevel) {
  86050. noOptimizationApplied = false;
  86051. allDone = allDone && optimization.apply(scene, this);
  86052. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  86053. }
  86054. }
  86055. // If no optimization was applied, this is a failure :(
  86056. if (noOptimizationApplied) {
  86057. this._isRunning = false;
  86058. this.onFailureObservable.notifyObservers(this);
  86059. return;
  86060. }
  86061. // If all optimizations were done, move to next level
  86062. if (allDone) {
  86063. this._currentPriorityLevel++;
  86064. }
  86065. // Let's the system running for a specific amount of time before checking FPS
  86066. scene.executeWhenReady(function () {
  86067. setTimeout(function () {
  86068. _this._checkCurrentState();
  86069. }, _this._trackerDuration);
  86070. });
  86071. };
  86072. /**
  86073. * Release all resources
  86074. */
  86075. SceneOptimizer.prototype.dispose = function () {
  86076. this.stop();
  86077. this.onSuccessObservable.clear();
  86078. this.onFailureObservable.clear();
  86079. this.onNewOptimizationAppliedObservable.clear();
  86080. if (this._sceneDisposeObserver) {
  86081. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  86082. }
  86083. };
  86084. /**
  86085. * Helper function to create a SceneOptimizer with one single line of code
  86086. * @param scene defines the scene to work on
  86087. * @param options defines the options to use with the SceneOptimizer
  86088. * @param onSuccess defines a callback to call on success
  86089. * @param onFailure defines a callback to call on failure
  86090. * @returns the new SceneOptimizer object
  86091. */
  86092. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  86093. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  86094. if (onSuccess) {
  86095. optimizer.onSuccessObservable.add(function () {
  86096. onSuccess();
  86097. });
  86098. }
  86099. if (onFailure) {
  86100. optimizer.onFailureObservable.add(function () {
  86101. onFailure();
  86102. });
  86103. }
  86104. optimizer.start();
  86105. return optimizer;
  86106. };
  86107. return SceneOptimizer;
  86108. }());
  86109. BABYLON.SceneOptimizer = SceneOptimizer;
  86110. })(BABYLON || (BABYLON = {}));
  86111. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  86112. "use strict";
  86113. var BABYLON;
  86114. (function (BABYLON) {
  86115. var OutlineRenderer = /** @class */ (function () {
  86116. function OutlineRenderer(scene) {
  86117. this.zOffset = 1;
  86118. this._scene = scene;
  86119. }
  86120. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  86121. var _this = this;
  86122. if (useOverlay === void 0) { useOverlay = false; }
  86123. var scene = this._scene;
  86124. var engine = this._scene.getEngine();
  86125. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86126. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  86127. return;
  86128. }
  86129. var mesh = subMesh.getRenderingMesh();
  86130. var material = subMesh.getMaterial();
  86131. if (!material || !scene.activeCamera) {
  86132. return;
  86133. }
  86134. engine.enableEffect(this._effect);
  86135. // Logarithmic depth
  86136. if (material.useLogarithmicDepth) {
  86137. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  86138. }
  86139. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  86140. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  86141. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  86142. // Bones
  86143. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86144. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86145. }
  86146. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  86147. // Alpha test
  86148. if (material && material.needAlphaTesting()) {
  86149. var alphaTexture = material.getAlphaTestTexture();
  86150. if (alphaTexture) {
  86151. this._effect.setTexture("diffuseSampler", alphaTexture);
  86152. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  86153. }
  86154. }
  86155. engine.setZOffset(-this.zOffset);
  86156. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  86157. engine.setZOffset(0);
  86158. };
  86159. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  86160. var defines = [];
  86161. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  86162. var mesh = subMesh.getMesh();
  86163. var material = subMesh.getMaterial();
  86164. if (material) {
  86165. // Alpha test
  86166. if (material.needAlphaTesting()) {
  86167. defines.push("#define ALPHATEST");
  86168. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86169. attribs.push(BABYLON.VertexBuffer.UVKind);
  86170. defines.push("#define UV1");
  86171. }
  86172. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  86173. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86174. defines.push("#define UV2");
  86175. }
  86176. }
  86177. //Logarithmic depth
  86178. if (material.useLogarithmicDepth) {
  86179. defines.push("#define LOGARITHMICDEPTH");
  86180. }
  86181. }
  86182. // Bones
  86183. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86184. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86185. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86186. if (mesh.numBoneInfluencers > 4) {
  86187. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86188. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86189. }
  86190. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86191. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  86192. }
  86193. else {
  86194. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86195. }
  86196. // Instances
  86197. if (useInstances) {
  86198. defines.push("#define INSTANCES");
  86199. attribs.push("world0");
  86200. attribs.push("world1");
  86201. attribs.push("world2");
  86202. attribs.push("world3");
  86203. }
  86204. // Get correct effect
  86205. var join = defines.join("\n");
  86206. if (this._cachedDefines !== join) {
  86207. this._cachedDefines = join;
  86208. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  86209. }
  86210. return this._effect.isReady();
  86211. };
  86212. return OutlineRenderer;
  86213. }());
  86214. BABYLON.OutlineRenderer = OutlineRenderer;
  86215. })(BABYLON || (BABYLON = {}));
  86216. //# sourceMappingURL=babylon.outlineRenderer.js.map
  86217. "use strict";
  86218. var BABYLON;
  86219. (function (BABYLON) {
  86220. var FaceAdjacencies = /** @class */ (function () {
  86221. function FaceAdjacencies() {
  86222. this.edges = new Array();
  86223. this.edgesConnectedCount = 0;
  86224. }
  86225. return FaceAdjacencies;
  86226. }());
  86227. var EdgesRenderer = /** @class */ (function () {
  86228. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  86229. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  86230. if (epsilon === void 0) { epsilon = 0.95; }
  86231. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  86232. this.edgesWidthScalerForOrthographic = 1000.0;
  86233. this.edgesWidthScalerForPerspective = 50.0;
  86234. this._linesPositions = new Array();
  86235. this._linesNormals = new Array();
  86236. this._linesIndices = new Array();
  86237. this._buffers = {};
  86238. this._checkVerticesInsteadOfIndices = false;
  86239. this._source = source;
  86240. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  86241. this._epsilon = epsilon;
  86242. this._prepareRessources();
  86243. this._generateEdgesLines();
  86244. }
  86245. EdgesRenderer.prototype._prepareRessources = function () {
  86246. if (this._lineShader) {
  86247. return;
  86248. }
  86249. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  86250. attributes: ["position", "normal"],
  86251. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  86252. });
  86253. this._lineShader.disableDepthWrite = true;
  86254. this._lineShader.backFaceCulling = false;
  86255. };
  86256. EdgesRenderer.prototype._rebuild = function () {
  86257. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  86258. if (buffer) {
  86259. buffer._rebuild();
  86260. }
  86261. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  86262. if (buffer) {
  86263. buffer._rebuild();
  86264. }
  86265. var scene = this._source.getScene();
  86266. var engine = scene.getEngine();
  86267. this._ib = engine.createIndexBuffer(this._linesIndices);
  86268. };
  86269. EdgesRenderer.prototype.dispose = function () {
  86270. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  86271. if (buffer) {
  86272. buffer.dispose();
  86273. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  86274. }
  86275. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  86276. if (buffer) {
  86277. buffer.dispose();
  86278. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  86279. }
  86280. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  86281. this._lineShader.dispose();
  86282. };
  86283. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  86284. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  86285. return 0;
  86286. }
  86287. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  86288. return 1;
  86289. }
  86290. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  86291. return 2;
  86292. }
  86293. return -1;
  86294. };
  86295. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  86296. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  86297. return 0;
  86298. }
  86299. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  86300. return 1;
  86301. }
  86302. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  86303. return 2;
  86304. }
  86305. return -1;
  86306. };
  86307. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  86308. var needToCreateLine;
  86309. if (edge === undefined) {
  86310. needToCreateLine = true;
  86311. }
  86312. else {
  86313. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  86314. needToCreateLine = dotProduct < this._epsilon;
  86315. }
  86316. if (needToCreateLine) {
  86317. var offset = this._linesPositions.length / 3;
  86318. var normal = p0.subtract(p1);
  86319. normal.normalize();
  86320. // Positions
  86321. this._linesPositions.push(p0.x);
  86322. this._linesPositions.push(p0.y);
  86323. this._linesPositions.push(p0.z);
  86324. this._linesPositions.push(p0.x);
  86325. this._linesPositions.push(p0.y);
  86326. this._linesPositions.push(p0.z);
  86327. this._linesPositions.push(p1.x);
  86328. this._linesPositions.push(p1.y);
  86329. this._linesPositions.push(p1.z);
  86330. this._linesPositions.push(p1.x);
  86331. this._linesPositions.push(p1.y);
  86332. this._linesPositions.push(p1.z);
  86333. // Normals
  86334. this._linesNormals.push(p1.x);
  86335. this._linesNormals.push(p1.y);
  86336. this._linesNormals.push(p1.z);
  86337. this._linesNormals.push(-1);
  86338. this._linesNormals.push(p1.x);
  86339. this._linesNormals.push(p1.y);
  86340. this._linesNormals.push(p1.z);
  86341. this._linesNormals.push(1);
  86342. this._linesNormals.push(p0.x);
  86343. this._linesNormals.push(p0.y);
  86344. this._linesNormals.push(p0.z);
  86345. this._linesNormals.push(-1);
  86346. this._linesNormals.push(p0.x);
  86347. this._linesNormals.push(p0.y);
  86348. this._linesNormals.push(p0.z);
  86349. this._linesNormals.push(1);
  86350. // Indices
  86351. this._linesIndices.push(offset);
  86352. this._linesIndices.push(offset + 1);
  86353. this._linesIndices.push(offset + 2);
  86354. this._linesIndices.push(offset);
  86355. this._linesIndices.push(offset + 2);
  86356. this._linesIndices.push(offset + 3);
  86357. }
  86358. };
  86359. EdgesRenderer.prototype._generateEdgesLines = function () {
  86360. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  86361. var indices = this._source.getIndices();
  86362. if (!indices || !positions) {
  86363. return;
  86364. }
  86365. // First let's find adjacencies
  86366. var adjacencies = new Array();
  86367. var faceNormals = new Array();
  86368. var index;
  86369. var faceAdjacencies;
  86370. // Prepare faces
  86371. for (index = 0; index < indices.length; index += 3) {
  86372. faceAdjacencies = new FaceAdjacencies();
  86373. var p0Index = indices[index];
  86374. var p1Index = indices[index + 1];
  86375. var p2Index = indices[index + 2];
  86376. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  86377. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  86378. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  86379. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  86380. faceNormal.normalize();
  86381. faceNormals.push(faceNormal);
  86382. adjacencies.push(faceAdjacencies);
  86383. }
  86384. // Scan
  86385. for (index = 0; index < adjacencies.length; index++) {
  86386. faceAdjacencies = adjacencies[index];
  86387. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  86388. var otherFaceAdjacencies = adjacencies[otherIndex];
  86389. if (faceAdjacencies.edgesConnectedCount === 3) {
  86390. break;
  86391. }
  86392. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  86393. continue;
  86394. }
  86395. var otherP0 = indices[otherIndex * 3];
  86396. var otherP1 = indices[otherIndex * 3 + 1];
  86397. var otherP2 = indices[otherIndex * 3 + 2];
  86398. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  86399. var otherEdgeIndex = 0;
  86400. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  86401. continue;
  86402. }
  86403. switch (edgeIndex) {
  86404. case 0:
  86405. if (this._checkVerticesInsteadOfIndices) {
  86406. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86407. }
  86408. else {
  86409. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  86410. }
  86411. break;
  86412. case 1:
  86413. if (this._checkVerticesInsteadOfIndices) {
  86414. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86415. }
  86416. else {
  86417. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  86418. }
  86419. break;
  86420. case 2:
  86421. if (this._checkVerticesInsteadOfIndices) {
  86422. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86423. }
  86424. else {
  86425. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  86426. }
  86427. break;
  86428. }
  86429. if (otherEdgeIndex === -1) {
  86430. continue;
  86431. }
  86432. faceAdjacencies.edges[edgeIndex] = otherIndex;
  86433. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  86434. faceAdjacencies.edgesConnectedCount++;
  86435. otherFaceAdjacencies.edgesConnectedCount++;
  86436. if (faceAdjacencies.edgesConnectedCount === 3) {
  86437. break;
  86438. }
  86439. }
  86440. }
  86441. }
  86442. // Create lines
  86443. for (index = 0; index < adjacencies.length; index++) {
  86444. // 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
  86445. var current = adjacencies[index];
  86446. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  86447. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  86448. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  86449. }
  86450. // Merge into a single mesh
  86451. var engine = this._source.getScene().getEngine();
  86452. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  86453. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  86454. this._ib = engine.createIndexBuffer(this._linesIndices);
  86455. this._indicesCount = this._linesIndices.length;
  86456. };
  86457. EdgesRenderer.prototype.render = function () {
  86458. var scene = this._source.getScene();
  86459. if (!this._lineShader.isReady() || !scene.activeCamera) {
  86460. return;
  86461. }
  86462. var engine = scene.getEngine();
  86463. this._lineShader._preBind();
  86464. // VBOs
  86465. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  86466. scene.resetCachedMaterial();
  86467. this._lineShader.setColor4("color", this._source.edgesColor);
  86468. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  86469. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  86470. }
  86471. else {
  86472. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  86473. }
  86474. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  86475. this._lineShader.bind(this._source.getWorldMatrix());
  86476. // Draw order
  86477. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  86478. this._lineShader.unbind();
  86479. engine.setDepthWrite(true);
  86480. };
  86481. return EdgesRenderer;
  86482. }());
  86483. BABYLON.EdgesRenderer = EdgesRenderer;
  86484. })(BABYLON || (BABYLON = {}));
  86485. //# sourceMappingURL=babylon.edgesRenderer.js.map
  86486. "use strict";
  86487. var __assign = (this && this.__assign) || Object.assign || function(t) {
  86488. for (var s, i = 1, n = arguments.length; i < n; i++) {
  86489. s = arguments[i];
  86490. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  86491. t[p] = s[p];
  86492. }
  86493. return t;
  86494. };
  86495. var BABYLON;
  86496. (function (BABYLON) {
  86497. /**
  86498. * The effect layer Helps adding post process effect blended with the main pass.
  86499. *
  86500. * This can be for instance use to generate glow or higlight effects on the scene.
  86501. *
  86502. * The effect layer class can not be used directly and is intented to inherited from to be
  86503. * customized per effects.
  86504. */
  86505. var EffectLayer = /** @class */ (function () {
  86506. /**
  86507. * Instantiates a new effect Layer and references it in the scene.
  86508. * @param name The name of the layer
  86509. * @param scene The scene to use the layer in
  86510. */
  86511. function EffectLayer(
  86512. /** The Friendly of the effect in the scene */
  86513. name, scene) {
  86514. this.name = name;
  86515. this._vertexBuffers = {};
  86516. this._maxSize = 0;
  86517. this._mainTextureDesiredSize = { width: 0, height: 0 };
  86518. this._shouldRender = true;
  86519. this._postProcesses = [];
  86520. this._textures = [];
  86521. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  86522. /**
  86523. * The clear color of the texture used to generate the glow map.
  86524. */
  86525. this.neutralColor = new BABYLON.Color4();
  86526. /**
  86527. * Specifies wether the highlight layer is enabled or not.
  86528. */
  86529. this.isEnabled = true;
  86530. /**
  86531. * An event triggered when the effect layer has been disposed.
  86532. */
  86533. this.onDisposeObservable = new BABYLON.Observable();
  86534. /**
  86535. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  86536. */
  86537. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  86538. /**
  86539. * An event triggered when the generated texture is being merged in the scene.
  86540. */
  86541. this.onBeforeComposeObservable = new BABYLON.Observable();
  86542. /**
  86543. * An event triggered when the generated texture has been merged in the scene.
  86544. */
  86545. this.onAfterComposeObservable = new BABYLON.Observable();
  86546. /**
  86547. * An event triggered when the efffect layer changes its size.
  86548. */
  86549. this.onSizeChangedObservable = new BABYLON.Observable();
  86550. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86551. this._engine = scene.getEngine();
  86552. this._maxSize = this._engine.getCaps().maxTextureSize;
  86553. this._scene.effectLayers.push(this);
  86554. // Generate Buffers
  86555. this._generateIndexBuffer();
  86556. this._genrateVertexBuffer();
  86557. }
  86558. Object.defineProperty(EffectLayer.prototype, "camera", {
  86559. /**
  86560. * Gets the camera attached to the layer.
  86561. */
  86562. get: function () {
  86563. return this._effectLayerOptions.camera;
  86564. },
  86565. enumerable: true,
  86566. configurable: true
  86567. });
  86568. /**
  86569. * Initializes the effect layer with the required options.
  86570. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  86571. */
  86572. EffectLayer.prototype._init = function (options) {
  86573. // Adapt options
  86574. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86575. this._setMainTextureSize();
  86576. this._createMainTexture();
  86577. this._createTextureAndPostProcesses();
  86578. this._mergeEffect = this._createMergeEffect();
  86579. };
  86580. /**
  86581. * Generates the index buffer of the full screen quad blending to the main canvas.
  86582. */
  86583. EffectLayer.prototype._generateIndexBuffer = function () {
  86584. // Indices
  86585. var indices = [];
  86586. indices.push(0);
  86587. indices.push(1);
  86588. indices.push(2);
  86589. indices.push(0);
  86590. indices.push(2);
  86591. indices.push(3);
  86592. this._indexBuffer = this._engine.createIndexBuffer(indices);
  86593. };
  86594. /**
  86595. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  86596. */
  86597. EffectLayer.prototype._genrateVertexBuffer = function () {
  86598. // VBO
  86599. var vertices = [];
  86600. vertices.push(1, 1);
  86601. vertices.push(-1, 1);
  86602. vertices.push(-1, -1);
  86603. vertices.push(1, -1);
  86604. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86605. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86606. };
  86607. /**
  86608. * Sets the main texture desired size which is the closest power of two
  86609. * of the engine canvas size.
  86610. */
  86611. EffectLayer.prototype._setMainTextureSize = function () {
  86612. if (this._effectLayerOptions.mainTextureFixedSize) {
  86613. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  86614. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  86615. }
  86616. else {
  86617. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  86618. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  86619. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  86620. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  86621. }
  86622. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  86623. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  86624. };
  86625. /**
  86626. * Creates the main texture for the effect layer.
  86627. */
  86628. EffectLayer.prototype._createMainTexture = function () {
  86629. var _this = this;
  86630. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  86631. width: this._mainTextureDesiredSize.width,
  86632. height: this._mainTextureDesiredSize.height
  86633. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86634. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  86635. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86636. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86637. this._mainTexture.anisotropicFilteringLevel = 1;
  86638. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86639. this._mainTexture.renderParticles = false;
  86640. this._mainTexture.renderList = null;
  86641. this._mainTexture.ignoreCameraViewport = true;
  86642. // Custom render function
  86643. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86644. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  86645. var index;
  86646. var engine = _this._scene.getEngine();
  86647. if (depthOnlySubMeshes.length) {
  86648. engine.setColorWrite(false);
  86649. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86650. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  86651. }
  86652. engine.setColorWrite(true);
  86653. }
  86654. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86655. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  86656. }
  86657. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86658. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  86659. }
  86660. for (index = 0; index < transparentSubMeshes.length; index++) {
  86661. _this._renderSubMesh(transparentSubMeshes.data[index]);
  86662. }
  86663. };
  86664. this._mainTexture.onClearObservable.add(function (engine) {
  86665. engine.clear(_this.neutralColor, true, true, true);
  86666. });
  86667. };
  86668. /**
  86669. * Checks for the readiness of the element composing the layer.
  86670. * @param subMesh the mesh to check for
  86671. * @param useInstances specify wether or not to use instances to render the mesh
  86672. * @param emissiveTexture the associated emissive texture used to generate the glow
  86673. * @return true if ready otherwise, false
  86674. */
  86675. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  86676. var material = subMesh.getMaterial();
  86677. if (!material) {
  86678. return false;
  86679. }
  86680. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  86681. return false;
  86682. }
  86683. var defines = [];
  86684. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86685. var mesh = subMesh.getMesh();
  86686. var uv1 = false;
  86687. var uv2 = false;
  86688. // Alpha test
  86689. if (material && material.needAlphaTesting()) {
  86690. var alphaTexture = material.getAlphaTestTexture();
  86691. if (alphaTexture) {
  86692. defines.push("#define ALPHATEST");
  86693. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86694. alphaTexture.coordinatesIndex === 1) {
  86695. defines.push("#define DIFFUSEUV2");
  86696. uv2 = true;
  86697. }
  86698. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86699. defines.push("#define DIFFUSEUV1");
  86700. uv1 = true;
  86701. }
  86702. }
  86703. }
  86704. // Emissive
  86705. if (emissiveTexture) {
  86706. defines.push("#define EMISSIVE");
  86707. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86708. emissiveTexture.coordinatesIndex === 1) {
  86709. defines.push("#define EMISSIVEUV2");
  86710. uv2 = true;
  86711. }
  86712. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86713. defines.push("#define EMISSIVEUV1");
  86714. uv1 = true;
  86715. }
  86716. }
  86717. if (uv1) {
  86718. attribs.push(BABYLON.VertexBuffer.UVKind);
  86719. defines.push("#define UV1");
  86720. }
  86721. if (uv2) {
  86722. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86723. defines.push("#define UV2");
  86724. }
  86725. // Bones
  86726. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86727. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86728. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86729. if (mesh.numBoneInfluencers > 4) {
  86730. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86731. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86732. }
  86733. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86734. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86735. }
  86736. else {
  86737. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86738. }
  86739. // Morph targets
  86740. var manager = mesh.morphTargetManager;
  86741. var morphInfluencers = 0;
  86742. if (manager) {
  86743. if (manager.numInfluencers > 0) {
  86744. defines.push("#define MORPHTARGETS");
  86745. morphInfluencers = manager.numInfluencers;
  86746. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  86747. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  86748. }
  86749. }
  86750. // Instances
  86751. if (useInstances) {
  86752. defines.push("#define INSTANCES");
  86753. attribs.push("world0");
  86754. attribs.push("world1");
  86755. attribs.push("world2");
  86756. attribs.push("world3");
  86757. }
  86758. // Get correct effect
  86759. var join = defines.join("\n");
  86760. if (this._cachedDefines !== join) {
  86761. this._cachedDefines = join;
  86762. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  86763. }
  86764. return this._effectLayerMapGenerationEffect.isReady();
  86765. };
  86766. /**
  86767. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  86768. */
  86769. EffectLayer.prototype.render = function () {
  86770. var currentEffect = this._mergeEffect;
  86771. // Check
  86772. if (!currentEffect.isReady())
  86773. return;
  86774. for (var i = 0; i < this._postProcesses.length; i++) {
  86775. if (!this._postProcesses[i].isReady()) {
  86776. return;
  86777. }
  86778. }
  86779. var engine = this._scene.getEngine();
  86780. this.onBeforeComposeObservable.notifyObservers(this);
  86781. // Render
  86782. engine.enableEffect(currentEffect);
  86783. engine.setState(false);
  86784. // VBOs
  86785. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86786. // Cache
  86787. var previousAlphaMode = engine.getAlphaMode();
  86788. // Go Blend.
  86789. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  86790. // Blends the map on the main canvas.
  86791. this._internalRender(currentEffect);
  86792. // Restore Alpha
  86793. engine.setAlphaMode(previousAlphaMode);
  86794. this.onAfterComposeObservable.notifyObservers(this);
  86795. // Handle size changes.
  86796. var size = this._mainTexture.getSize();
  86797. this._setMainTextureSize();
  86798. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  86799. // Recreate RTT and post processes on size change.
  86800. this.onSizeChangedObservable.notifyObservers(this);
  86801. this._disposeTextureAndPostProcesses();
  86802. this._createMainTexture();
  86803. this._createTextureAndPostProcesses();
  86804. }
  86805. };
  86806. /**
  86807. * Determine if a given mesh will be used in the current effect.
  86808. * @param mesh mesh to test
  86809. * @returns true if the mesh will be used
  86810. */
  86811. EffectLayer.prototype.hasMesh = function (mesh) {
  86812. return true;
  86813. };
  86814. /**
  86815. * Returns true if the layer contains information to display, otherwise false.
  86816. * @returns true if the glow layer should be rendered
  86817. */
  86818. EffectLayer.prototype.shouldRender = function () {
  86819. return this.isEnabled && this._shouldRender;
  86820. };
  86821. /**
  86822. * Returns true if the mesh should render, otherwise false.
  86823. * @param mesh The mesh to render
  86824. * @returns true if it should render otherwise false
  86825. */
  86826. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  86827. return true;
  86828. };
  86829. /**
  86830. * Returns true if the mesh should render, otherwise false.
  86831. * @param mesh The mesh to render
  86832. * @returns true if it should render otherwise false
  86833. */
  86834. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  86835. return true;
  86836. };
  86837. /**
  86838. * Renders the submesh passed in parameter to the generation map.
  86839. */
  86840. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  86841. var _this = this;
  86842. if (!this.shouldRender()) {
  86843. return;
  86844. }
  86845. var material = subMesh.getMaterial();
  86846. var mesh = subMesh.getRenderingMesh();
  86847. var scene = this._scene;
  86848. var engine = scene.getEngine();
  86849. if (!material) {
  86850. return;
  86851. }
  86852. // Do not block in blend mode.
  86853. if (material.needAlphaBlendingForMesh(mesh)) {
  86854. return;
  86855. }
  86856. // Culling
  86857. engine.setState(material.backFaceCulling);
  86858. // Managing instances
  86859. var batch = mesh._getInstancesRenderList(subMesh._id);
  86860. if (batch.mustReturn) {
  86861. return;
  86862. }
  86863. // Early Exit per mesh
  86864. if (!this._shouldRenderMesh(mesh)) {
  86865. return;
  86866. }
  86867. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86868. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  86869. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  86870. engine.enableEffect(this._effectLayerMapGenerationEffect);
  86871. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  86872. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  86873. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  86874. // Alpha test
  86875. if (material && material.needAlphaTesting()) {
  86876. var alphaTexture = material.getAlphaTestTexture();
  86877. if (alphaTexture) {
  86878. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  86879. var textureMatrix = alphaTexture.getTextureMatrix();
  86880. if (textureMatrix) {
  86881. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  86882. }
  86883. }
  86884. }
  86885. // Glow emissive only
  86886. if (this._emissiveTextureAndColor.texture) {
  86887. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  86888. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  86889. }
  86890. // Bones
  86891. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86892. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86893. }
  86894. // Morph targets
  86895. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  86896. // Draw
  86897. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  86898. }
  86899. else {
  86900. // Need to reset refresh rate of the shadowMap
  86901. this._mainTexture.resetRefreshCounter();
  86902. }
  86903. };
  86904. /**
  86905. * Rebuild the required buffers.
  86906. * @ignore Internal use only.
  86907. */
  86908. EffectLayer.prototype._rebuild = function () {
  86909. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86910. if (vb) {
  86911. vb._rebuild();
  86912. }
  86913. this._generateIndexBuffer();
  86914. };
  86915. /**
  86916. * Dispose only the render target textures and post process.
  86917. */
  86918. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  86919. this._mainTexture.dispose();
  86920. for (var i = 0; i < this._postProcesses.length; i++) {
  86921. if (this._postProcesses[i]) {
  86922. this._postProcesses[i].dispose();
  86923. }
  86924. }
  86925. this._postProcesses = [];
  86926. for (var i = 0; i < this._textures.length; i++) {
  86927. if (this._textures[i]) {
  86928. this._textures[i].dispose();
  86929. }
  86930. }
  86931. this._textures = [];
  86932. };
  86933. /**
  86934. * Dispose the highlight layer and free resources.
  86935. */
  86936. EffectLayer.prototype.dispose = function () {
  86937. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86938. if (vertexBuffer) {
  86939. vertexBuffer.dispose();
  86940. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86941. }
  86942. if (this._indexBuffer) {
  86943. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86944. this._indexBuffer = null;
  86945. }
  86946. // Clean textures and post processes
  86947. this._disposeTextureAndPostProcesses();
  86948. // Remove from scene
  86949. var index = this._scene.effectLayers.indexOf(this, 0);
  86950. if (index > -1) {
  86951. this._scene.effectLayers.splice(index, 1);
  86952. }
  86953. // Callback
  86954. this.onDisposeObservable.notifyObservers(this);
  86955. this.onDisposeObservable.clear();
  86956. this.onBeforeRenderMainTextureObservable.clear();
  86957. this.onBeforeComposeObservable.clear();
  86958. this.onAfterComposeObservable.clear();
  86959. this.onSizeChangedObservable.clear();
  86960. };
  86961. return EffectLayer;
  86962. }());
  86963. BABYLON.EffectLayer = EffectLayer;
  86964. })(BABYLON || (BABYLON = {}));
  86965. //# sourceMappingURL=babylon.effectLayer.js.map
  86966. "use strict";
  86967. var BABYLON;
  86968. (function (BABYLON) {
  86969. /**
  86970. * Special Glow Blur post process only blurring the alpha channel
  86971. * It enforces keeping the most luminous color in the color channel.
  86972. */
  86973. var GlowBlurPostProcess = /** @class */ (function (_super) {
  86974. __extends(GlowBlurPostProcess, _super);
  86975. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  86976. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86977. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  86978. _this.direction = direction;
  86979. _this.kernel = kernel;
  86980. _this.onApplyObservable.add(function (effect) {
  86981. effect.setFloat2("screenSize", _this.width, _this.height);
  86982. effect.setVector2("direction", _this.direction);
  86983. effect.setFloat("blurWidth", _this.kernel);
  86984. });
  86985. return _this;
  86986. }
  86987. return GlowBlurPostProcess;
  86988. }(BABYLON.PostProcess));
  86989. /**
  86990. * The highlight layer Helps adding a glow effect around a mesh.
  86991. *
  86992. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86993. * glowy meshes to your scene.
  86994. *
  86995. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  86996. */
  86997. var HighlightLayer = /** @class */ (function (_super) {
  86998. __extends(HighlightLayer, _super);
  86999. /**
  87000. * Instantiates a new highlight Layer and references it to the scene..
  87001. * @param name The name of the layer
  87002. * @param scene The scene to use the layer in
  87003. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  87004. */
  87005. function HighlightLayer(name, scene, options) {
  87006. var _this = _super.call(this, name, scene) || this;
  87007. _this.name = name;
  87008. /**
  87009. * Specifies whether or not the inner glow is ACTIVE in the layer.
  87010. */
  87011. _this.innerGlow = true;
  87012. /**
  87013. * Specifies whether or not the outer glow is ACTIVE in the layer.
  87014. */
  87015. _this.outerGlow = true;
  87016. /**
  87017. * An event triggered when the highlight layer is being blurred.
  87018. */
  87019. _this.onBeforeBlurObservable = new BABYLON.Observable();
  87020. /**
  87021. * An event triggered when the highlight layer has been blurred.
  87022. */
  87023. _this.onAfterBlurObservable = new BABYLON.Observable();
  87024. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  87025. _this._meshes = {};
  87026. _this._excludedMeshes = {};
  87027. _this.neutralColor = HighlightLayer.NeutralColor;
  87028. // Warn on stencil
  87029. if (!_this._engine.isStencilEnable) {
  87030. 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 }");
  87031. }
  87032. // Adapt options
  87033. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  87034. // Initialize the layer
  87035. _this._init({
  87036. alphaBlendingMode: _this._options.alphaBlendingMode,
  87037. camera: _this._options.camera,
  87038. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87039. mainTextureRatio: _this._options.mainTextureRatio
  87040. });
  87041. // Do not render as long as no meshes have been added
  87042. _this._shouldRender = false;
  87043. return _this;
  87044. }
  87045. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  87046. /**
  87047. * Gets the horizontal size of the blur.
  87048. */
  87049. get: function () {
  87050. return this._horizontalBlurPostprocess.kernel;
  87051. },
  87052. /**
  87053. * Specifies the horizontal size of the blur.
  87054. */
  87055. set: function (value) {
  87056. this._horizontalBlurPostprocess.kernel = value;
  87057. },
  87058. enumerable: true,
  87059. configurable: true
  87060. });
  87061. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  87062. /**
  87063. * Gets the vertical size of the blur.
  87064. */
  87065. get: function () {
  87066. return this._verticalBlurPostprocess.kernel;
  87067. },
  87068. /**
  87069. * Specifies the vertical size of the blur.
  87070. */
  87071. set: function (value) {
  87072. this._verticalBlurPostprocess.kernel = value;
  87073. },
  87074. enumerable: true,
  87075. configurable: true
  87076. });
  87077. /**
  87078. * Get the effect name of the layer.
  87079. * @return The effect name
  87080. */
  87081. HighlightLayer.prototype.getEffectName = function () {
  87082. return HighlightLayer.EffectName;
  87083. };
  87084. /**
  87085. * Create the merge effect. This is the shader use to blit the information back
  87086. * to the main canvas at the end of the scene rendering.
  87087. */
  87088. HighlightLayer.prototype._createMergeEffect = function () {
  87089. // Effect
  87090. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  87091. };
  87092. /**
  87093. * Creates the render target textures and post processes used in the highlight layer.
  87094. */
  87095. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  87096. var _this = this;
  87097. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  87098. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  87099. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87100. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87101. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  87102. width: blurTextureWidth,
  87103. height: blurTextureHeight
  87104. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87105. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87106. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87107. this._blurTexture.anisotropicFilteringLevel = 16;
  87108. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  87109. this._blurTexture.renderParticles = false;
  87110. this._blurTexture.ignoreCameraViewport = true;
  87111. this._textures = [this._blurTexture];
  87112. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  87113. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87114. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  87115. effect.setTexture("textureSampler", _this._mainTexture);
  87116. });
  87117. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87118. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  87119. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  87120. });
  87121. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87122. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  87123. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  87124. });
  87125. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  87126. }
  87127. else {
  87128. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  87129. width: blurTextureWidth,
  87130. height: blurTextureHeight
  87131. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87132. this._horizontalBlurPostprocess.width = blurTextureWidth;
  87133. this._horizontalBlurPostprocess.height = blurTextureHeight;
  87134. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  87135. effect.setTexture("textureSampler", _this._mainTexture);
  87136. });
  87137. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  87138. width: blurTextureWidth,
  87139. height: blurTextureHeight
  87140. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87141. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  87142. }
  87143. this._mainTexture.onAfterUnbindObservable.add(function () {
  87144. _this.onBeforeBlurObservable.notifyObservers(_this);
  87145. var internalTexture = _this._blurTexture.getInternalTexture();
  87146. if (internalTexture) {
  87147. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  87148. }
  87149. _this.onAfterBlurObservable.notifyObservers(_this);
  87150. });
  87151. // Prevent autoClear.
  87152. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87153. };
  87154. /**
  87155. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87156. */
  87157. HighlightLayer.prototype.needStencil = function () {
  87158. return true;
  87159. };
  87160. /**
  87161. * Checks for the readiness of the element composing the layer.
  87162. * @param subMesh the mesh to check for
  87163. * @param useInstances specify wether or not to use instances to render the mesh
  87164. * @param emissiveTexture the associated emissive texture used to generate the glow
  87165. * @return true if ready otherwise, false
  87166. */
  87167. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  87168. var material = subMesh.getMaterial();
  87169. var mesh = subMesh.getRenderingMesh();
  87170. if (!material || !mesh || !this._meshes) {
  87171. return false;
  87172. }
  87173. var emissiveTexture = null;
  87174. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  87175. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  87176. emissiveTexture = material.emissiveTexture;
  87177. }
  87178. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87179. };
  87180. /**
  87181. * Implementation specific of rendering the generating effect on the main canvas.
  87182. * @param effect The effect used to render through
  87183. */
  87184. HighlightLayer.prototype._internalRender = function (effect) {
  87185. // Texture
  87186. effect.setTexture("textureSampler", this._blurTexture);
  87187. // Cache
  87188. var engine = this._engine;
  87189. var previousStencilBuffer = engine.getStencilBuffer();
  87190. var previousStencilFunction = engine.getStencilFunction();
  87191. var previousStencilMask = engine.getStencilMask();
  87192. var previousStencilOperationPass = engine.getStencilOperationPass();
  87193. var previousStencilOperationFail = engine.getStencilOperationFail();
  87194. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  87195. var previousStencilReference = engine.getStencilFunctionReference();
  87196. // Stencil operations
  87197. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  87198. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  87199. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  87200. // Draw order
  87201. engine.setStencilMask(0x00);
  87202. engine.setStencilBuffer(true);
  87203. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  87204. // 2 passes inner outer
  87205. if (this.outerGlow) {
  87206. effect.setFloat("offset", 0);
  87207. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  87208. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87209. }
  87210. if (this.innerGlow) {
  87211. effect.setFloat("offset", 1);
  87212. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  87213. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87214. }
  87215. // Restore Cache
  87216. engine.setStencilFunction(previousStencilFunction);
  87217. engine.setStencilMask(previousStencilMask);
  87218. engine.setStencilBuffer(previousStencilBuffer);
  87219. engine.setStencilOperationPass(previousStencilOperationPass);
  87220. engine.setStencilOperationFail(previousStencilOperationFail);
  87221. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  87222. engine.setStencilFunctionReference(previousStencilReference);
  87223. };
  87224. /**
  87225. * Returns true if the layer contains information to display, otherwise false.
  87226. */
  87227. HighlightLayer.prototype.shouldRender = function () {
  87228. if (_super.prototype.shouldRender.call(this)) {
  87229. return this._meshes ? true : false;
  87230. }
  87231. return false;
  87232. };
  87233. /**
  87234. * Returns true if the mesh should render, otherwise false.
  87235. * @param mesh The mesh to render
  87236. * @returns true if it should render otherwise false
  87237. */
  87238. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  87239. // Excluded Mesh
  87240. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  87241. return false;
  87242. }
  87243. ;
  87244. return true;
  87245. };
  87246. /**
  87247. * Sets the required values for both the emissive texture and and the main color.
  87248. */
  87249. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87250. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  87251. if (highlightLayerMesh) {
  87252. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  87253. }
  87254. else {
  87255. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87256. }
  87257. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  87258. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87259. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  87260. }
  87261. else {
  87262. this._emissiveTextureAndColor.texture = null;
  87263. }
  87264. };
  87265. /**
  87266. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  87267. * @param mesh The mesh to exclude from the highlight layer
  87268. */
  87269. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  87270. if (!this._excludedMeshes) {
  87271. return;
  87272. }
  87273. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  87274. if (!meshExcluded) {
  87275. this._excludedMeshes[mesh.uniqueId] = {
  87276. mesh: mesh,
  87277. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  87278. mesh.getEngine().setStencilBuffer(false);
  87279. }),
  87280. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  87281. mesh.getEngine().setStencilBuffer(true);
  87282. }),
  87283. };
  87284. }
  87285. };
  87286. /**
  87287. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  87288. * @param mesh The mesh to highlight
  87289. */
  87290. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  87291. if (!this._excludedMeshes) {
  87292. return;
  87293. }
  87294. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  87295. if (meshExcluded) {
  87296. if (meshExcluded.beforeRender) {
  87297. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  87298. }
  87299. if (meshExcluded.afterRender) {
  87300. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  87301. }
  87302. }
  87303. this._excludedMeshes[mesh.uniqueId] = null;
  87304. };
  87305. /**
  87306. * Determine if a given mesh will be highlighted by the current HighlightLayer
  87307. * @param mesh mesh to test
  87308. * @returns true if the mesh will be highlighted by the current HighlightLayer
  87309. */
  87310. HighlightLayer.prototype.hasMesh = function (mesh) {
  87311. if (!this._meshes) {
  87312. return false;
  87313. }
  87314. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  87315. };
  87316. /**
  87317. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  87318. * @param mesh The mesh to highlight
  87319. * @param color The color of the highlight
  87320. * @param glowEmissiveOnly Extract the glow from the emissive texture
  87321. */
  87322. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  87323. var _this = this;
  87324. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  87325. if (!this._meshes) {
  87326. return;
  87327. }
  87328. var meshHighlight = this._meshes[mesh.uniqueId];
  87329. if (meshHighlight) {
  87330. meshHighlight.color = color;
  87331. }
  87332. else {
  87333. this._meshes[mesh.uniqueId] = {
  87334. mesh: mesh,
  87335. color: color,
  87336. // Lambda required for capture due to Observable this context
  87337. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  87338. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  87339. _this._defaultStencilReference(mesh);
  87340. }
  87341. else {
  87342. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  87343. }
  87344. }),
  87345. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  87346. glowEmissiveOnly: glowEmissiveOnly
  87347. };
  87348. }
  87349. this._shouldRender = true;
  87350. };
  87351. /**
  87352. * Remove a mesh from the highlight layer in order to make it stop glowing.
  87353. * @param mesh The mesh to highlight
  87354. */
  87355. HighlightLayer.prototype.removeMesh = function (mesh) {
  87356. if (!this._meshes) {
  87357. return;
  87358. }
  87359. var meshHighlight = this._meshes[mesh.uniqueId];
  87360. if (meshHighlight) {
  87361. if (meshHighlight.observerHighlight) {
  87362. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87363. }
  87364. if (meshHighlight.observerDefault) {
  87365. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87366. }
  87367. delete this._meshes[mesh.uniqueId];
  87368. }
  87369. this._shouldRender = false;
  87370. for (var meshHighlightToCheck in this._meshes) {
  87371. if (this._meshes[meshHighlightToCheck]) {
  87372. this._shouldRender = true;
  87373. break;
  87374. }
  87375. }
  87376. };
  87377. /**
  87378. * Force the stencil to the normal expected value for none glowing parts
  87379. */
  87380. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  87381. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  87382. };
  87383. /**
  87384. * Free any resources and references associated to a mesh.
  87385. * Internal use
  87386. * @param mesh The mesh to free.
  87387. */
  87388. HighlightLayer.prototype._disposeMesh = function (mesh) {
  87389. this.removeMesh(mesh);
  87390. this.removeExcludedMesh(mesh);
  87391. };
  87392. /**
  87393. * Dispose the highlight layer and free resources.
  87394. */
  87395. HighlightLayer.prototype.dispose = function () {
  87396. if (this._meshes) {
  87397. // Clean mesh references
  87398. for (var id in this._meshes) {
  87399. var meshHighlight = this._meshes[id];
  87400. if (meshHighlight && meshHighlight.mesh) {
  87401. if (meshHighlight.observerHighlight) {
  87402. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87403. }
  87404. if (meshHighlight.observerDefault) {
  87405. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87406. }
  87407. }
  87408. }
  87409. this._meshes = null;
  87410. }
  87411. if (this._excludedMeshes) {
  87412. for (var id in this._excludedMeshes) {
  87413. var meshHighlight = this._excludedMeshes[id];
  87414. if (meshHighlight) {
  87415. if (meshHighlight.beforeRender) {
  87416. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  87417. }
  87418. if (meshHighlight.afterRender) {
  87419. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  87420. }
  87421. }
  87422. }
  87423. this._excludedMeshes = null;
  87424. }
  87425. _super.prototype.dispose.call(this);
  87426. };
  87427. /**
  87428. * Effect Name of the highlight layer.
  87429. */
  87430. HighlightLayer.EffectName = "HighlightLayer";
  87431. /**
  87432. * The neutral color used during the preparation of the glow effect.
  87433. * This is black by default as the blend operation is a blend operation.
  87434. */
  87435. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  87436. /**
  87437. * Stencil value used for glowing meshes.
  87438. */
  87439. HighlightLayer.GlowingMeshStencilReference = 0x02;
  87440. /**
  87441. * Stencil value used for the other meshes in the scene.
  87442. */
  87443. HighlightLayer.NormalMeshStencilReference = 0x01;
  87444. return HighlightLayer;
  87445. }(BABYLON.EffectLayer));
  87446. BABYLON.HighlightLayer = HighlightLayer;
  87447. })(BABYLON || (BABYLON = {}));
  87448. //# sourceMappingURL=babylon.highlightLayer.js.map
  87449. "use strict";
  87450. var BABYLON;
  87451. (function (BABYLON) {
  87452. /**
  87453. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  87454. *
  87455. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  87456. * glowy meshes to your scene.
  87457. *
  87458. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  87459. */
  87460. var GlowLayer = /** @class */ (function (_super) {
  87461. __extends(GlowLayer, _super);
  87462. /**
  87463. * Instantiates a new glow Layer and references it to the scene.
  87464. * @param name The name of the layer
  87465. * @param scene The scene to use the layer in
  87466. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  87467. */
  87468. function GlowLayer(name, scene, options) {
  87469. var _this = _super.call(this, name, scene) || this;
  87470. _this.name = name;
  87471. _this._intensity = 1.0;
  87472. _this._includedOnlyMeshes = [];
  87473. _this._excludedMeshes = [];
  87474. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  87475. // Adapt options
  87476. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  87477. // Initialize the layer
  87478. _this._init({
  87479. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  87480. camera: _this._options.camera,
  87481. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87482. mainTextureRatio: _this._options.mainTextureRatio
  87483. });
  87484. return _this;
  87485. }
  87486. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  87487. /**
  87488. * Gets the kernel size of the blur.
  87489. */
  87490. get: function () {
  87491. return this._horizontalBlurPostprocess1.kernel;
  87492. },
  87493. /**
  87494. * Sets the kernel size of the blur.
  87495. */
  87496. set: function (value) {
  87497. this._horizontalBlurPostprocess1.kernel = value;
  87498. this._verticalBlurPostprocess1.kernel = value;
  87499. this._horizontalBlurPostprocess2.kernel = value;
  87500. this._verticalBlurPostprocess2.kernel = value;
  87501. },
  87502. enumerable: true,
  87503. configurable: true
  87504. });
  87505. Object.defineProperty(GlowLayer.prototype, "intensity", {
  87506. /**
  87507. * Gets the glow intensity.
  87508. */
  87509. get: function () {
  87510. return this._intensity;
  87511. },
  87512. /**
  87513. * Sets the glow intensity.
  87514. */
  87515. set: function (value) {
  87516. this._intensity = value;
  87517. },
  87518. enumerable: true,
  87519. configurable: true
  87520. });
  87521. /**
  87522. * Get the effect name of the layer.
  87523. * @return The effect name
  87524. */
  87525. GlowLayer.prototype.getEffectName = function () {
  87526. return GlowLayer.EffectName;
  87527. };
  87528. /**
  87529. * Create the merge effect. This is the shader use to blit the information back
  87530. * to the main canvas at the end of the scene rendering.
  87531. */
  87532. GlowLayer.prototype._createMergeEffect = function () {
  87533. // Effect
  87534. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  87535. };
  87536. /**
  87537. * Creates the render target textures and post processes used in the glow layer.
  87538. */
  87539. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  87540. var _this = this;
  87541. var blurTextureWidth = this._mainTextureDesiredSize.width;
  87542. var blurTextureHeight = this._mainTextureDesiredSize.height;
  87543. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87544. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87545. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  87546. width: blurTextureWidth,
  87547. height: blurTextureHeight
  87548. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87549. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87550. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87551. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87552. this._blurTexture1.renderParticles = false;
  87553. this._blurTexture1.ignoreCameraViewport = true;
  87554. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  87555. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  87556. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  87557. width: blurTextureWidth2,
  87558. height: blurTextureHeight2
  87559. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87560. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87561. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87562. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87563. this._blurTexture2.renderParticles = false;
  87564. this._blurTexture2.ignoreCameraViewport = true;
  87565. this._textures = [this._blurTexture1, this._blurTexture2];
  87566. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87567. width: blurTextureWidth,
  87568. height: blurTextureHeight
  87569. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87570. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  87571. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  87572. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  87573. effect.setTexture("textureSampler", _this._mainTexture);
  87574. });
  87575. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87576. width: blurTextureWidth,
  87577. height: blurTextureHeight
  87578. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87579. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87580. width: blurTextureWidth2,
  87581. height: blurTextureHeight2
  87582. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87583. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  87584. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  87585. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  87586. effect.setTexture("textureSampler", _this._blurTexture1);
  87587. });
  87588. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87589. width: blurTextureWidth2,
  87590. height: blurTextureHeight2
  87591. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87592. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87593. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  87594. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87595. this._mainTexture.samples = this._options.mainTextureSamples;
  87596. this._mainTexture.onAfterUnbindObservable.add(function () {
  87597. var internalTexture = _this._blurTexture1.getInternalTexture();
  87598. if (internalTexture) {
  87599. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  87600. internalTexture = _this._blurTexture2.getInternalTexture();
  87601. if (internalTexture) {
  87602. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  87603. }
  87604. }
  87605. });
  87606. // Prevent autoClear.
  87607. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87608. };
  87609. /**
  87610. * Checks for the readiness of the element composing the layer.
  87611. * @param subMesh the mesh to check for
  87612. * @param useInstances specify wether or not to use instances to render the mesh
  87613. * @param emissiveTexture the associated emissive texture used to generate the glow
  87614. * @return true if ready otherwise, false
  87615. */
  87616. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  87617. var material = subMesh.getMaterial();
  87618. var mesh = subMesh.getRenderingMesh();
  87619. if (!material || !mesh) {
  87620. return false;
  87621. }
  87622. var emissiveTexture = material.emissiveTexture;
  87623. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87624. };
  87625. /**
  87626. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87627. */
  87628. GlowLayer.prototype.needStencil = function () {
  87629. return false;
  87630. };
  87631. /**
  87632. * Implementation specific of rendering the generating effect on the main canvas.
  87633. * @param effect The effect used to render through
  87634. */
  87635. GlowLayer.prototype._internalRender = function (effect) {
  87636. // Texture
  87637. effect.setTexture("textureSampler", this._blurTexture1);
  87638. effect.setTexture("textureSampler2", this._blurTexture2);
  87639. effect.setFloat("offset", this._intensity);
  87640. // Cache
  87641. var engine = this._engine;
  87642. var previousStencilBuffer = engine.getStencilBuffer();
  87643. // Draw order
  87644. engine.setStencilBuffer(false);
  87645. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87646. // Draw order
  87647. engine.setStencilBuffer(previousStencilBuffer);
  87648. };
  87649. /**
  87650. * Sets the required values for both the emissive texture and and the main color.
  87651. */
  87652. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87653. var textureLevel = 1.0;
  87654. if (this.customEmissiveTextureSelector) {
  87655. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  87656. }
  87657. else {
  87658. if (material) {
  87659. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87660. if (this._emissiveTextureAndColor.texture) {
  87661. textureLevel = this._emissiveTextureAndColor.texture.level;
  87662. }
  87663. }
  87664. else {
  87665. this._emissiveTextureAndColor.texture = null;
  87666. }
  87667. }
  87668. if (this.customEmissiveColorSelector) {
  87669. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  87670. }
  87671. else {
  87672. if (material.emissiveColor) {
  87673. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  87674. }
  87675. else {
  87676. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87677. }
  87678. }
  87679. };
  87680. /**
  87681. * Returns true if the mesh should render, otherwise false.
  87682. * @param mesh The mesh to render
  87683. * @returns true if it should render otherwise false
  87684. */
  87685. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  87686. return this.hasMesh(mesh);
  87687. };
  87688. /**
  87689. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  87690. * @param mesh The mesh to exclude from the glow layer
  87691. */
  87692. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  87693. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  87694. this._excludedMeshes.push(mesh.uniqueId);
  87695. }
  87696. };
  87697. /**
  87698. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  87699. * @param mesh The mesh to remove
  87700. */
  87701. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  87702. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  87703. if (index !== -1) {
  87704. this._excludedMeshes.splice(index, 1);
  87705. }
  87706. };
  87707. /**
  87708. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  87709. * @param mesh The mesh to include in the glow layer
  87710. */
  87711. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  87712. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  87713. this._includedOnlyMeshes.push(mesh.uniqueId);
  87714. }
  87715. };
  87716. /**
  87717. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  87718. * @param mesh The mesh to remove
  87719. */
  87720. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  87721. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  87722. if (index !== -1) {
  87723. this._includedOnlyMeshes.splice(index, 1);
  87724. }
  87725. };
  87726. /**
  87727. * Determine if a given mesh will be used in the glow layer
  87728. * @param mesh The mesh to test
  87729. * @returns true if the mesh will be highlighted by the current glow layer
  87730. */
  87731. GlowLayer.prototype.hasMesh = function (mesh) {
  87732. // Included Mesh
  87733. if (this._includedOnlyMeshes.length) {
  87734. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  87735. }
  87736. ;
  87737. // Excluded Mesh
  87738. if (this._excludedMeshes.length) {
  87739. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  87740. }
  87741. ;
  87742. return true;
  87743. };
  87744. /**
  87745. * Free any resources and references associated to a mesh.
  87746. * Internal use
  87747. * @param mesh The mesh to free.
  87748. */
  87749. GlowLayer.prototype._disposeMesh = function (mesh) {
  87750. this.removeIncludedOnlyMesh(mesh);
  87751. this.removeExcludedMesh(mesh);
  87752. };
  87753. /**
  87754. * Effect Name of the layer.
  87755. */
  87756. GlowLayer.EffectName = "GlowLayer";
  87757. /**
  87758. * The default blur kernel size used for the glow.
  87759. */
  87760. GlowLayer.DefaultBlurKernelSize = 32;
  87761. /**
  87762. * The default texture size ratio used for the glow.
  87763. */
  87764. GlowLayer.DefaultTextureRatio = 0.5;
  87765. return GlowLayer;
  87766. }(BABYLON.EffectLayer));
  87767. BABYLON.GlowLayer = GlowLayer;
  87768. })(BABYLON || (BABYLON = {}));
  87769. //# sourceMappingURL=babylon.glowLayer.js.map
  87770. "use strict";
  87771. var BABYLON;
  87772. (function (BABYLON) {
  87773. /**
  87774. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  87775. */
  87776. var AssetTaskState;
  87777. (function (AssetTaskState) {
  87778. /**
  87779. * Initialization
  87780. */
  87781. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  87782. /**
  87783. * Running
  87784. */
  87785. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  87786. /**
  87787. * Done
  87788. */
  87789. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  87790. /**
  87791. * Error
  87792. */
  87793. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  87794. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  87795. /**
  87796. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  87797. */
  87798. var AbstractAssetTask = /** @class */ (function () {
  87799. /**
  87800. * Creates a new {BABYLON.AssetsManager}
  87801. * @param name defines the name of the task
  87802. */
  87803. function AbstractAssetTask(
  87804. /**
  87805. * Task name
  87806. */ name) {
  87807. this.name = name;
  87808. this._isCompleted = false;
  87809. this._taskState = AssetTaskState.INIT;
  87810. }
  87811. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  87812. /**
  87813. * Get if the task is completed
  87814. */
  87815. get: function () {
  87816. return this._isCompleted;
  87817. },
  87818. enumerable: true,
  87819. configurable: true
  87820. });
  87821. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  87822. /**
  87823. * Gets the current state of the task
  87824. */
  87825. get: function () {
  87826. return this._taskState;
  87827. },
  87828. enumerable: true,
  87829. configurable: true
  87830. });
  87831. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  87832. /**
  87833. * Gets the current error object (if task is in error)
  87834. */
  87835. get: function () {
  87836. return this._errorObject;
  87837. },
  87838. enumerable: true,
  87839. configurable: true
  87840. });
  87841. /**
  87842. * Internal only
  87843. * @ignore
  87844. */
  87845. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  87846. if (this._errorObject) {
  87847. return;
  87848. }
  87849. this._errorObject = {
  87850. message: message,
  87851. exception: exception
  87852. };
  87853. };
  87854. /**
  87855. * Execute the current task
  87856. * @param scene defines the scene where you want your assets to be loaded
  87857. * @param onSuccess is a callback called when the task is successfully executed
  87858. * @param onError is a callback called if an error occurs
  87859. */
  87860. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87861. var _this = this;
  87862. this._taskState = AssetTaskState.RUNNING;
  87863. this.runTask(scene, function () {
  87864. _this.onDoneCallback(onSuccess, onError);
  87865. }, function (msg, exception) {
  87866. _this.onErrorCallback(onError, msg, exception);
  87867. });
  87868. };
  87869. /**
  87870. * Execute the current task
  87871. * @param scene defines the scene where you want your assets to be loaded
  87872. * @param onSuccess is a callback called when the task is successfully executed
  87873. * @param onError is a callback called if an error occurs
  87874. */
  87875. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87876. throw new Error("runTask is not implemented");
  87877. };
  87878. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  87879. this._taskState = AssetTaskState.ERROR;
  87880. this._errorObject = {
  87881. message: message,
  87882. exception: exception
  87883. };
  87884. if (this.onError) {
  87885. this.onError(this, message, exception);
  87886. }
  87887. onError();
  87888. };
  87889. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  87890. try {
  87891. this._taskState = AssetTaskState.DONE;
  87892. this._isCompleted = true;
  87893. if (this.onSuccess) {
  87894. this.onSuccess(this);
  87895. }
  87896. onSuccess();
  87897. }
  87898. catch (e) {
  87899. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  87900. }
  87901. };
  87902. return AbstractAssetTask;
  87903. }());
  87904. BABYLON.AbstractAssetTask = AbstractAssetTask;
  87905. /**
  87906. * Class used to share progress information about assets loading
  87907. */
  87908. var AssetsProgressEvent = /** @class */ (function () {
  87909. /**
  87910. * Creates a {BABYLON.AssetsProgressEvent}
  87911. * @param remainingCount defines the number of remaining tasks to process
  87912. * @param totalCount defines the total number of tasks
  87913. * @param task defines the task that was just processed
  87914. */
  87915. function AssetsProgressEvent(remainingCount, totalCount, task) {
  87916. this.remainingCount = remainingCount;
  87917. this.totalCount = totalCount;
  87918. this.task = task;
  87919. }
  87920. return AssetsProgressEvent;
  87921. }());
  87922. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  87923. /**
  87924. * Define a task used by {BABYLON.AssetsManager} to load meshes
  87925. */
  87926. var MeshAssetTask = /** @class */ (function (_super) {
  87927. __extends(MeshAssetTask, _super);
  87928. /**
  87929. * Creates a new {BABYLON.MeshAssetTask}
  87930. * @param name defines the name of the task
  87931. * @param meshesNames defines the list of mesh's names you want to load
  87932. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  87933. * @param sceneFilename defines the filename of the scene to load from
  87934. */
  87935. function MeshAssetTask(
  87936. /**
  87937. * Defines the name of the task
  87938. */
  87939. name,
  87940. /**
  87941. * Defines the list of mesh's names you want to load
  87942. */
  87943. meshesNames,
  87944. /**
  87945. * Defines the root url to use as a base to load your meshes and associated resources
  87946. */
  87947. rootUrl,
  87948. /**
  87949. * Defines the filename of the scene to load from
  87950. */
  87951. sceneFilename) {
  87952. var _this = _super.call(this, name) || this;
  87953. _this.name = name;
  87954. _this.meshesNames = meshesNames;
  87955. _this.rootUrl = rootUrl;
  87956. _this.sceneFilename = sceneFilename;
  87957. return _this;
  87958. }
  87959. /**
  87960. * Execute the current task
  87961. * @param scene defines the scene where you want your assets to be loaded
  87962. * @param onSuccess is a callback called when the task is successfully executed
  87963. * @param onError is a callback called if an error occurs
  87964. */
  87965. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87966. var _this = this;
  87967. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  87968. _this.loadedMeshes = meshes;
  87969. _this.loadedParticleSystems = particleSystems;
  87970. _this.loadedSkeletons = skeletons;
  87971. onSuccess();
  87972. }, null, function (scene, message, exception) {
  87973. onError(message, exception);
  87974. });
  87975. };
  87976. return MeshAssetTask;
  87977. }(AbstractAssetTask));
  87978. BABYLON.MeshAssetTask = MeshAssetTask;
  87979. /**
  87980. * Define a task used by {BABYLON.AssetsManager} to load text content
  87981. */
  87982. var TextFileAssetTask = /** @class */ (function (_super) {
  87983. __extends(TextFileAssetTask, _super);
  87984. /**
  87985. * Creates a new TextFileAssetTask object
  87986. * @param name defines the name of the task
  87987. * @param url defines the location of the file to load
  87988. */
  87989. function TextFileAssetTask(
  87990. /**
  87991. * Defines the name of the task
  87992. */
  87993. name,
  87994. /**
  87995. * Defines the location of the file to load
  87996. */
  87997. url) {
  87998. var _this = _super.call(this, name) || this;
  87999. _this.name = name;
  88000. _this.url = url;
  88001. return _this;
  88002. }
  88003. /**
  88004. * Execute the current task
  88005. * @param scene defines the scene where you want your assets to be loaded
  88006. * @param onSuccess is a callback called when the task is successfully executed
  88007. * @param onError is a callback called if an error occurs
  88008. */
  88009. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88010. var _this = this;
  88011. scene._loadFile(this.url, function (data) {
  88012. _this.text = data;
  88013. onSuccess();
  88014. }, undefined, false, false, function (request, exception) {
  88015. if (request) {
  88016. onError(request.status + " " + request.statusText, exception);
  88017. }
  88018. });
  88019. };
  88020. return TextFileAssetTask;
  88021. }(AbstractAssetTask));
  88022. BABYLON.TextFileAssetTask = TextFileAssetTask;
  88023. /**
  88024. * Define a task used by {BABYLON.AssetsManager} to load binary data
  88025. */
  88026. var BinaryFileAssetTask = /** @class */ (function (_super) {
  88027. __extends(BinaryFileAssetTask, _super);
  88028. /**
  88029. * Creates a new BinaryFileAssetTask object
  88030. * @param name defines the name of the new task
  88031. * @param url defines the location of the file to load
  88032. */
  88033. function BinaryFileAssetTask(
  88034. /**
  88035. * Defines the name of the task
  88036. */
  88037. name,
  88038. /**
  88039. * Defines the location of the file to load
  88040. */
  88041. url) {
  88042. var _this = _super.call(this, name) || this;
  88043. _this.name = name;
  88044. _this.url = url;
  88045. return _this;
  88046. }
  88047. /**
  88048. * Execute the current task
  88049. * @param scene defines the scene where you want your assets to be loaded
  88050. * @param onSuccess is a callback called when the task is successfully executed
  88051. * @param onError is a callback called if an error occurs
  88052. */
  88053. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88054. var _this = this;
  88055. scene._loadFile(this.url, function (data) {
  88056. _this.data = data;
  88057. onSuccess();
  88058. }, undefined, true, true, function (request, exception) {
  88059. if (request) {
  88060. onError(request.status + " " + request.statusText, exception);
  88061. }
  88062. });
  88063. };
  88064. return BinaryFileAssetTask;
  88065. }(AbstractAssetTask));
  88066. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  88067. /**
  88068. * Define a task used by {BABYLON.AssetsManager} to load images
  88069. */
  88070. var ImageAssetTask = /** @class */ (function (_super) {
  88071. __extends(ImageAssetTask, _super);
  88072. /**
  88073. * Creates a new ImageAssetTask
  88074. * @param name defines the name of the task
  88075. * @param url defines the location of the image to load
  88076. */
  88077. function ImageAssetTask(
  88078. /**
  88079. * Defines the name of the task
  88080. */
  88081. name,
  88082. /**
  88083. * Defines the location of the image to load
  88084. */
  88085. url) {
  88086. var _this = _super.call(this, name) || this;
  88087. _this.name = name;
  88088. _this.url = url;
  88089. return _this;
  88090. }
  88091. /**
  88092. * Execute the current task
  88093. * @param scene defines the scene where you want your assets to be loaded
  88094. * @param onSuccess is a callback called when the task is successfully executed
  88095. * @param onError is a callback called if an error occurs
  88096. */
  88097. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88098. var _this = this;
  88099. var img = new Image();
  88100. BABYLON.Tools.SetCorsBehavior(this.url, img);
  88101. img.onload = function () {
  88102. _this.image = img;
  88103. onSuccess();
  88104. };
  88105. img.onerror = function (err) {
  88106. onError("Error loading image", err);
  88107. };
  88108. img.src = this.url;
  88109. };
  88110. return ImageAssetTask;
  88111. }(AbstractAssetTask));
  88112. BABYLON.ImageAssetTask = ImageAssetTask;
  88113. /**
  88114. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  88115. */
  88116. var TextureAssetTask = /** @class */ (function (_super) {
  88117. __extends(TextureAssetTask, _super);
  88118. /**
  88119. * Creates a new TextureAssetTask object
  88120. * @param name defines the name of the task
  88121. * @param url defines the location of the file to load
  88122. * @param noMipmap defines if mipmap should not be generated (default is false)
  88123. * @param invertY defines if texture must be inverted on Y axis (default is false)
  88124. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  88125. */
  88126. function TextureAssetTask(
  88127. /**
  88128. * Defines the name of the task
  88129. */
  88130. name,
  88131. /**
  88132. * Defines the location of the file to load
  88133. */
  88134. url,
  88135. /**
  88136. * Defines if mipmap should not be generated (default is false)
  88137. */
  88138. noMipmap,
  88139. /**
  88140. * Defines if texture must be inverted on Y axis (default is false)
  88141. */
  88142. invertY,
  88143. /**
  88144. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  88145. */
  88146. samplingMode) {
  88147. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88148. var _this = _super.call(this, name) || this;
  88149. _this.name = name;
  88150. _this.url = url;
  88151. _this.noMipmap = noMipmap;
  88152. _this.invertY = invertY;
  88153. _this.samplingMode = samplingMode;
  88154. return _this;
  88155. }
  88156. /**
  88157. * Execute the current task
  88158. * @param scene defines the scene where you want your assets to be loaded
  88159. * @param onSuccess is a callback called when the task is successfully executed
  88160. * @param onError is a callback called if an error occurs
  88161. */
  88162. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88163. var onload = function () {
  88164. onSuccess();
  88165. };
  88166. var onerror = function (message, exception) {
  88167. onError(message, exception);
  88168. };
  88169. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  88170. };
  88171. return TextureAssetTask;
  88172. }(AbstractAssetTask));
  88173. BABYLON.TextureAssetTask = TextureAssetTask;
  88174. /**
  88175. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  88176. */
  88177. var CubeTextureAssetTask = /** @class */ (function (_super) {
  88178. __extends(CubeTextureAssetTask, _super);
  88179. /**
  88180. * Creates a new CubeTextureAssetTask
  88181. * @param name defines the name of the task
  88182. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  88183. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  88184. * @param noMipmap defines if mipmaps should not be generated (default is false)
  88185. * @param files defines the explicit list of files (undefined by default)
  88186. */
  88187. function CubeTextureAssetTask(
  88188. /**
  88189. * Defines the name of the task
  88190. */
  88191. name,
  88192. /**
  88193. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  88194. */
  88195. url,
  88196. /**
  88197. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  88198. */
  88199. extensions,
  88200. /**
  88201. * Defines if mipmaps should not be generated (default is false)
  88202. */
  88203. noMipmap,
  88204. /**
  88205. * Defines the explicit list of files (undefined by default)
  88206. */
  88207. files) {
  88208. var _this = _super.call(this, name) || this;
  88209. _this.name = name;
  88210. _this.url = url;
  88211. _this.extensions = extensions;
  88212. _this.noMipmap = noMipmap;
  88213. _this.files = files;
  88214. return _this;
  88215. }
  88216. /**
  88217. * Execute the current task
  88218. * @param scene defines the scene where you want your assets to be loaded
  88219. * @param onSuccess is a callback called when the task is successfully executed
  88220. * @param onError is a callback called if an error occurs
  88221. */
  88222. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88223. var onload = function () {
  88224. onSuccess();
  88225. };
  88226. var onerror = function (message, exception) {
  88227. onError(message, exception);
  88228. };
  88229. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  88230. };
  88231. return CubeTextureAssetTask;
  88232. }(AbstractAssetTask));
  88233. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  88234. /**
  88235. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  88236. */
  88237. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  88238. __extends(HDRCubeTextureAssetTask, _super);
  88239. /**
  88240. * Creates a new HDRCubeTextureAssetTask object
  88241. * @param name defines the name of the task
  88242. * @param url defines the location of the file to load
  88243. * @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.
  88244. * @param noMipmap defines if mipmaps should not be generated (default is false)
  88245. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  88246. * @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)
  88247. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  88248. */
  88249. function HDRCubeTextureAssetTask(
  88250. /**
  88251. * Defines the name of the task
  88252. */
  88253. name,
  88254. /**
  88255. * Defines the location of the file to load
  88256. */
  88257. url,
  88258. /**
  88259. * 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.
  88260. */
  88261. size,
  88262. /**
  88263. * Defines if mipmaps should not be generated (default is false)
  88264. */
  88265. noMipmap,
  88266. /**
  88267. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  88268. */
  88269. generateHarmonics,
  88270. /**
  88271. * 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)
  88272. */
  88273. useInGammaSpace,
  88274. /**
  88275. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  88276. */
  88277. usePMREMGenerator) {
  88278. if (noMipmap === void 0) { noMipmap = false; }
  88279. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88280. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88281. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88282. var _this = _super.call(this, name) || this;
  88283. _this.name = name;
  88284. _this.url = url;
  88285. _this.size = size;
  88286. _this.noMipmap = noMipmap;
  88287. _this.generateHarmonics = generateHarmonics;
  88288. _this.useInGammaSpace = useInGammaSpace;
  88289. _this.usePMREMGenerator = usePMREMGenerator;
  88290. return _this;
  88291. }
  88292. /**
  88293. * Execute the current task
  88294. * @param scene defines the scene where you want your assets to be loaded
  88295. * @param onSuccess is a callback called when the task is successfully executed
  88296. * @param onError is a callback called if an error occurs
  88297. */
  88298. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  88299. var onload = function () {
  88300. onSuccess();
  88301. };
  88302. var onerror = function (message, exception) {
  88303. onError(message, exception);
  88304. };
  88305. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  88306. };
  88307. return HDRCubeTextureAssetTask;
  88308. }(AbstractAssetTask));
  88309. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  88310. /**
  88311. * This class can be used to easily import assets into a scene
  88312. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  88313. */
  88314. var AssetsManager = /** @class */ (function () {
  88315. /**
  88316. * Creates a new AssetsManager
  88317. * @param scene defines the scene to work on
  88318. */
  88319. function AssetsManager(scene) {
  88320. this._isLoading = false;
  88321. this._tasks = new Array();
  88322. this._waitingTasksCount = 0;
  88323. this._totalTasksCount = 0;
  88324. /**
  88325. * Observable called when all tasks are processed
  88326. */
  88327. this.onTaskSuccessObservable = new BABYLON.Observable();
  88328. /**
  88329. * Observable called when a task had an error
  88330. */
  88331. this.onTaskErrorObservable = new BABYLON.Observable();
  88332. /**
  88333. * Observable called when a task is successful
  88334. */
  88335. this.onTasksDoneObservable = new BABYLON.Observable();
  88336. /**
  88337. * Observable called when a task is done (whatever the result is)
  88338. */
  88339. this.onProgressObservable = new BABYLON.Observable();
  88340. /**
  88341. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  88342. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  88343. */
  88344. this.useDefaultLoadingScreen = true;
  88345. this._scene = scene;
  88346. }
  88347. /**
  88348. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  88349. * @param taskName defines the name of the new task
  88350. * @param meshesNames defines the name of meshes to load
  88351. * @param rootUrl defines the root url to use to locate files
  88352. * @param sceneFilename defines the filename of the scene file
  88353. * @returns a new {BABYLON.MeshAssetTask} object
  88354. */
  88355. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  88356. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  88357. this._tasks.push(task);
  88358. return task;
  88359. };
  88360. /**
  88361. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  88362. * @param taskName defines the name of the new task
  88363. * @param url defines the url of the file to load
  88364. * @returns a new {BABYLON.TextFileAssetTask} object
  88365. */
  88366. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  88367. var task = new TextFileAssetTask(taskName, url);
  88368. this._tasks.push(task);
  88369. return task;
  88370. };
  88371. /**
  88372. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  88373. * @param taskName defines the name of the new task
  88374. * @param url defines the url of the file to load
  88375. * @returns a new {BABYLON.BinaryFileAssetTask} object
  88376. */
  88377. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  88378. var task = new BinaryFileAssetTask(taskName, url);
  88379. this._tasks.push(task);
  88380. return task;
  88381. };
  88382. /**
  88383. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  88384. * @param taskName defines the name of the new task
  88385. * @param url defines the url of the file to load
  88386. * @returns a new {BABYLON.ImageAssetTask} object
  88387. */
  88388. AssetsManager.prototype.addImageTask = function (taskName, url) {
  88389. var task = new ImageAssetTask(taskName, url);
  88390. this._tasks.push(task);
  88391. return task;
  88392. };
  88393. /**
  88394. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  88395. * @param taskName defines the name of the new task
  88396. * @param url defines the url of the file to load
  88397. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88398. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  88399. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  88400. * @returns a new {BABYLON.TextureAssetTask} object
  88401. */
  88402. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  88403. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88404. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  88405. this._tasks.push(task);
  88406. return task;
  88407. };
  88408. /**
  88409. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  88410. * @param taskName defines the name of the new task
  88411. * @param url defines the url of the file to load
  88412. * @param extensions defines the extension to use to load the cube map (can be null)
  88413. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88414. * @param files defines the list of files to load (can be null)
  88415. * @returns a new {BABYLON.CubeTextureAssetTask} object
  88416. */
  88417. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  88418. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  88419. this._tasks.push(task);
  88420. return task;
  88421. };
  88422. /**
  88423. *
  88424. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  88425. * @param taskName defines the name of the new task
  88426. * @param url defines the url of the file to load
  88427. * @param size defines the size you want for the cubemap (can be null)
  88428. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88429. * @param generateHarmonics defines if you want to automatically generate (true by default)
  88430. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  88431. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  88432. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  88433. */
  88434. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  88435. if (noMipmap === void 0) { noMipmap = false; }
  88436. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88437. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88438. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88439. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  88440. this._tasks.push(task);
  88441. return task;
  88442. };
  88443. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  88444. var _this = this;
  88445. this._waitingTasksCount--;
  88446. try {
  88447. if (task.taskState === AssetTaskState.DONE) {
  88448. // Let's remove successfull tasks
  88449. BABYLON.Tools.SetImmediate(function () {
  88450. var index = _this._tasks.indexOf(task);
  88451. if (index > -1) {
  88452. _this._tasks.splice(index, 1);
  88453. }
  88454. });
  88455. }
  88456. if (this.onProgress) {
  88457. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  88458. }
  88459. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  88460. }
  88461. catch (e) {
  88462. BABYLON.Tools.Error("Error running progress callbacks.");
  88463. console.log(e);
  88464. }
  88465. if (this._waitingTasksCount === 0) {
  88466. try {
  88467. if (this.onFinish) {
  88468. this.onFinish(this._tasks);
  88469. }
  88470. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88471. }
  88472. catch (e) {
  88473. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  88474. console.log(e);
  88475. }
  88476. this._isLoading = false;
  88477. this._scene.getEngine().hideLoadingUI();
  88478. }
  88479. };
  88480. AssetsManager.prototype._runTask = function (task) {
  88481. var _this = this;
  88482. var done = function () {
  88483. try {
  88484. if (_this.onTaskSuccess) {
  88485. _this.onTaskSuccess(task);
  88486. }
  88487. _this.onTaskSuccessObservable.notifyObservers(task);
  88488. _this._decreaseWaitingTasksCount(task);
  88489. }
  88490. catch (e) {
  88491. error("Error executing task success callbacks", e);
  88492. }
  88493. };
  88494. var error = function (message, exception) {
  88495. task._setErrorObject(message, exception);
  88496. if (_this.onTaskError) {
  88497. _this.onTaskError(task);
  88498. }
  88499. _this.onTaskErrorObservable.notifyObservers(task);
  88500. _this._decreaseWaitingTasksCount(task);
  88501. };
  88502. task.run(this._scene, done, error);
  88503. };
  88504. /**
  88505. * Reset the {BABYLON.AssetsManager} and remove all tasks
  88506. * @return the current instance of the {BABYLON.AssetsManager}
  88507. */
  88508. AssetsManager.prototype.reset = function () {
  88509. this._isLoading = false;
  88510. this._tasks = new Array();
  88511. return this;
  88512. };
  88513. /**
  88514. * Start the loading process
  88515. * @return the current instance of the {BABYLON.AssetsManager}
  88516. */
  88517. AssetsManager.prototype.load = function () {
  88518. if (this._isLoading) {
  88519. return this;
  88520. }
  88521. this._isLoading = true;
  88522. this._waitingTasksCount = this._tasks.length;
  88523. this._totalTasksCount = this._tasks.length;
  88524. if (this._waitingTasksCount === 0) {
  88525. this._isLoading = false;
  88526. if (this.onFinish) {
  88527. this.onFinish(this._tasks);
  88528. }
  88529. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88530. return this;
  88531. }
  88532. if (this.useDefaultLoadingScreen) {
  88533. this._scene.getEngine().displayLoadingUI();
  88534. }
  88535. for (var index = 0; index < this._tasks.length; index++) {
  88536. var task = this._tasks[index];
  88537. this._runTask(task);
  88538. }
  88539. return this;
  88540. };
  88541. return AssetsManager;
  88542. }());
  88543. BABYLON.AssetsManager = AssetsManager;
  88544. })(BABYLON || (BABYLON = {}));
  88545. //# sourceMappingURL=babylon.assetsManager.js.map
  88546. "use strict";
  88547. var BABYLON;
  88548. (function (BABYLON) {
  88549. var serializedGeometries = [];
  88550. var serializeGeometry = function (geometry, serializationGeometries) {
  88551. if (serializedGeometries[geometry.id]) {
  88552. return;
  88553. }
  88554. if (geometry.doNotSerialize) {
  88555. return;
  88556. }
  88557. if (geometry instanceof BABYLON.BoxGeometry) {
  88558. serializationGeometries.boxes.push(geometry.serialize());
  88559. }
  88560. else if (geometry instanceof BABYLON.SphereGeometry) {
  88561. serializationGeometries.spheres.push(geometry.serialize());
  88562. }
  88563. else if (geometry instanceof BABYLON.CylinderGeometry) {
  88564. serializationGeometries.cylinders.push(geometry.serialize());
  88565. }
  88566. else if (geometry instanceof BABYLON.TorusGeometry) {
  88567. serializationGeometries.toruses.push(geometry.serialize());
  88568. }
  88569. else if (geometry instanceof BABYLON.GroundGeometry) {
  88570. serializationGeometries.grounds.push(geometry.serialize());
  88571. }
  88572. else if (geometry instanceof BABYLON.Plane) {
  88573. serializationGeometries.planes.push(geometry.serialize());
  88574. }
  88575. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  88576. serializationGeometries.torusKnots.push(geometry.serialize());
  88577. }
  88578. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  88579. throw new Error("Unknown primitive type");
  88580. }
  88581. else {
  88582. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  88583. }
  88584. serializedGeometries[geometry.id] = true;
  88585. };
  88586. var serializeMesh = function (mesh, serializationScene) {
  88587. var serializationObject = {};
  88588. // Geometry
  88589. var geometry = mesh._geometry;
  88590. if (geometry) {
  88591. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  88592. // 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
  88593. serializeGeometry(geometry, serializationScene.geometries);
  88594. }
  88595. }
  88596. // Custom
  88597. if (mesh.serialize) {
  88598. mesh.serialize(serializationObject);
  88599. }
  88600. return serializationObject;
  88601. };
  88602. var finalizeSingleMesh = function (mesh, serializationObject) {
  88603. //only works if the mesh is already loaded
  88604. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88605. //serialize material
  88606. if (mesh.material) {
  88607. if (mesh.material instanceof BABYLON.StandardMaterial) {
  88608. serializationObject.materials = serializationObject.materials || [];
  88609. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88610. serializationObject.materials.push(mesh.material.serialize());
  88611. }
  88612. }
  88613. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  88614. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  88615. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88616. serializationObject.multiMaterials.push(mesh.material.serialize());
  88617. }
  88618. }
  88619. }
  88620. //serialize geometry
  88621. var geometry = mesh._geometry;
  88622. if (geometry) {
  88623. if (!serializationObject.geometries) {
  88624. serializationObject.geometries = {};
  88625. serializationObject.geometries.boxes = [];
  88626. serializationObject.geometries.spheres = [];
  88627. serializationObject.geometries.cylinders = [];
  88628. serializationObject.geometries.toruses = [];
  88629. serializationObject.geometries.grounds = [];
  88630. serializationObject.geometries.planes = [];
  88631. serializationObject.geometries.torusKnots = [];
  88632. serializationObject.geometries.vertexData = [];
  88633. }
  88634. serializeGeometry(geometry, serializationObject.geometries);
  88635. }
  88636. // Skeletons
  88637. if (mesh.skeleton) {
  88638. serializationObject.skeletons = serializationObject.skeletons || [];
  88639. serializationObject.skeletons.push(mesh.skeleton.serialize());
  88640. }
  88641. //serialize the actual mesh
  88642. serializationObject.meshes = serializationObject.meshes || [];
  88643. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88644. }
  88645. };
  88646. var SceneSerializer = /** @class */ (function () {
  88647. function SceneSerializer() {
  88648. }
  88649. SceneSerializer.ClearCache = function () {
  88650. serializedGeometries = [];
  88651. };
  88652. SceneSerializer.Serialize = function (scene) {
  88653. var serializationObject = {};
  88654. SceneSerializer.ClearCache();
  88655. // Scene
  88656. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  88657. serializationObject.autoClear = scene.autoClear;
  88658. serializationObject.clearColor = scene.clearColor.asArray();
  88659. serializationObject.ambientColor = scene.ambientColor.asArray();
  88660. serializationObject.gravity = scene.gravity.asArray();
  88661. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  88662. serializationObject.workerCollisions = scene.workerCollisions;
  88663. // Fog
  88664. if (scene.fogMode && scene.fogMode !== 0) {
  88665. serializationObject.fogMode = scene.fogMode;
  88666. serializationObject.fogColor = scene.fogColor.asArray();
  88667. serializationObject.fogStart = scene.fogStart;
  88668. serializationObject.fogEnd = scene.fogEnd;
  88669. serializationObject.fogDensity = scene.fogDensity;
  88670. }
  88671. //Physics
  88672. if (scene.isPhysicsEnabled()) {
  88673. var physicEngine = scene.getPhysicsEngine();
  88674. if (physicEngine) {
  88675. serializationObject.physicsEnabled = true;
  88676. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  88677. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  88678. }
  88679. }
  88680. // Metadata
  88681. if (scene.metadata) {
  88682. serializationObject.metadata = scene.metadata;
  88683. }
  88684. // Morph targets
  88685. serializationObject.morphTargetManagers = [];
  88686. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  88687. var abstractMesh = _a[_i];
  88688. var manager = abstractMesh.morphTargetManager;
  88689. if (manager) {
  88690. serializationObject.morphTargetManagers.push(manager.serialize());
  88691. }
  88692. }
  88693. // Lights
  88694. serializationObject.lights = [];
  88695. var index;
  88696. var light;
  88697. for (index = 0; index < scene.lights.length; index++) {
  88698. light = scene.lights[index];
  88699. if (!light.doNotSerialize) {
  88700. serializationObject.lights.push(light.serialize());
  88701. }
  88702. }
  88703. // Cameras
  88704. serializationObject.cameras = [];
  88705. for (index = 0; index < scene.cameras.length; index++) {
  88706. var camera = scene.cameras[index];
  88707. if (!camera.doNotSerialize) {
  88708. serializationObject.cameras.push(camera.serialize());
  88709. }
  88710. }
  88711. if (scene.activeCamera) {
  88712. serializationObject.activeCameraID = scene.activeCamera.id;
  88713. }
  88714. // Animations
  88715. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  88716. // Materials
  88717. serializationObject.materials = [];
  88718. serializationObject.multiMaterials = [];
  88719. var material;
  88720. for (index = 0; index < scene.materials.length; index++) {
  88721. material = scene.materials[index];
  88722. if (!material.doNotSerialize) {
  88723. serializationObject.materials.push(material.serialize());
  88724. }
  88725. }
  88726. // MultiMaterials
  88727. serializationObject.multiMaterials = [];
  88728. for (index = 0; index < scene.multiMaterials.length; index++) {
  88729. var multiMaterial = scene.multiMaterials[index];
  88730. serializationObject.multiMaterials.push(multiMaterial.serialize());
  88731. }
  88732. // Environment texture
  88733. if (scene.environmentTexture) {
  88734. serializationObject.environmentTexture = scene.environmentTexture.name;
  88735. }
  88736. // Skeletons
  88737. serializationObject.skeletons = [];
  88738. for (index = 0; index < scene.skeletons.length; index++) {
  88739. var skeleton = scene.skeletons[index];
  88740. if (!skeleton.doNotSerialize) {
  88741. serializationObject.skeletons.push(skeleton.serialize());
  88742. }
  88743. }
  88744. // Transform nodes
  88745. serializationObject.transformNodes = [];
  88746. for (index = 0; index < scene.transformNodes.length; index++) {
  88747. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  88748. }
  88749. // Geometries
  88750. serializationObject.geometries = {};
  88751. serializationObject.geometries.boxes = [];
  88752. serializationObject.geometries.spheres = [];
  88753. serializationObject.geometries.cylinders = [];
  88754. serializationObject.geometries.toruses = [];
  88755. serializationObject.geometries.grounds = [];
  88756. serializationObject.geometries.planes = [];
  88757. serializationObject.geometries.torusKnots = [];
  88758. serializationObject.geometries.vertexData = [];
  88759. serializedGeometries = [];
  88760. var geometries = scene.getGeometries();
  88761. for (index = 0; index < geometries.length; index++) {
  88762. var geometry = geometries[index];
  88763. if (geometry.isReady()) {
  88764. serializeGeometry(geometry, serializationObject.geometries);
  88765. }
  88766. }
  88767. // Meshes
  88768. serializationObject.meshes = [];
  88769. for (index = 0; index < scene.meshes.length; index++) {
  88770. var abstractMesh = scene.meshes[index];
  88771. if (abstractMesh instanceof BABYLON.Mesh) {
  88772. var mesh = abstractMesh;
  88773. if (!mesh.doNotSerialize) {
  88774. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88775. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88776. }
  88777. }
  88778. }
  88779. }
  88780. // Particles Systems
  88781. serializationObject.particleSystems = [];
  88782. for (index = 0; index < scene.particleSystems.length; index++) {
  88783. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  88784. }
  88785. // Lens flares
  88786. serializationObject.lensFlareSystems = [];
  88787. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  88788. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  88789. }
  88790. // Shadows
  88791. serializationObject.shadowGenerators = [];
  88792. for (index = 0; index < scene.lights.length; index++) {
  88793. light = scene.lights[index];
  88794. var shadowGenerator = light.getShadowGenerator();
  88795. if (shadowGenerator) {
  88796. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  88797. }
  88798. }
  88799. // Action Manager
  88800. if (scene.actionManager) {
  88801. serializationObject.actions = scene.actionManager.serialize("scene");
  88802. }
  88803. // Audio
  88804. serializationObject.sounds = [];
  88805. for (index = 0; index < scene.soundTracks.length; index++) {
  88806. var soundtrack = scene.soundTracks[index];
  88807. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  88808. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  88809. }
  88810. }
  88811. return serializationObject;
  88812. };
  88813. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  88814. if (withParents === void 0) { withParents = false; }
  88815. if (withChildren === void 0) { withChildren = false; }
  88816. var serializationObject = {};
  88817. SceneSerializer.ClearCache();
  88818. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  88819. if (withParents || withChildren) {
  88820. //deliberate for loop! not for each, appended should be processed as well.
  88821. for (var i = 0; i < toSerialize.length; ++i) {
  88822. if (withChildren) {
  88823. toSerialize[i].getDescendants().forEach(function (node) {
  88824. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  88825. toSerialize.push(node);
  88826. }
  88827. });
  88828. }
  88829. //make sure the array doesn't contain the object already
  88830. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  88831. toSerialize.push(toSerialize[i].parent);
  88832. }
  88833. }
  88834. }
  88835. toSerialize.forEach(function (mesh) {
  88836. finalizeSingleMesh(mesh, serializationObject);
  88837. });
  88838. return serializationObject;
  88839. };
  88840. return SceneSerializer;
  88841. }());
  88842. BABYLON.SceneSerializer = SceneSerializer;
  88843. })(BABYLON || (BABYLON = {}));
  88844. //# sourceMappingURL=babylon.sceneSerializer.js.map
  88845. "use strict";
  88846. var BABYLON;
  88847. (function (BABYLON) {
  88848. var ReflectionProbe = /** @class */ (function () {
  88849. function ReflectionProbe(name, size, scene, generateMipMaps) {
  88850. if (generateMipMaps === void 0) { generateMipMaps = true; }
  88851. var _this = this;
  88852. this.name = name;
  88853. this._viewMatrix = BABYLON.Matrix.Identity();
  88854. this._target = BABYLON.Vector3.Zero();
  88855. this._add = BABYLON.Vector3.Zero();
  88856. this._invertYAxis = false;
  88857. this.position = BABYLON.Vector3.Zero();
  88858. this._scene = scene;
  88859. this._scene.reflectionProbes.push(this);
  88860. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  88861. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  88862. switch (faceIndex) {
  88863. case 0:
  88864. _this._add.copyFromFloats(1, 0, 0);
  88865. break;
  88866. case 1:
  88867. _this._add.copyFromFloats(-1, 0, 0);
  88868. break;
  88869. case 2:
  88870. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  88871. break;
  88872. case 3:
  88873. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  88874. break;
  88875. case 4:
  88876. _this._add.copyFromFloats(0, 0, 1);
  88877. break;
  88878. case 5:
  88879. _this._add.copyFromFloats(0, 0, -1);
  88880. break;
  88881. }
  88882. if (_this._attachedMesh) {
  88883. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  88884. }
  88885. _this.position.addToRef(_this._add, _this._target);
  88886. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  88887. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  88888. scene._forcedViewPosition = _this.position;
  88889. });
  88890. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  88891. scene._forcedViewPosition = null;
  88892. scene.updateTransformMatrix(true);
  88893. });
  88894. if (scene.activeCamera) {
  88895. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  88896. }
  88897. }
  88898. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  88899. get: function () {
  88900. return this._renderTargetTexture.samples;
  88901. },
  88902. set: function (value) {
  88903. this._renderTargetTexture.samples = value;
  88904. },
  88905. enumerable: true,
  88906. configurable: true
  88907. });
  88908. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  88909. get: function () {
  88910. return this._renderTargetTexture.refreshRate;
  88911. },
  88912. set: function (value) {
  88913. this._renderTargetTexture.refreshRate = value;
  88914. },
  88915. enumerable: true,
  88916. configurable: true
  88917. });
  88918. ReflectionProbe.prototype.getScene = function () {
  88919. return this._scene;
  88920. };
  88921. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  88922. get: function () {
  88923. return this._renderTargetTexture;
  88924. },
  88925. enumerable: true,
  88926. configurable: true
  88927. });
  88928. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  88929. get: function () {
  88930. return this._renderTargetTexture.renderList;
  88931. },
  88932. enumerable: true,
  88933. configurable: true
  88934. });
  88935. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  88936. this._attachedMesh = mesh;
  88937. };
  88938. /**
  88939. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  88940. *
  88941. * @param renderingGroupId The rendering group id corresponding to its index
  88942. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  88943. */
  88944. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  88945. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  88946. };
  88947. ReflectionProbe.prototype.dispose = function () {
  88948. var index = this._scene.reflectionProbes.indexOf(this);
  88949. if (index !== -1) {
  88950. // Remove from the scene if found
  88951. this._scene.reflectionProbes.splice(index, 1);
  88952. }
  88953. if (this._renderTargetTexture) {
  88954. this._renderTargetTexture.dispose();
  88955. this._renderTargetTexture = null;
  88956. }
  88957. };
  88958. return ReflectionProbe;
  88959. }());
  88960. BABYLON.ReflectionProbe = ReflectionProbe;
  88961. })(BABYLON || (BABYLON = {}));
  88962. //# sourceMappingURL=babylon.reflectionProbe.js.map
  88963. "use strict";
  88964. var BABYLON;
  88965. (function (BABYLON) {
  88966. var Layer = /** @class */ (function () {
  88967. function Layer(name, imgUrl, scene, isBackground, color) {
  88968. this.name = name;
  88969. this.scale = new BABYLON.Vector2(1, 1);
  88970. this.offset = new BABYLON.Vector2(0, 0);
  88971. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  88972. this.layerMask = 0x0FFFFFFF;
  88973. this._vertexBuffers = {};
  88974. // Events
  88975. /**
  88976. * An event triggered when the layer is disposed.
  88977. * @type {BABYLON.Observable}
  88978. */
  88979. this.onDisposeObservable = new BABYLON.Observable();
  88980. /**
  88981. * An event triggered before rendering the scene
  88982. * @type {BABYLON.Observable}
  88983. */
  88984. this.onBeforeRenderObservable = new BABYLON.Observable();
  88985. /**
  88986. * An event triggered after rendering the scene
  88987. * @type {BABYLON.Observable}
  88988. */
  88989. this.onAfterRenderObservable = new BABYLON.Observable();
  88990. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  88991. this.isBackground = isBackground === undefined ? true : isBackground;
  88992. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  88993. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  88994. this._scene.layers.push(this);
  88995. var engine = this._scene.getEngine();
  88996. // VBO
  88997. var vertices = [];
  88998. vertices.push(1, 1);
  88999. vertices.push(-1, 1);
  89000. vertices.push(-1, -1);
  89001. vertices.push(1, -1);
  89002. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  89003. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  89004. this._createIndexBuffer();
  89005. // Effects
  89006. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  89007. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  89008. }
  89009. Object.defineProperty(Layer.prototype, "onDispose", {
  89010. set: function (callback) {
  89011. if (this._onDisposeObserver) {
  89012. this.onDisposeObservable.remove(this._onDisposeObserver);
  89013. }
  89014. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  89015. },
  89016. enumerable: true,
  89017. configurable: true
  89018. });
  89019. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  89020. set: function (callback) {
  89021. if (this._onBeforeRenderObserver) {
  89022. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  89023. }
  89024. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  89025. },
  89026. enumerable: true,
  89027. configurable: true
  89028. });
  89029. Object.defineProperty(Layer.prototype, "onAfterRender", {
  89030. set: function (callback) {
  89031. if (this._onAfterRenderObserver) {
  89032. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  89033. }
  89034. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  89035. },
  89036. enumerable: true,
  89037. configurable: true
  89038. });
  89039. Layer.prototype._createIndexBuffer = function () {
  89040. var engine = this._scene.getEngine();
  89041. // Indices
  89042. var indices = [];
  89043. indices.push(0);
  89044. indices.push(1);
  89045. indices.push(2);
  89046. indices.push(0);
  89047. indices.push(2);
  89048. indices.push(3);
  89049. this._indexBuffer = engine.createIndexBuffer(indices);
  89050. };
  89051. Layer.prototype._rebuild = function () {
  89052. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89053. if (vb) {
  89054. vb._rebuild();
  89055. }
  89056. this._createIndexBuffer();
  89057. };
  89058. Layer.prototype.render = function () {
  89059. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  89060. // Check
  89061. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  89062. return;
  89063. var engine = this._scene.getEngine();
  89064. this.onBeforeRenderObservable.notifyObservers(this);
  89065. // Render
  89066. engine.enableEffect(currentEffect);
  89067. engine.setState(false);
  89068. // Texture
  89069. currentEffect.setTexture("textureSampler", this.texture);
  89070. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  89071. // Color
  89072. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  89073. // Scale / offset
  89074. currentEffect.setVector2("offset", this.offset);
  89075. currentEffect.setVector2("scale", this.scale);
  89076. // VBOs
  89077. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  89078. // Draw order
  89079. if (!this.alphaTest) {
  89080. engine.setAlphaMode(this.alphaBlendingMode);
  89081. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89082. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  89083. }
  89084. else {
  89085. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89086. }
  89087. this.onAfterRenderObservable.notifyObservers(this);
  89088. };
  89089. Layer.prototype.dispose = function () {
  89090. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89091. if (vertexBuffer) {
  89092. vertexBuffer.dispose();
  89093. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  89094. }
  89095. if (this._indexBuffer) {
  89096. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  89097. this._indexBuffer = null;
  89098. }
  89099. if (this.texture) {
  89100. this.texture.dispose();
  89101. this.texture = null;
  89102. }
  89103. // Remove from scene
  89104. var index = this._scene.layers.indexOf(this);
  89105. this._scene.layers.splice(index, 1);
  89106. // Callback
  89107. this.onDisposeObservable.notifyObservers(this);
  89108. this.onDisposeObservable.clear();
  89109. this.onAfterRenderObservable.clear();
  89110. this.onBeforeRenderObservable.clear();
  89111. };
  89112. return Layer;
  89113. }());
  89114. BABYLON.Layer = Layer;
  89115. })(BABYLON || (BABYLON = {}));
  89116. //# sourceMappingURL=babylon.layer.js.map
  89117. "use strict";
  89118. var BABYLON;
  89119. (function (BABYLON) {
  89120. var TextureTools = /** @class */ (function () {
  89121. function TextureTools() {
  89122. }
  89123. /**
  89124. * Uses the GPU to create a copy texture rescaled at a given size
  89125. * @param texture Texture to copy from
  89126. * @param width Desired width
  89127. * @param height Desired height
  89128. * @return Generated texture
  89129. */
  89130. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  89131. if (useBilinearMode === void 0) { useBilinearMode = true; }
  89132. var scene = texture.getScene();
  89133. var engine = scene.getEngine();
  89134. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  89135. rtt.wrapU = texture.wrapU;
  89136. rtt.wrapV = texture.wrapV;
  89137. rtt.uOffset = texture.uOffset;
  89138. rtt.vOffset = texture.vOffset;
  89139. rtt.uScale = texture.uScale;
  89140. rtt.vScale = texture.vScale;
  89141. rtt.uAng = texture.uAng;
  89142. rtt.vAng = texture.vAng;
  89143. rtt.wAng = texture.wAng;
  89144. rtt.coordinatesIndex = texture.coordinatesIndex;
  89145. rtt.level = texture.level;
  89146. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  89147. rtt._texture.isReady = false;
  89148. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89149. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89150. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89151. passPostProcess.getEffect().executeWhenCompiled(function () {
  89152. passPostProcess.onApply = function (effect) {
  89153. effect.setTexture("textureSampler", texture);
  89154. };
  89155. var internalTexture = rtt.getInternalTexture();
  89156. if (internalTexture) {
  89157. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  89158. engine.unBindFramebuffer(internalTexture);
  89159. rtt.disposeFramebufferObjects();
  89160. passPostProcess.dispose();
  89161. internalTexture.isReady = true;
  89162. }
  89163. });
  89164. return rtt;
  89165. };
  89166. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  89167. if (!scene._environmentBRDFTexture) {
  89168. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89169. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89170. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89171. scene._environmentBRDFTexture = texture;
  89172. }
  89173. return scene._environmentBRDFTexture;
  89174. };
  89175. 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=";
  89176. return TextureTools;
  89177. }());
  89178. BABYLON.TextureTools = TextureTools;
  89179. })(BABYLON || (BABYLON = {}));
  89180. //# sourceMappingURL=babylon.textureTools.js.map
  89181. "use strict";
  89182. var BABYLON;
  89183. (function (BABYLON) {
  89184. var FramingBehavior = /** @class */ (function () {
  89185. function FramingBehavior() {
  89186. this._mode = FramingBehavior.FitFrustumSidesMode;
  89187. this._radiusScale = 1.0;
  89188. this._positionScale = 0.5;
  89189. this._defaultElevation = 0.3;
  89190. this._elevationReturnTime = 1500;
  89191. this._elevationReturnWaitTime = 1000;
  89192. this._zoomStopsAnimation = false;
  89193. this._framingTime = 1500;
  89194. this._isPointerDown = false;
  89195. this._lastInteractionTime = -Infinity;
  89196. // Framing control
  89197. this._animatables = new Array();
  89198. this._betaIsAnimating = false;
  89199. }
  89200. Object.defineProperty(FramingBehavior.prototype, "name", {
  89201. get: function () {
  89202. return "Framing";
  89203. },
  89204. enumerable: true,
  89205. configurable: true
  89206. });
  89207. Object.defineProperty(FramingBehavior.prototype, "mode", {
  89208. /**
  89209. * Gets current mode used by the behavior.
  89210. */
  89211. get: function () {
  89212. return this._mode;
  89213. },
  89214. /**
  89215. * Sets the current mode used by the behavior
  89216. */
  89217. set: function (mode) {
  89218. this._mode = mode;
  89219. },
  89220. enumerable: true,
  89221. configurable: true
  89222. });
  89223. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  89224. /**
  89225. * Gets the scale applied to the radius
  89226. */
  89227. get: function () {
  89228. return this._radiusScale;
  89229. },
  89230. /**
  89231. * Sets the scale applied to the radius (1 by default)
  89232. */
  89233. set: function (radius) {
  89234. this._radiusScale = radius;
  89235. },
  89236. enumerable: true,
  89237. configurable: true
  89238. });
  89239. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  89240. /**
  89241. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  89242. */
  89243. get: function () {
  89244. return this._positionScale;
  89245. },
  89246. /**
  89247. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  89248. */
  89249. set: function (scale) {
  89250. this._positionScale = scale;
  89251. },
  89252. enumerable: true,
  89253. configurable: true
  89254. });
  89255. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  89256. /**
  89257. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  89258. * behaviour is triggered, in radians.
  89259. */
  89260. get: function () {
  89261. return this._defaultElevation;
  89262. },
  89263. /**
  89264. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  89265. * behaviour is triggered, in radians.
  89266. */
  89267. set: function (elevation) {
  89268. this._defaultElevation = elevation;
  89269. },
  89270. enumerable: true,
  89271. configurable: true
  89272. });
  89273. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  89274. /**
  89275. * Gets the time (in milliseconds) taken to return to the default beta position.
  89276. * Negative value indicates camera should not return to default.
  89277. */
  89278. get: function () {
  89279. return this._elevationReturnTime;
  89280. },
  89281. /**
  89282. * Sets the time (in milliseconds) taken to return to the default beta position.
  89283. * Negative value indicates camera should not return to default.
  89284. */
  89285. set: function (speed) {
  89286. this._elevationReturnTime = speed;
  89287. },
  89288. enumerable: true,
  89289. configurable: true
  89290. });
  89291. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  89292. /**
  89293. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  89294. */
  89295. get: function () {
  89296. return this._elevationReturnWaitTime;
  89297. },
  89298. /**
  89299. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  89300. */
  89301. set: function (time) {
  89302. this._elevationReturnWaitTime = time;
  89303. },
  89304. enumerable: true,
  89305. configurable: true
  89306. });
  89307. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  89308. /**
  89309. * Gets the flag that indicates if user zooming should stop animation.
  89310. */
  89311. get: function () {
  89312. return this._zoomStopsAnimation;
  89313. },
  89314. /**
  89315. * Sets the flag that indicates if user zooming should stop animation.
  89316. */
  89317. set: function (flag) {
  89318. this._zoomStopsAnimation = flag;
  89319. },
  89320. enumerable: true,
  89321. configurable: true
  89322. });
  89323. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  89324. /**
  89325. * Gets the transition time when framing the mesh, in milliseconds
  89326. */
  89327. get: function () {
  89328. return this._framingTime;
  89329. },
  89330. /**
  89331. * Sets the transition time when framing the mesh, in milliseconds
  89332. */
  89333. set: function (time) {
  89334. this._framingTime = time;
  89335. },
  89336. enumerable: true,
  89337. configurable: true
  89338. });
  89339. FramingBehavior.prototype.init = function () {
  89340. // Do notihng
  89341. };
  89342. FramingBehavior.prototype.attach = function (camera) {
  89343. var _this = this;
  89344. this._attachedCamera = camera;
  89345. var scene = this._attachedCamera.getScene();
  89346. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  89347. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89348. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89349. _this._isPointerDown = true;
  89350. return;
  89351. }
  89352. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89353. _this._isPointerDown = false;
  89354. }
  89355. });
  89356. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89357. if (mesh) {
  89358. _this.zoomOnMesh(mesh);
  89359. }
  89360. });
  89361. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89362. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89363. _this._applyUserInteraction();
  89364. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  89365. // back to the default position after a given timeout
  89366. _this._maintainCameraAboveGround();
  89367. });
  89368. };
  89369. FramingBehavior.prototype.detach = function () {
  89370. if (!this._attachedCamera) {
  89371. return;
  89372. }
  89373. var scene = this._attachedCamera.getScene();
  89374. if (this._onPrePointerObservableObserver) {
  89375. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89376. }
  89377. if (this._onAfterCheckInputsObserver) {
  89378. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89379. }
  89380. if (this._onMeshTargetChangedObserver) {
  89381. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89382. }
  89383. this._attachedCamera = null;
  89384. };
  89385. /**
  89386. * Targets the given mesh and updates zoom level accordingly.
  89387. * @param mesh The mesh to target.
  89388. * @param radius Optional. If a cached radius position already exists, overrides default.
  89389. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89390. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89391. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89392. */
  89393. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89394. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89395. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89396. mesh.computeWorldMatrix(true);
  89397. var boundingBox = mesh.getBoundingInfo().boundingBox;
  89398. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  89399. };
  89400. /**
  89401. * Targets the given mesh with its children and updates zoom level accordingly.
  89402. * @param mesh The mesh to target.
  89403. * @param radius Optional. If a cached radius position already exists, overrides default.
  89404. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89405. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89406. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89407. */
  89408. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89409. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89410. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89411. mesh.computeWorldMatrix(true);
  89412. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  89413. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  89414. };
  89415. /**
  89416. * Targets the given meshes with their children and updates zoom level accordingly.
  89417. * @param meshes The mesh to target.
  89418. * @param radius Optional. If a cached radius position already exists, overrides default.
  89419. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89420. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89421. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89422. */
  89423. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  89424. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89425. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89426. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  89427. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  89428. for (var i = 0; i < meshes.length; i++) {
  89429. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  89430. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  89431. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  89432. }
  89433. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  89434. };
  89435. /**
  89436. * Targets the given mesh and updates zoom level accordingly.
  89437. * @param mesh The mesh to target.
  89438. * @param radius Optional. If a cached radius position already exists, overrides default.
  89439. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89440. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89441. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89442. */
  89443. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  89444. var _this = this;
  89445. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89446. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89447. var zoomTarget;
  89448. if (!this._attachedCamera) {
  89449. return;
  89450. }
  89451. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  89452. var bottom = minimumWorld.y;
  89453. var top = maximumWorld.y;
  89454. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  89455. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  89456. if (focusOnOriginXZ) {
  89457. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  89458. }
  89459. else {
  89460. var centerWorld = minimumWorld.add(radiusWorld);
  89461. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  89462. }
  89463. if (!this._vectorTransition) {
  89464. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  89465. }
  89466. this._betaIsAnimating = true;
  89467. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  89468. if (animatable) {
  89469. this._animatables.push(animatable);
  89470. }
  89471. // sets the radius and lower radius bounds
  89472. // Small delta ensures camera is not always at lower zoom limit.
  89473. var radius = 0;
  89474. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  89475. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89476. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  89477. radius = position;
  89478. }
  89479. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89480. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89481. if (this._attachedCamera.lowerRadiusLimit === null) {
  89482. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  89483. }
  89484. }
  89485. // Set sensibilities
  89486. var extend = maximumWorld.subtract(minimumWorld).length();
  89487. this._attachedCamera.panningSensibility = 5000 / extend;
  89488. this._attachedCamera.wheelPrecision = 100 / radius;
  89489. // transition to new radius
  89490. if (!this._radiusTransition) {
  89491. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89492. }
  89493. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  89494. _this.stopAllAnimations();
  89495. if (onAnimationEnd) {
  89496. onAnimationEnd();
  89497. }
  89498. if (_this._attachedCamera) {
  89499. _this._attachedCamera.storeState();
  89500. }
  89501. });
  89502. if (animatable) {
  89503. this._animatables.push(animatable);
  89504. }
  89505. };
  89506. /**
  89507. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  89508. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  89509. * frustum width.
  89510. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  89511. * to fully enclose the mesh in the viewing frustum.
  89512. */
  89513. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  89514. var size = maximumWorld.subtract(minimumWorld);
  89515. var boxVectorGlobalDiagonal = size.length();
  89516. var frustumSlope = this._getFrustumSlope();
  89517. // Formula for setting distance
  89518. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  89519. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  89520. // Horizon distance
  89521. var radius = radiusWithoutFraming * this._radiusScale;
  89522. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  89523. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  89524. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  89525. var camera = this._attachedCamera;
  89526. if (!camera) {
  89527. return 0;
  89528. }
  89529. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89530. // Don't exceed the requested limit
  89531. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  89532. }
  89533. // Don't exceed the upper radius limit
  89534. if (camera.upperRadiusLimit) {
  89535. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  89536. }
  89537. return distance;
  89538. };
  89539. /**
  89540. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  89541. * is automatically returned to its default position (expected to be above ground plane).
  89542. */
  89543. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  89544. var _this = this;
  89545. if (this._elevationReturnTime < 0) {
  89546. return;
  89547. }
  89548. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  89549. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  89550. var limitBeta = Math.PI * 0.5;
  89551. // Bring the camera back up if below the ground plane
  89552. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  89553. this._betaIsAnimating = true;
  89554. //Transition to new position
  89555. this.stopAllAnimations();
  89556. if (!this._betaTransition) {
  89557. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89558. }
  89559. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  89560. _this._clearAnimationLocks();
  89561. _this.stopAllAnimations();
  89562. });
  89563. if (animatabe) {
  89564. this._animatables.push(animatabe);
  89565. }
  89566. }
  89567. };
  89568. /**
  89569. * Returns the frustum slope based on the canvas ratio and camera FOV
  89570. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  89571. */
  89572. FramingBehavior.prototype._getFrustumSlope = function () {
  89573. // Calculate the viewport ratio
  89574. // Aspect Ratio is Height/Width.
  89575. var camera = this._attachedCamera;
  89576. if (!camera) {
  89577. return BABYLON.Vector2.Zero();
  89578. }
  89579. var engine = camera.getScene().getEngine();
  89580. var aspectRatio = engine.getAspectRatio(camera);
  89581. // Camera FOV is the vertical field of view (top-bottom) in radians.
  89582. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  89583. var frustumSlopeY = Math.tan(camera.fov / 2);
  89584. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  89585. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  89586. // along the forward vector.
  89587. var frustumSlopeX = frustumSlopeY * aspectRatio;
  89588. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  89589. };
  89590. /**
  89591. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  89592. */
  89593. FramingBehavior.prototype._clearAnimationLocks = function () {
  89594. this._betaIsAnimating = false;
  89595. };
  89596. /**
  89597. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89598. */
  89599. FramingBehavior.prototype._applyUserInteraction = function () {
  89600. if (this.isUserIsMoving) {
  89601. this._lastInteractionTime = BABYLON.Tools.Now;
  89602. this.stopAllAnimations();
  89603. this._clearAnimationLocks();
  89604. }
  89605. };
  89606. /**
  89607. * Stops and removes all animations that have been applied to the camera
  89608. */
  89609. FramingBehavior.prototype.stopAllAnimations = function () {
  89610. if (this._attachedCamera) {
  89611. this._attachedCamera.animations = [];
  89612. }
  89613. while (this._animatables.length) {
  89614. if (this._animatables[0]) {
  89615. this._animatables[0].onAnimationEnd = null;
  89616. this._animatables[0].stop();
  89617. }
  89618. this._animatables.shift();
  89619. }
  89620. };
  89621. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  89622. /**
  89623. * Gets a value indicating if the user is moving the camera
  89624. */
  89625. get: function () {
  89626. if (!this._attachedCamera) {
  89627. return false;
  89628. }
  89629. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89630. this._attachedCamera.inertialBetaOffset !== 0 ||
  89631. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89632. this._attachedCamera.inertialPanningX !== 0 ||
  89633. this._attachedCamera.inertialPanningY !== 0 ||
  89634. this._isPointerDown;
  89635. },
  89636. enumerable: true,
  89637. configurable: true
  89638. });
  89639. /**
  89640. * The easing function used by animations
  89641. */
  89642. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  89643. /**
  89644. * The easing mode used by animations
  89645. */
  89646. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  89647. // Statics
  89648. /**
  89649. * The camera can move all the way towards the mesh.
  89650. */
  89651. FramingBehavior.IgnoreBoundsSizeMode = 0;
  89652. /**
  89653. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  89654. */
  89655. FramingBehavior.FitFrustumSidesMode = 1;
  89656. return FramingBehavior;
  89657. }());
  89658. BABYLON.FramingBehavior = FramingBehavior;
  89659. })(BABYLON || (BABYLON = {}));
  89660. //# sourceMappingURL=babylon.framingBehavior.js.map
  89661. "use strict";
  89662. var BABYLON;
  89663. (function (BABYLON) {
  89664. /**
  89665. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  89666. */
  89667. var BouncingBehavior = /** @class */ (function () {
  89668. function BouncingBehavior() {
  89669. /**
  89670. * The duration of the animation, in milliseconds
  89671. */
  89672. this.transitionDuration = 450;
  89673. /**
  89674. * Length of the distance animated by the transition when lower radius is reached
  89675. */
  89676. this.lowerRadiusTransitionRange = 2;
  89677. /**
  89678. * Length of the distance animated by the transition when upper radius is reached
  89679. */
  89680. this.upperRadiusTransitionRange = -2;
  89681. this._autoTransitionRange = false;
  89682. // Animations
  89683. this._radiusIsAnimating = false;
  89684. this._radiusBounceTransition = null;
  89685. this._animatables = new Array();
  89686. }
  89687. Object.defineProperty(BouncingBehavior.prototype, "name", {
  89688. get: function () {
  89689. return "Bouncing";
  89690. },
  89691. enumerable: true,
  89692. configurable: true
  89693. });
  89694. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  89695. /**
  89696. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89697. */
  89698. get: function () {
  89699. return this._autoTransitionRange;
  89700. },
  89701. /**
  89702. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89703. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  89704. */
  89705. set: function (value) {
  89706. var _this = this;
  89707. if (this._autoTransitionRange === value) {
  89708. return;
  89709. }
  89710. this._autoTransitionRange = value;
  89711. var camera = this._attachedCamera;
  89712. if (!camera) {
  89713. return;
  89714. }
  89715. if (value) {
  89716. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89717. if (!mesh) {
  89718. return;
  89719. }
  89720. mesh.computeWorldMatrix(true);
  89721. var diagonal = mesh.getBoundingInfo().diagonalLength;
  89722. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  89723. _this.upperRadiusTransitionRange = diagonal * 0.05;
  89724. });
  89725. }
  89726. else if (this._onMeshTargetChangedObserver) {
  89727. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89728. }
  89729. },
  89730. enumerable: true,
  89731. configurable: true
  89732. });
  89733. BouncingBehavior.prototype.init = function () {
  89734. // Do notihng
  89735. };
  89736. BouncingBehavior.prototype.attach = function (camera) {
  89737. var _this = this;
  89738. this._attachedCamera = camera;
  89739. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89740. if (!_this._attachedCamera) {
  89741. return;
  89742. }
  89743. // Add the bounce animation to the lower radius limit
  89744. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  89745. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  89746. }
  89747. // Add the bounce animation to the upper radius limit
  89748. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  89749. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  89750. }
  89751. });
  89752. };
  89753. BouncingBehavior.prototype.detach = function () {
  89754. if (!this._attachedCamera) {
  89755. return;
  89756. }
  89757. if (this._onAfterCheckInputsObserver) {
  89758. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89759. }
  89760. if (this._onMeshTargetChangedObserver) {
  89761. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89762. }
  89763. this._attachedCamera = null;
  89764. };
  89765. /**
  89766. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  89767. * @param radiusLimit The limit to check against.
  89768. * @return Bool to indicate if at limit.
  89769. */
  89770. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  89771. if (!this._attachedCamera) {
  89772. return false;
  89773. }
  89774. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  89775. return true;
  89776. }
  89777. return false;
  89778. };
  89779. /**
  89780. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  89781. * @param radiusDelta The delta by which to animate to. Can be negative.
  89782. */
  89783. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  89784. var _this = this;
  89785. if (!this._attachedCamera) {
  89786. return;
  89787. }
  89788. if (!this._radiusBounceTransition) {
  89789. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  89790. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  89791. }
  89792. // Prevent zoom until bounce has completed
  89793. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  89794. this._attachedCamera.wheelPrecision = Infinity;
  89795. this._attachedCamera.inertialRadiusOffset = 0;
  89796. // Animate to the radius limit
  89797. this.stopAllAnimations();
  89798. this._radiusIsAnimating = true;
  89799. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  89800. if (animatable) {
  89801. this._animatables.push(animatable);
  89802. }
  89803. };
  89804. /**
  89805. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  89806. */
  89807. BouncingBehavior.prototype._clearAnimationLocks = function () {
  89808. this._radiusIsAnimating = false;
  89809. if (this._attachedCamera) {
  89810. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  89811. }
  89812. };
  89813. /**
  89814. * Stops and removes all animations that have been applied to the camera
  89815. */
  89816. BouncingBehavior.prototype.stopAllAnimations = function () {
  89817. if (this._attachedCamera) {
  89818. this._attachedCamera.animations = [];
  89819. }
  89820. while (this._animatables.length) {
  89821. this._animatables[0].onAnimationEnd = null;
  89822. this._animatables[0].stop();
  89823. this._animatables.shift();
  89824. }
  89825. };
  89826. /**
  89827. * The easing function used by animations
  89828. */
  89829. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  89830. /**
  89831. * The easing mode used by animations
  89832. */
  89833. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  89834. return BouncingBehavior;
  89835. }());
  89836. BABYLON.BouncingBehavior = BouncingBehavior;
  89837. })(BABYLON || (BABYLON = {}));
  89838. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  89839. "use strict";
  89840. var BABYLON;
  89841. (function (BABYLON) {
  89842. var AutoRotationBehavior = /** @class */ (function () {
  89843. function AutoRotationBehavior() {
  89844. this._zoomStopsAnimation = false;
  89845. this._idleRotationSpeed = 0.05;
  89846. this._idleRotationWaitTime = 2000;
  89847. this._idleRotationSpinupTime = 2000;
  89848. this._isPointerDown = false;
  89849. this._lastFrameTime = null;
  89850. this._lastInteractionTime = -Infinity;
  89851. this._cameraRotationSpeed = 0;
  89852. this._lastFrameRadius = 0;
  89853. }
  89854. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  89855. get: function () {
  89856. return "AutoRotation";
  89857. },
  89858. enumerable: true,
  89859. configurable: true
  89860. });
  89861. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  89862. /**
  89863. * Gets the flag that indicates if user zooming should stop animation.
  89864. */
  89865. get: function () {
  89866. return this._zoomStopsAnimation;
  89867. },
  89868. /**
  89869. * Sets the flag that indicates if user zooming should stop animation.
  89870. */
  89871. set: function (flag) {
  89872. this._zoomStopsAnimation = flag;
  89873. },
  89874. enumerable: true,
  89875. configurable: true
  89876. });
  89877. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  89878. /**
  89879. * Gets the default speed at which the camera rotates around the model.
  89880. */
  89881. get: function () {
  89882. return this._idleRotationSpeed;
  89883. },
  89884. /**
  89885. * Sets the default speed at which the camera rotates around the model.
  89886. */
  89887. set: function (speed) {
  89888. this._idleRotationSpeed = speed;
  89889. },
  89890. enumerable: true,
  89891. configurable: true
  89892. });
  89893. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  89894. /**
  89895. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  89896. */
  89897. get: function () {
  89898. return this._idleRotationWaitTime;
  89899. },
  89900. /**
  89901. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  89902. */
  89903. set: function (time) {
  89904. this._idleRotationWaitTime = time;
  89905. },
  89906. enumerable: true,
  89907. configurable: true
  89908. });
  89909. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  89910. /**
  89911. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89912. */
  89913. get: function () {
  89914. return this._idleRotationSpinupTime;
  89915. },
  89916. /**
  89917. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89918. */
  89919. set: function (time) {
  89920. this._idleRotationSpinupTime = time;
  89921. },
  89922. enumerable: true,
  89923. configurable: true
  89924. });
  89925. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  89926. /**
  89927. * Gets a value indicating if the camera is currently rotating because of this behavior
  89928. */
  89929. get: function () {
  89930. return Math.abs(this._cameraRotationSpeed) > 0;
  89931. },
  89932. enumerable: true,
  89933. configurable: true
  89934. });
  89935. AutoRotationBehavior.prototype.init = function () {
  89936. // Do notihng
  89937. };
  89938. AutoRotationBehavior.prototype.attach = function (camera) {
  89939. var _this = this;
  89940. this._attachedCamera = camera;
  89941. var scene = this._attachedCamera.getScene();
  89942. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89943. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89944. _this._isPointerDown = true;
  89945. return;
  89946. }
  89947. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89948. _this._isPointerDown = false;
  89949. }
  89950. });
  89951. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89952. var now = BABYLON.Tools.Now;
  89953. var dt = 0;
  89954. if (_this._lastFrameTime != null) {
  89955. dt = now - _this._lastFrameTime;
  89956. }
  89957. _this._lastFrameTime = now;
  89958. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89959. _this._applyUserInteraction();
  89960. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  89961. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  89962. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  89963. // Step camera rotation by rotation speed
  89964. if (_this._attachedCamera) {
  89965. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  89966. }
  89967. });
  89968. };
  89969. AutoRotationBehavior.prototype.detach = function () {
  89970. if (!this._attachedCamera) {
  89971. return;
  89972. }
  89973. var scene = this._attachedCamera.getScene();
  89974. if (this._onPrePointerObservableObserver) {
  89975. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89976. }
  89977. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89978. this._attachedCamera = null;
  89979. };
  89980. /**
  89981. * Returns true if user is scrolling.
  89982. * @return true if user is scrolling.
  89983. */
  89984. AutoRotationBehavior.prototype._userIsZooming = function () {
  89985. if (!this._attachedCamera) {
  89986. return false;
  89987. }
  89988. return this._attachedCamera.inertialRadiusOffset !== 0;
  89989. };
  89990. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  89991. if (!this._attachedCamera) {
  89992. return false;
  89993. }
  89994. var zoomHasHitLimit = false;
  89995. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  89996. zoomHasHitLimit = true;
  89997. }
  89998. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  89999. this._lastFrameRadius = this._attachedCamera.radius;
  90000. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  90001. };
  90002. /**
  90003. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  90004. */
  90005. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  90006. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  90007. this._lastInteractionTime = BABYLON.Tools.Now;
  90008. }
  90009. };
  90010. // Tools
  90011. AutoRotationBehavior.prototype._userIsMoving = function () {
  90012. if (!this._attachedCamera) {
  90013. return false;
  90014. }
  90015. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  90016. this._attachedCamera.inertialBetaOffset !== 0 ||
  90017. this._attachedCamera.inertialRadiusOffset !== 0 ||
  90018. this._attachedCamera.inertialPanningX !== 0 ||
  90019. this._attachedCamera.inertialPanningY !== 0 ||
  90020. this._isPointerDown;
  90021. };
  90022. return AutoRotationBehavior;
  90023. }());
  90024. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  90025. })(BABYLON || (BABYLON = {}));
  90026. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  90027. "use strict";
  90028. var BABYLON;
  90029. (function (BABYLON) {
  90030. var NullEngineOptions = /** @class */ (function () {
  90031. function NullEngineOptions() {
  90032. this.renderWidth = 512;
  90033. this.renderHeight = 256;
  90034. this.textureSize = 512;
  90035. this.deterministicLockstep = false;
  90036. this.lockstepMaxSteps = 4;
  90037. }
  90038. return NullEngineOptions;
  90039. }());
  90040. BABYLON.NullEngineOptions = NullEngineOptions;
  90041. /**
  90042. * The null engine class provides support for headless version of babylon.js.
  90043. * This can be used in server side scenario or for testing purposes
  90044. */
  90045. var NullEngine = /** @class */ (function (_super) {
  90046. __extends(NullEngine, _super);
  90047. function NullEngine(options) {
  90048. if (options === void 0) { options = new NullEngineOptions(); }
  90049. var _this = _super.call(this, null) || this;
  90050. if (options.deterministicLockstep === undefined) {
  90051. options.deterministicLockstep = false;
  90052. }
  90053. if (options.lockstepMaxSteps === undefined) {
  90054. options.lockstepMaxSteps = 4;
  90055. }
  90056. _this._options = options;
  90057. // Init caps
  90058. // We consider we are on a webgl1 capable device
  90059. _this._caps = new BABYLON.EngineCapabilities();
  90060. _this._caps.maxTexturesImageUnits = 16;
  90061. _this._caps.maxVertexTextureImageUnits = 16;
  90062. _this._caps.maxTextureSize = 512;
  90063. _this._caps.maxCubemapTextureSize = 512;
  90064. _this._caps.maxRenderTextureSize = 512;
  90065. _this._caps.maxVertexAttribs = 16;
  90066. _this._caps.maxVaryingVectors = 16;
  90067. _this._caps.maxFragmentUniformVectors = 16;
  90068. _this._caps.maxVertexUniformVectors = 16;
  90069. // Extensions
  90070. _this._caps.standardDerivatives = false;
  90071. _this._caps.astc = null;
  90072. _this._caps.s3tc = null;
  90073. _this._caps.pvrtc = null;
  90074. _this._caps.etc1 = null;
  90075. _this._caps.etc2 = null;
  90076. _this._caps.textureAnisotropicFilterExtension = null;
  90077. _this._caps.maxAnisotropy = 0;
  90078. _this._caps.uintIndices = false;
  90079. _this._caps.fragmentDepthSupported = false;
  90080. _this._caps.highPrecisionShaderSupported = true;
  90081. _this._caps.colorBufferFloat = false;
  90082. _this._caps.textureFloat = false;
  90083. _this._caps.textureFloatLinearFiltering = false;
  90084. _this._caps.textureFloatRender = false;
  90085. _this._caps.textureHalfFloat = false;
  90086. _this._caps.textureHalfFloatLinearFiltering = false;
  90087. _this._caps.textureHalfFloatRender = false;
  90088. _this._caps.textureLOD = false;
  90089. _this._caps.drawBuffersExtension = false;
  90090. _this._caps.depthTextureExtension = false;
  90091. _this._caps.vertexArrayObject = false;
  90092. _this._caps.instancedArrays = false;
  90093. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  90094. // Wrappers
  90095. if (typeof URL === "undefined") {
  90096. URL = {
  90097. createObjectURL: function () { },
  90098. revokeObjectURL: function () { }
  90099. };
  90100. }
  90101. if (typeof Blob === "undefined") {
  90102. Blob = function () { };
  90103. }
  90104. return _this;
  90105. }
  90106. NullEngine.prototype.isDeterministicLockStep = function () {
  90107. return this._options.deterministicLockstep;
  90108. };
  90109. NullEngine.prototype.getLockstepMaxSteps = function () {
  90110. return this._options.lockstepMaxSteps;
  90111. };
  90112. NullEngine.prototype.getHardwareScalingLevel = function () {
  90113. return 1.0;
  90114. };
  90115. NullEngine.prototype.createVertexBuffer = function (vertices) {
  90116. return {
  90117. capacity: 0,
  90118. references: 1,
  90119. is32Bits: false
  90120. };
  90121. };
  90122. NullEngine.prototype.createIndexBuffer = function (indices) {
  90123. return {
  90124. capacity: 0,
  90125. references: 1,
  90126. is32Bits: false
  90127. };
  90128. };
  90129. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  90130. if (stencil === void 0) { stencil = false; }
  90131. };
  90132. NullEngine.prototype.getRenderWidth = function (useScreen) {
  90133. if (useScreen === void 0) { useScreen = false; }
  90134. if (!useScreen && this._currentRenderTarget) {
  90135. return this._currentRenderTarget.width;
  90136. }
  90137. return this._options.renderWidth;
  90138. };
  90139. NullEngine.prototype.getRenderHeight = function (useScreen) {
  90140. if (useScreen === void 0) { useScreen = false; }
  90141. if (!useScreen && this._currentRenderTarget) {
  90142. return this._currentRenderTarget.height;
  90143. }
  90144. return this._options.renderHeight;
  90145. };
  90146. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  90147. this._cachedViewport = viewport;
  90148. };
  90149. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  90150. return {
  90151. transformFeedback: null,
  90152. __SPECTOR_rebuildProgram: null
  90153. };
  90154. };
  90155. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  90156. return [];
  90157. };
  90158. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  90159. return [];
  90160. };
  90161. NullEngine.prototype.bindSamplers = function (effect) {
  90162. this._currentEffect = null;
  90163. };
  90164. NullEngine.prototype.enableEffect = function (effect) {
  90165. this._currentEffect = effect;
  90166. if (effect.onBind) {
  90167. effect.onBind(effect);
  90168. }
  90169. effect.onBindObservable.notifyObservers(effect);
  90170. };
  90171. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  90172. if (zOffset === void 0) { zOffset = 0; }
  90173. if (reverseSide === void 0) { reverseSide = false; }
  90174. };
  90175. NullEngine.prototype.setIntArray = function (uniform, array) {
  90176. };
  90177. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  90178. };
  90179. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  90180. };
  90181. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  90182. };
  90183. NullEngine.prototype.setFloatArray = function (uniform, array) {
  90184. };
  90185. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  90186. };
  90187. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  90188. };
  90189. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  90190. };
  90191. NullEngine.prototype.setArray = function (uniform, array) {
  90192. };
  90193. NullEngine.prototype.setArray2 = function (uniform, array) {
  90194. };
  90195. NullEngine.prototype.setArray3 = function (uniform, array) {
  90196. };
  90197. NullEngine.prototype.setArray4 = function (uniform, array) {
  90198. };
  90199. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  90200. };
  90201. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  90202. };
  90203. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  90204. };
  90205. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  90206. };
  90207. NullEngine.prototype.setFloat = function (uniform, value) {
  90208. };
  90209. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  90210. };
  90211. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  90212. };
  90213. NullEngine.prototype.setBool = function (uniform, bool) {
  90214. };
  90215. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  90216. };
  90217. NullEngine.prototype.setColor3 = function (uniform, color3) {
  90218. };
  90219. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  90220. };
  90221. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  90222. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  90223. if (this._alphaMode === mode) {
  90224. return;
  90225. }
  90226. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  90227. if (!noDepthWriteChange) {
  90228. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  90229. }
  90230. this._alphaMode = mode;
  90231. };
  90232. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  90233. };
  90234. NullEngine.prototype.wipeCaches = function (bruteForce) {
  90235. if (this.preventCacheWipeBetweenFrames) {
  90236. return;
  90237. }
  90238. this.resetTextureCache();
  90239. this._currentEffect = null;
  90240. if (bruteForce) {
  90241. this._currentProgram = null;
  90242. this._stencilState.reset();
  90243. this._depthCullingState.reset();
  90244. this._alphaState.reset();
  90245. }
  90246. this._cachedVertexBuffers = null;
  90247. this._cachedIndexBuffer = null;
  90248. this._cachedEffectForVertexBuffers = null;
  90249. };
  90250. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  90251. };
  90252. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  90253. };
  90254. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  90255. };
  90256. NullEngine.prototype._createTexture = function () {
  90257. return {};
  90258. };
  90259. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  90260. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  90261. if (onLoad === void 0) { onLoad = null; }
  90262. if (onError === void 0) { onError = null; }
  90263. if (buffer === void 0) { buffer = null; }
  90264. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  90265. var url = String(urlArg);
  90266. texture.url = url;
  90267. texture.generateMipMaps = !noMipmap;
  90268. texture.samplingMode = samplingMode;
  90269. texture.invertY = invertY;
  90270. texture.baseWidth = this._options.textureSize;
  90271. texture.baseHeight = this._options.textureSize;
  90272. texture.width = this._options.textureSize;
  90273. texture.height = this._options.textureSize;
  90274. if (format) {
  90275. texture.format = format;
  90276. }
  90277. texture.isReady = true;
  90278. if (onLoad) {
  90279. onLoad();
  90280. }
  90281. return texture;
  90282. };
  90283. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  90284. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  90285. if (options !== undefined && typeof options === "object") {
  90286. fullOptions.generateMipMaps = options.generateMipMaps;
  90287. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  90288. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  90289. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  90290. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  90291. }
  90292. else {
  90293. fullOptions.generateMipMaps = options;
  90294. fullOptions.generateDepthBuffer = true;
  90295. fullOptions.generateStencilBuffer = false;
  90296. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90297. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  90298. }
  90299. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  90300. var width = size.width || size;
  90301. var height = size.height || size;
  90302. texture._depthStencilBuffer = {};
  90303. texture._framebuffer = {};
  90304. texture.baseWidth = width;
  90305. texture.baseHeight = height;
  90306. texture.width = width;
  90307. texture.height = height;
  90308. texture.isReady = true;
  90309. texture.samples = 1;
  90310. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  90311. texture.samplingMode = fullOptions.samplingMode;
  90312. texture.type = fullOptions.type;
  90313. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  90314. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  90315. return texture;
  90316. };
  90317. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  90318. texture.samplingMode = samplingMode;
  90319. };
  90320. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  90321. if (this._currentRenderTarget) {
  90322. this.unBindFramebuffer(this._currentRenderTarget);
  90323. }
  90324. this._currentRenderTarget = texture;
  90325. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  90326. if (this._cachedViewport && !forceFullscreenViewport) {
  90327. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  90328. }
  90329. };
  90330. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  90331. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  90332. this._currentRenderTarget = null;
  90333. if (onBeforeUnbind) {
  90334. if (texture._MSAAFramebuffer) {
  90335. this._currentFramebuffer = texture._framebuffer;
  90336. }
  90337. onBeforeUnbind();
  90338. }
  90339. this._currentFramebuffer = null;
  90340. };
  90341. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  90342. var vbo = {
  90343. capacity: 1,
  90344. references: 1,
  90345. is32Bits: false
  90346. };
  90347. return vbo;
  90348. };
  90349. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  90350. if (offset === void 0) { offset = 0; }
  90351. };
  90352. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  90353. };
  90354. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  90355. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  90356. this._boundTexturesCache[this._activeChannel] = texture;
  90357. }
  90358. };
  90359. NullEngine.prototype._bindTexture = function (channel, texture) {
  90360. if (channel < 0) {
  90361. return;
  90362. }
  90363. this._bindTextureDirectly(0, texture);
  90364. };
  90365. NullEngine.prototype._releaseBuffer = function (buffer) {
  90366. buffer.references--;
  90367. if (buffer.references === 0) {
  90368. return true;
  90369. }
  90370. return false;
  90371. };
  90372. return NullEngine;
  90373. }(BABYLON.Engine));
  90374. BABYLON.NullEngine = NullEngine;
  90375. })(BABYLON || (BABYLON = {}));
  90376. //# sourceMappingURL=babylon.nullEngine.js.map
  90377. "use strict";
  90378. var BABYLON;
  90379. (function (BABYLON) {
  90380. /**
  90381. * This class can be used to get instrumentation data from a Babylon engine
  90382. */
  90383. var EngineInstrumentation = /** @class */ (function () {
  90384. function EngineInstrumentation(engine) {
  90385. this.engine = engine;
  90386. this._captureGPUFrameTime = false;
  90387. this._gpuFrameTime = new BABYLON.PerfCounter();
  90388. this._captureShaderCompilationTime = false;
  90389. this._shaderCompilationTime = new BABYLON.PerfCounter();
  90390. // Observers
  90391. this._onBeginFrameObserver = null;
  90392. this._onEndFrameObserver = null;
  90393. this._onBeforeShaderCompilationObserver = null;
  90394. this._onAfterShaderCompilationObserver = null;
  90395. }
  90396. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  90397. // Properties
  90398. /**
  90399. * Gets the perf counter used for GPU frame time
  90400. */
  90401. get: function () {
  90402. return this._gpuFrameTime;
  90403. },
  90404. enumerable: true,
  90405. configurable: true
  90406. });
  90407. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  90408. /**
  90409. * Gets the GPU frame time capture status
  90410. */
  90411. get: function () {
  90412. return this._captureGPUFrameTime;
  90413. },
  90414. /**
  90415. * Enable or disable the GPU frame time capture
  90416. */
  90417. set: function (value) {
  90418. var _this = this;
  90419. if (value === this._captureGPUFrameTime) {
  90420. return;
  90421. }
  90422. this._captureGPUFrameTime = value;
  90423. if (value) {
  90424. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  90425. if (!_this._gpuFrameTimeToken) {
  90426. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  90427. }
  90428. });
  90429. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  90430. if (!_this._gpuFrameTimeToken) {
  90431. return;
  90432. }
  90433. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  90434. if (time > -1) {
  90435. _this._gpuFrameTimeToken = null;
  90436. _this._gpuFrameTime.fetchNewFrame();
  90437. _this._gpuFrameTime.addCount(time, true);
  90438. }
  90439. });
  90440. }
  90441. else {
  90442. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90443. this._onBeginFrameObserver = null;
  90444. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90445. this._onEndFrameObserver = null;
  90446. }
  90447. },
  90448. enumerable: true,
  90449. configurable: true
  90450. });
  90451. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  90452. /**
  90453. * Gets the perf counter used for shader compilation time
  90454. */
  90455. get: function () {
  90456. return this._shaderCompilationTime;
  90457. },
  90458. enumerable: true,
  90459. configurable: true
  90460. });
  90461. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  90462. /**
  90463. * Gets the shader compilation time capture status
  90464. */
  90465. get: function () {
  90466. return this._captureShaderCompilationTime;
  90467. },
  90468. /**
  90469. * Enable or disable the shader compilation time capture
  90470. */
  90471. set: function (value) {
  90472. var _this = this;
  90473. if (value === this._captureShaderCompilationTime) {
  90474. return;
  90475. }
  90476. this._captureShaderCompilationTime = value;
  90477. if (value) {
  90478. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  90479. _this._shaderCompilationTime.fetchNewFrame();
  90480. _this._shaderCompilationTime.beginMonitoring();
  90481. });
  90482. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  90483. _this._shaderCompilationTime.endMonitoring();
  90484. });
  90485. }
  90486. else {
  90487. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90488. this._onBeforeShaderCompilationObserver = null;
  90489. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90490. this._onAfterShaderCompilationObserver = null;
  90491. }
  90492. },
  90493. enumerable: true,
  90494. configurable: true
  90495. });
  90496. EngineInstrumentation.prototype.dispose = function () {
  90497. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90498. this._onBeginFrameObserver = null;
  90499. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90500. this._onEndFrameObserver = null;
  90501. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90502. this._onBeforeShaderCompilationObserver = null;
  90503. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90504. this._onAfterShaderCompilationObserver = null;
  90505. this.engine = null;
  90506. };
  90507. return EngineInstrumentation;
  90508. }());
  90509. BABYLON.EngineInstrumentation = EngineInstrumentation;
  90510. })(BABYLON || (BABYLON = {}));
  90511. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  90512. "use strict";
  90513. var BABYLON;
  90514. (function (BABYLON) {
  90515. /**
  90516. * This class can be used to get instrumentation data from a Babylon engine
  90517. */
  90518. var SceneInstrumentation = /** @class */ (function () {
  90519. function SceneInstrumentation(scene) {
  90520. var _this = this;
  90521. this.scene = scene;
  90522. this._captureActiveMeshesEvaluationTime = false;
  90523. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  90524. this._captureRenderTargetsRenderTime = false;
  90525. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  90526. this._captureFrameTime = false;
  90527. this._frameTime = new BABYLON.PerfCounter();
  90528. this._captureRenderTime = false;
  90529. this._renderTime = new BABYLON.PerfCounter();
  90530. this._captureInterFrameTime = false;
  90531. this._interFrameTime = new BABYLON.PerfCounter();
  90532. this._captureParticlesRenderTime = false;
  90533. this._particlesRenderTime = new BABYLON.PerfCounter();
  90534. this._captureSpritesRenderTime = false;
  90535. this._spritesRenderTime = new BABYLON.PerfCounter();
  90536. this._capturePhysicsTime = false;
  90537. this._physicsTime = new BABYLON.PerfCounter();
  90538. this._captureAnimationsTime = false;
  90539. this._animationsTime = new BABYLON.PerfCounter();
  90540. // Observers
  90541. this._onBeforeActiveMeshesEvaluationObserver = null;
  90542. this._onAfterActiveMeshesEvaluationObserver = null;
  90543. this._onBeforeRenderTargetsRenderObserver = null;
  90544. this._onAfterRenderTargetsRenderObserver = null;
  90545. this._onAfterRenderObserver = null;
  90546. this._onBeforeDrawPhaseObserver = null;
  90547. this._onAfterDrawPhaseObserver = null;
  90548. this._onBeforeAnimationsObserver = null;
  90549. this._onBeforeParticlesRenderingObserver = null;
  90550. this._onAfterParticlesRenderingObserver = null;
  90551. this._onBeforeSpritesRenderingObserver = null;
  90552. this._onAfterSpritesRenderingObserver = null;
  90553. this._onBeforePhysicsObserver = null;
  90554. this._onAfterPhysicsObserver = null;
  90555. this._onAfterAnimationsObserver = null;
  90556. // Before render
  90557. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  90558. if (_this._captureActiveMeshesEvaluationTime) {
  90559. _this._activeMeshesEvaluationTime.fetchNewFrame();
  90560. }
  90561. if (_this._captureRenderTargetsRenderTime) {
  90562. _this._renderTargetsRenderTime.fetchNewFrame();
  90563. }
  90564. if (_this._captureFrameTime) {
  90565. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  90566. _this._frameTime.beginMonitoring();
  90567. }
  90568. if (_this._captureInterFrameTime) {
  90569. _this._interFrameTime.endMonitoring();
  90570. }
  90571. if (_this._captureParticlesRenderTime) {
  90572. _this._particlesRenderTime.fetchNewFrame();
  90573. }
  90574. if (_this._captureSpritesRenderTime) {
  90575. _this._spritesRenderTime.fetchNewFrame();
  90576. }
  90577. if (_this._captureAnimationsTime) {
  90578. _this._animationsTime.beginMonitoring();
  90579. }
  90580. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  90581. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  90582. });
  90583. // After render
  90584. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  90585. if (_this._captureFrameTime) {
  90586. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  90587. _this._frameTime.endMonitoring();
  90588. }
  90589. if (_this._captureRenderTime) {
  90590. _this._renderTime.endMonitoring(false);
  90591. }
  90592. if (_this._captureInterFrameTime) {
  90593. _this._interFrameTime.beginMonitoring();
  90594. }
  90595. });
  90596. }
  90597. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  90598. // Properties
  90599. /**
  90600. * Gets the perf counter used for active meshes evaluation time
  90601. */
  90602. get: function () {
  90603. return this._activeMeshesEvaluationTime;
  90604. },
  90605. enumerable: true,
  90606. configurable: true
  90607. });
  90608. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  90609. /**
  90610. * Gets the active meshes evaluation time capture status
  90611. */
  90612. get: function () {
  90613. return this._captureActiveMeshesEvaluationTime;
  90614. },
  90615. /**
  90616. * Enable or disable the active meshes evaluation time capture
  90617. */
  90618. set: function (value) {
  90619. var _this = this;
  90620. if (value === this._captureActiveMeshesEvaluationTime) {
  90621. return;
  90622. }
  90623. this._captureActiveMeshesEvaluationTime = value;
  90624. if (value) {
  90625. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  90626. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  90627. _this._activeMeshesEvaluationTime.beginMonitoring();
  90628. });
  90629. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  90630. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  90631. _this._activeMeshesEvaluationTime.endMonitoring();
  90632. });
  90633. }
  90634. else {
  90635. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90636. this._onBeforeActiveMeshesEvaluationObserver = null;
  90637. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90638. this._onAfterActiveMeshesEvaluationObserver = null;
  90639. }
  90640. },
  90641. enumerable: true,
  90642. configurable: true
  90643. });
  90644. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  90645. /**
  90646. * Gets the perf counter used for render targets render time
  90647. */
  90648. get: function () {
  90649. return this._renderTargetsRenderTime;
  90650. },
  90651. enumerable: true,
  90652. configurable: true
  90653. });
  90654. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  90655. /**
  90656. * Gets the render targets render time capture status
  90657. */
  90658. get: function () {
  90659. return this._captureRenderTargetsRenderTime;
  90660. },
  90661. /**
  90662. * Enable or disable the render targets render time capture
  90663. */
  90664. set: function (value) {
  90665. var _this = this;
  90666. if (value === this._captureRenderTargetsRenderTime) {
  90667. return;
  90668. }
  90669. this._captureRenderTargetsRenderTime = value;
  90670. if (value) {
  90671. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  90672. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  90673. _this._renderTargetsRenderTime.beginMonitoring();
  90674. });
  90675. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  90676. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  90677. _this._renderTargetsRenderTime.endMonitoring(false);
  90678. });
  90679. }
  90680. else {
  90681. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90682. this._onBeforeRenderTargetsRenderObserver = null;
  90683. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90684. this._onAfterRenderTargetsRenderObserver = null;
  90685. }
  90686. },
  90687. enumerable: true,
  90688. configurable: true
  90689. });
  90690. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  90691. /**
  90692. * Gets the perf counter used for particles render time
  90693. */
  90694. get: function () {
  90695. return this._particlesRenderTime;
  90696. },
  90697. enumerable: true,
  90698. configurable: true
  90699. });
  90700. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  90701. /**
  90702. * Gets the particles render time capture status
  90703. */
  90704. get: function () {
  90705. return this._captureParticlesRenderTime;
  90706. },
  90707. /**
  90708. * Enable or disable the particles render time capture
  90709. */
  90710. set: function (value) {
  90711. var _this = this;
  90712. if (value === this._captureParticlesRenderTime) {
  90713. return;
  90714. }
  90715. this._captureParticlesRenderTime = value;
  90716. if (value) {
  90717. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  90718. BABYLON.Tools.StartPerformanceCounter("Particles");
  90719. _this._particlesRenderTime.beginMonitoring();
  90720. });
  90721. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  90722. BABYLON.Tools.EndPerformanceCounter("Particles");
  90723. _this._particlesRenderTime.endMonitoring(false);
  90724. });
  90725. }
  90726. else {
  90727. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90728. this._onBeforeParticlesRenderingObserver = null;
  90729. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90730. this._onAfterParticlesRenderingObserver = null;
  90731. }
  90732. },
  90733. enumerable: true,
  90734. configurable: true
  90735. });
  90736. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  90737. /**
  90738. * Gets the perf counter used for sprites render time
  90739. */
  90740. get: function () {
  90741. return this._spritesRenderTime;
  90742. },
  90743. enumerable: true,
  90744. configurable: true
  90745. });
  90746. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  90747. /**
  90748. * Gets the sprites render time capture status
  90749. */
  90750. get: function () {
  90751. return this._captureSpritesRenderTime;
  90752. },
  90753. /**
  90754. * Enable or disable the sprites render time capture
  90755. */
  90756. set: function (value) {
  90757. var _this = this;
  90758. if (value === this._captureSpritesRenderTime) {
  90759. return;
  90760. }
  90761. this._captureSpritesRenderTime = value;
  90762. if (value) {
  90763. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  90764. BABYLON.Tools.StartPerformanceCounter("Sprites");
  90765. _this._spritesRenderTime.beginMonitoring();
  90766. });
  90767. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  90768. BABYLON.Tools.EndPerformanceCounter("Sprites");
  90769. _this._spritesRenderTime.endMonitoring(false);
  90770. });
  90771. }
  90772. else {
  90773. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90774. this._onBeforeSpritesRenderingObserver = null;
  90775. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90776. this._onAfterSpritesRenderingObserver = null;
  90777. }
  90778. },
  90779. enumerable: true,
  90780. configurable: true
  90781. });
  90782. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  90783. /**
  90784. * Gets the perf counter used for physics time
  90785. */
  90786. get: function () {
  90787. return this._physicsTime;
  90788. },
  90789. enumerable: true,
  90790. configurable: true
  90791. });
  90792. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  90793. /**
  90794. * Gets the physics time capture status
  90795. */
  90796. get: function () {
  90797. return this._capturePhysicsTime;
  90798. },
  90799. /**
  90800. * Enable or disable the physics time capture
  90801. */
  90802. set: function (value) {
  90803. var _this = this;
  90804. if (value === this._capturePhysicsTime) {
  90805. return;
  90806. }
  90807. this._capturePhysicsTime = value;
  90808. if (value) {
  90809. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  90810. BABYLON.Tools.StartPerformanceCounter("Physics");
  90811. _this._physicsTime.beginMonitoring();
  90812. });
  90813. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  90814. BABYLON.Tools.EndPerformanceCounter("Physics");
  90815. _this._physicsTime.endMonitoring();
  90816. });
  90817. }
  90818. else {
  90819. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90820. this._onBeforePhysicsObserver = null;
  90821. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90822. this._onAfterPhysicsObserver = null;
  90823. }
  90824. },
  90825. enumerable: true,
  90826. configurable: true
  90827. });
  90828. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  90829. /**
  90830. * Gets the perf counter used for animations time
  90831. */
  90832. get: function () {
  90833. return this._animationsTime;
  90834. },
  90835. enumerable: true,
  90836. configurable: true
  90837. });
  90838. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  90839. /**
  90840. * Gets the animations time capture status
  90841. */
  90842. get: function () {
  90843. return this._captureAnimationsTime;
  90844. },
  90845. /**
  90846. * Enable or disable the animations time capture
  90847. */
  90848. set: function (value) {
  90849. var _this = this;
  90850. if (value === this._captureAnimationsTime) {
  90851. return;
  90852. }
  90853. this._captureAnimationsTime = value;
  90854. if (value) {
  90855. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  90856. _this._animationsTime.endMonitoring();
  90857. });
  90858. }
  90859. else {
  90860. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90861. this._onAfterAnimationsObserver = null;
  90862. }
  90863. },
  90864. enumerable: true,
  90865. configurable: true
  90866. });
  90867. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  90868. /**
  90869. * Gets the perf counter used for frame time capture
  90870. */
  90871. get: function () {
  90872. return this._frameTime;
  90873. },
  90874. enumerable: true,
  90875. configurable: true
  90876. });
  90877. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  90878. /**
  90879. * Gets the frame time capture status
  90880. */
  90881. get: function () {
  90882. return this._captureFrameTime;
  90883. },
  90884. /**
  90885. * Enable or disable the frame time capture
  90886. */
  90887. set: function (value) {
  90888. this._captureFrameTime = value;
  90889. },
  90890. enumerable: true,
  90891. configurable: true
  90892. });
  90893. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  90894. /**
  90895. * Gets the perf counter used for inter-frames time capture
  90896. */
  90897. get: function () {
  90898. return this._interFrameTime;
  90899. },
  90900. enumerable: true,
  90901. configurable: true
  90902. });
  90903. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  90904. /**
  90905. * Gets the inter-frames time capture status
  90906. */
  90907. get: function () {
  90908. return this._captureInterFrameTime;
  90909. },
  90910. /**
  90911. * Enable or disable the inter-frames time capture
  90912. */
  90913. set: function (value) {
  90914. this._captureInterFrameTime = value;
  90915. },
  90916. enumerable: true,
  90917. configurable: true
  90918. });
  90919. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  90920. /**
  90921. * Gets the perf counter used for render time capture
  90922. */
  90923. get: function () {
  90924. return this._renderTime;
  90925. },
  90926. enumerable: true,
  90927. configurable: true
  90928. });
  90929. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  90930. /**
  90931. * Gets the render time capture status
  90932. */
  90933. get: function () {
  90934. return this._captureRenderTime;
  90935. },
  90936. /**
  90937. * Enable or disable the render time capture
  90938. */
  90939. set: function (value) {
  90940. var _this = this;
  90941. if (value === this._captureRenderTime) {
  90942. return;
  90943. }
  90944. this._captureRenderTime = value;
  90945. if (value) {
  90946. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  90947. _this._renderTime.beginMonitoring();
  90948. BABYLON.Tools.StartPerformanceCounter("Main render");
  90949. });
  90950. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  90951. _this._renderTime.endMonitoring(false);
  90952. BABYLON.Tools.EndPerformanceCounter("Main render");
  90953. });
  90954. }
  90955. else {
  90956. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90957. this._onBeforeDrawPhaseObserver = null;
  90958. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90959. this._onAfterDrawPhaseObserver = null;
  90960. }
  90961. },
  90962. enumerable: true,
  90963. configurable: true
  90964. });
  90965. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  90966. /**
  90967. * Gets the perf counter used for draw calls
  90968. */
  90969. get: function () {
  90970. return this.scene.getEngine()._drawCalls;
  90971. },
  90972. enumerable: true,
  90973. configurable: true
  90974. });
  90975. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  90976. /**
  90977. * Gets the perf counter used for texture collisions
  90978. */
  90979. get: function () {
  90980. return this.scene.getEngine()._textureCollisions;
  90981. },
  90982. enumerable: true,
  90983. configurable: true
  90984. });
  90985. SceneInstrumentation.prototype.dispose = function () {
  90986. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  90987. this._onAfterRenderObserver = null;
  90988. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90989. this._onBeforeActiveMeshesEvaluationObserver = null;
  90990. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90991. this._onAfterActiveMeshesEvaluationObserver = null;
  90992. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90993. this._onBeforeRenderTargetsRenderObserver = null;
  90994. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90995. this._onAfterRenderTargetsRenderObserver = null;
  90996. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  90997. this._onBeforeAnimationsObserver = null;
  90998. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90999. this._onBeforeParticlesRenderingObserver = null;
  91000. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  91001. this._onAfterParticlesRenderingObserver = null;
  91002. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  91003. this._onBeforeSpritesRenderingObserver = null;
  91004. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  91005. this._onAfterSpritesRenderingObserver = null;
  91006. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  91007. this._onBeforeDrawPhaseObserver = null;
  91008. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  91009. this._onAfterDrawPhaseObserver = null;
  91010. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  91011. this._onBeforePhysicsObserver = null;
  91012. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  91013. this._onAfterPhysicsObserver = null;
  91014. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  91015. this._onAfterAnimationsObserver = null;
  91016. this.scene = null;
  91017. };
  91018. return SceneInstrumentation;
  91019. }());
  91020. BABYLON.SceneInstrumentation = SceneInstrumentation;
  91021. })(BABYLON || (BABYLON = {}));
  91022. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  91023. "use strict";
  91024. var BABYLON;
  91025. (function (BABYLON) {
  91026. var _TimeToken = /** @class */ (function () {
  91027. function _TimeToken() {
  91028. this._timeElapsedQueryEnded = false;
  91029. }
  91030. return _TimeToken;
  91031. }());
  91032. BABYLON._TimeToken = _TimeToken;
  91033. })(BABYLON || (BABYLON = {}));
  91034. //# sourceMappingURL=babylon.timeToken.js.map
  91035. "use strict";
  91036. var BABYLON;
  91037. (function (BABYLON) {
  91038. /**
  91039. * Background material defines definition.
  91040. * @ignore Mainly internal Use
  91041. */
  91042. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  91043. __extends(BackgroundMaterialDefines, _super);
  91044. /**
  91045. * Constructor of the defines.
  91046. */
  91047. function BackgroundMaterialDefines() {
  91048. var _this = _super.call(this) || this;
  91049. /**
  91050. * True if the diffuse texture is in use.
  91051. */
  91052. _this.DIFFUSE = false;
  91053. /**
  91054. * The direct UV channel to use.
  91055. */
  91056. _this.DIFFUSEDIRECTUV = 0;
  91057. /**
  91058. * True if the diffuse texture is in gamma space.
  91059. */
  91060. _this.GAMMADIFFUSE = false;
  91061. /**
  91062. * True if the diffuse texture has opacity in the alpha channel.
  91063. */
  91064. _this.DIFFUSEHASALPHA = false;
  91065. /**
  91066. * True if you want the material to fade to transparent at grazing angle.
  91067. */
  91068. _this.OPACITYFRESNEL = false;
  91069. /**
  91070. * True if an extra blur needs to be added in the reflection.
  91071. */
  91072. _this.REFLECTIONBLUR = false;
  91073. /**
  91074. * True if you want the material to fade to reflection at grazing angle.
  91075. */
  91076. _this.REFLECTIONFRESNEL = false;
  91077. /**
  91078. * True if you want the material to falloff as far as you move away from the scene center.
  91079. */
  91080. _this.REFLECTIONFALLOFF = false;
  91081. /**
  91082. * False if the current Webgl implementation does not support the texture lod extension.
  91083. */
  91084. _this.TEXTURELODSUPPORT = false;
  91085. /**
  91086. * True to ensure the data are premultiplied.
  91087. */
  91088. _this.PREMULTIPLYALPHA = false;
  91089. /**
  91090. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  91091. */
  91092. _this.USERGBCOLOR = false;
  91093. /**
  91094. * True to add noise in order to reduce the banding effect.
  91095. */
  91096. _this.NOISE = false;
  91097. /**
  91098. * is the reflection texture in BGR color scheme?
  91099. * Mainly used to solve a bug in ios10 video tag
  91100. */
  91101. _this.REFLECTIONBGR = false;
  91102. _this.IMAGEPROCESSING = false;
  91103. _this.VIGNETTE = false;
  91104. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  91105. _this.VIGNETTEBLENDMODEOPAQUE = false;
  91106. _this.TONEMAPPING = false;
  91107. _this.CONTRAST = false;
  91108. _this.COLORCURVES = false;
  91109. _this.COLORGRADING = false;
  91110. _this.COLORGRADING3D = false;
  91111. _this.SAMPLER3DGREENDEPTH = false;
  91112. _this.SAMPLER3DBGRMAP = false;
  91113. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  91114. _this.EXPOSURE = false;
  91115. _this.GRAIN = false;
  91116. // Reflection.
  91117. _this.REFLECTION = false;
  91118. _this.REFLECTIONMAP_3D = false;
  91119. _this.REFLECTIONMAP_SPHERICAL = false;
  91120. _this.REFLECTIONMAP_PLANAR = false;
  91121. _this.REFLECTIONMAP_CUBIC = false;
  91122. _this.REFLECTIONMAP_PROJECTION = false;
  91123. _this.REFLECTIONMAP_SKYBOX = false;
  91124. _this.REFLECTIONMAP_EXPLICIT = false;
  91125. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91126. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91127. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91128. _this.INVERTCUBICMAP = false;
  91129. _this.REFLECTIONMAP_OPPOSITEZ = false;
  91130. _this.LODINREFLECTIONALPHA = false;
  91131. _this.GAMMAREFLECTION = false;
  91132. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  91133. // Default BJS.
  91134. _this.MAINUV1 = false;
  91135. _this.MAINUV2 = false;
  91136. _this.UV1 = false;
  91137. _this.UV2 = false;
  91138. _this.CLIPPLANE = false;
  91139. _this.POINTSIZE = false;
  91140. _this.FOG = false;
  91141. _this.NORMAL = false;
  91142. _this.NUM_BONE_INFLUENCERS = 0;
  91143. _this.BonesPerMesh = 0;
  91144. _this.INSTANCES = false;
  91145. _this.SHADOWFLOAT = false;
  91146. _this.rebuild();
  91147. return _this;
  91148. }
  91149. return BackgroundMaterialDefines;
  91150. }(BABYLON.MaterialDefines));
  91151. /**
  91152. * Background material used to create an efficient environement around your scene.
  91153. */
  91154. var BackgroundMaterial = /** @class */ (function (_super) {
  91155. __extends(BackgroundMaterial, _super);
  91156. /**
  91157. * Instantiates a Background Material in the given scene
  91158. * @param name The friendly name of the material
  91159. * @param scene The scene to add the material to
  91160. */
  91161. function BackgroundMaterial(name, scene) {
  91162. var _this = _super.call(this, name, scene) || this;
  91163. /**
  91164. * Key light Color (multiply against the R channel of the environement texture)
  91165. */
  91166. _this.primaryColor = BABYLON.Color3.White();
  91167. /**
  91168. * Key light Level (allowing HDR output of the background)
  91169. */
  91170. _this.primaryLevel = 1;
  91171. /**
  91172. * Secondary light Color (multiply against the G channel of the environement texture)
  91173. */
  91174. _this.secondaryColor = BABYLON.Color3.Gray();
  91175. /**
  91176. * Secondary light Level (allowing HDR output of the background)
  91177. */
  91178. _this.secondaryLevel = 1;
  91179. /**
  91180. * Tertiary light Color (multiply against the B channel of the environement texture)
  91181. */
  91182. _this.tertiaryColor = BABYLON.Color3.Black();
  91183. /**
  91184. * Tertiary light Level (allowing HDR output of the background)
  91185. */
  91186. _this.tertiaryLevel = 1;
  91187. /**
  91188. * Reflection Texture used in the material.
  91189. * Should be author in a specific way for the best result (refer to the documentation).
  91190. */
  91191. _this.reflectionTexture = null;
  91192. /**
  91193. * Reflection Texture level of blur.
  91194. *
  91195. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  91196. * texture twice.
  91197. */
  91198. _this.reflectionBlur = 0;
  91199. /**
  91200. * Diffuse Texture used in the material.
  91201. * Should be author in a specific way for the best result (refer to the documentation).
  91202. */
  91203. _this.diffuseTexture = null;
  91204. _this._shadowLights = null;
  91205. /**
  91206. * Specify the list of lights casting shadow on the material.
  91207. * All scene shadow lights will be included if null.
  91208. */
  91209. _this.shadowLights = null;
  91210. /**
  91211. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  91212. * soft lighting on the background.
  91213. */
  91214. _this.shadowBlurScale = 1;
  91215. /**
  91216. * Helps adjusting the shadow to a softer level if required.
  91217. * 0 means black shadows and 1 means no shadows.
  91218. */
  91219. _this.shadowLevel = 0;
  91220. /**
  91221. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  91222. * It is usually zero but might be interesting to modify according to your setup.
  91223. */
  91224. _this.sceneCenter = BABYLON.Vector3.Zero();
  91225. /**
  91226. * This helps specifying that the material is falling off to the sky box at grazing angle.
  91227. * This helps ensuring a nice transition when the camera goes under the ground.
  91228. */
  91229. _this.opacityFresnel = true;
  91230. /**
  91231. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  91232. * This helps adding a mirror texture on the ground.
  91233. */
  91234. _this.reflectionFresnel = false;
  91235. /**
  91236. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  91237. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  91238. */
  91239. _this.reflectionFalloffDistance = 0.0;
  91240. /**
  91241. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  91242. */
  91243. _this.reflectionAmount = 1.0;
  91244. /**
  91245. * This specifies the weight of the reflection at grazing angle.
  91246. */
  91247. _this.reflectionReflectance0 = 0.05;
  91248. /**
  91249. * This specifies the weight of the reflection at a perpendicular point of view.
  91250. */
  91251. _this.reflectionReflectance90 = 0.5;
  91252. /**
  91253. * Helps to directly use the maps channels instead of their level.
  91254. */
  91255. _this.useRGBColor = true;
  91256. /**
  91257. * This helps reducing the banding effect that could occur on the background.
  91258. */
  91259. _this.enableNoise = false;
  91260. _this._fovMultiplier = 1.0;
  91261. /**
  91262. * Enable the FOV adjustment feature controlled by fovMultiplier.
  91263. * @type {boolean}
  91264. */
  91265. _this.useEquirectangularFOV = false;
  91266. _this._maxSimultaneousLights = 4;
  91267. /**
  91268. * Number of Simultaneous lights allowed on the material.
  91269. */
  91270. _this.maxSimultaneousLights = 4;
  91271. /**
  91272. * Keep track of the image processing observer to allow dispose and replace.
  91273. */
  91274. _this._imageProcessingObserver = null;
  91275. /**
  91276. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  91277. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  91278. */
  91279. _this.switchToBGR = false;
  91280. // Temp values kept as cache in the material.
  91281. _this._renderTargets = new BABYLON.SmartArray(16);
  91282. _this._reflectionControls = BABYLON.Vector4.Zero();
  91283. // Setup the default processing configuration to the scene.
  91284. _this._attachImageProcessingConfiguration(null);
  91285. _this.getRenderTargetTextures = function () {
  91286. _this._renderTargets.reset();
  91287. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  91288. _this._renderTargets.push(_this._diffuseTexture);
  91289. }
  91290. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  91291. _this._renderTargets.push(_this._reflectionTexture);
  91292. }
  91293. return _this._renderTargets;
  91294. };
  91295. return _this;
  91296. }
  91297. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  91298. /**
  91299. * Sets the reflection reflectance fresnel values according to the default standard
  91300. * empirically know to work well :-)
  91301. */
  91302. set: function (value) {
  91303. var reflectionWeight = value;
  91304. if (reflectionWeight < 0.5) {
  91305. reflectionWeight = reflectionWeight * 2.0;
  91306. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  91307. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  91308. }
  91309. else {
  91310. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  91311. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  91312. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  91313. }
  91314. },
  91315. enumerable: true,
  91316. configurable: true
  91317. });
  91318. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  91319. /**
  91320. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  91321. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  91322. * Recommended to be keep at 1.0 except for special cases.
  91323. */
  91324. get: function () {
  91325. return this._fovMultiplier;
  91326. },
  91327. set: function (value) {
  91328. if (isNaN(value)) {
  91329. value = 1.0;
  91330. }
  91331. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  91332. },
  91333. enumerable: true,
  91334. configurable: true
  91335. });
  91336. /**
  91337. * Attaches a new image processing configuration to the PBR Material.
  91338. * @param configuration (if null the scene configuration will be use)
  91339. */
  91340. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  91341. var _this = this;
  91342. if (configuration === this._imageProcessingConfiguration) {
  91343. return;
  91344. }
  91345. // Detaches observer.
  91346. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91347. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91348. }
  91349. // Pick the scene configuration if needed.
  91350. if (!configuration) {
  91351. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  91352. }
  91353. else {
  91354. this._imageProcessingConfiguration = configuration;
  91355. }
  91356. // Attaches observer.
  91357. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  91358. _this._markAllSubMeshesAsImageProcessingDirty();
  91359. });
  91360. };
  91361. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  91362. /**
  91363. * Gets the image processing configuration used either in this material.
  91364. */
  91365. get: function () {
  91366. return this._imageProcessingConfiguration;
  91367. },
  91368. /**
  91369. * Sets the Default image processing configuration used either in the this material.
  91370. *
  91371. * If sets to null, the scene one is in use.
  91372. */
  91373. set: function (value) {
  91374. this._attachImageProcessingConfiguration(value);
  91375. // Ensure the effect will be rebuilt.
  91376. this._markAllSubMeshesAsTexturesDirty();
  91377. },
  91378. enumerable: true,
  91379. configurable: true
  91380. });
  91381. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  91382. /**
  91383. * Gets wether the color curves effect is enabled.
  91384. */
  91385. get: function () {
  91386. return this.imageProcessingConfiguration.colorCurvesEnabled;
  91387. },
  91388. /**
  91389. * Sets wether the color curves effect is enabled.
  91390. */
  91391. set: function (value) {
  91392. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  91393. },
  91394. enumerable: true,
  91395. configurable: true
  91396. });
  91397. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  91398. /**
  91399. * Gets wether the color grading effect is enabled.
  91400. */
  91401. get: function () {
  91402. return this.imageProcessingConfiguration.colorGradingEnabled;
  91403. },
  91404. /**
  91405. * Gets wether the color grading effect is enabled.
  91406. */
  91407. set: function (value) {
  91408. this.imageProcessingConfiguration.colorGradingEnabled = value;
  91409. },
  91410. enumerable: true,
  91411. configurable: true
  91412. });
  91413. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  91414. /**
  91415. * Gets wether tonemapping is enabled or not.
  91416. */
  91417. get: function () {
  91418. return this._imageProcessingConfiguration.toneMappingEnabled;
  91419. },
  91420. /**
  91421. * Sets wether tonemapping is enabled or not
  91422. */
  91423. set: function (value) {
  91424. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91425. },
  91426. enumerable: true,
  91427. configurable: true
  91428. });
  91429. ;
  91430. ;
  91431. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  91432. /**
  91433. * The camera exposure used on this material.
  91434. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91435. * This corresponds to a photographic exposure.
  91436. */
  91437. get: function () {
  91438. return this._imageProcessingConfiguration.exposure;
  91439. },
  91440. /**
  91441. * The camera exposure used on this material.
  91442. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91443. * This corresponds to a photographic exposure.
  91444. */
  91445. set: function (value) {
  91446. this._imageProcessingConfiguration.exposure = value;
  91447. },
  91448. enumerable: true,
  91449. configurable: true
  91450. });
  91451. ;
  91452. ;
  91453. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  91454. /**
  91455. * Gets The camera contrast used on this material.
  91456. */
  91457. get: function () {
  91458. return this._imageProcessingConfiguration.contrast;
  91459. },
  91460. /**
  91461. * Sets The camera contrast used on this material.
  91462. */
  91463. set: function (value) {
  91464. this._imageProcessingConfiguration.contrast = value;
  91465. },
  91466. enumerable: true,
  91467. configurable: true
  91468. });
  91469. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  91470. /**
  91471. * Gets the Color Grading 2D Lookup Texture.
  91472. */
  91473. get: function () {
  91474. return this._imageProcessingConfiguration.colorGradingTexture;
  91475. },
  91476. /**
  91477. * Sets the Color Grading 2D Lookup Texture.
  91478. */
  91479. set: function (value) {
  91480. this.imageProcessingConfiguration.colorGradingTexture = value;
  91481. },
  91482. enumerable: true,
  91483. configurable: true
  91484. });
  91485. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  91486. /**
  91487. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91488. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91489. * 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;
  91490. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91491. */
  91492. get: function () {
  91493. return this.imageProcessingConfiguration.colorCurves;
  91494. },
  91495. /**
  91496. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91497. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91498. * 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;
  91499. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91500. */
  91501. set: function (value) {
  91502. this.imageProcessingConfiguration.colorCurves = value;
  91503. },
  91504. enumerable: true,
  91505. configurable: true
  91506. });
  91507. /**
  91508. * The entire material has been created in order to prevent overdraw.
  91509. * @returns false
  91510. */
  91511. BackgroundMaterial.prototype.needAlphaTesting = function () {
  91512. return true;
  91513. };
  91514. /**
  91515. * The entire material has been created in order to prevent overdraw.
  91516. * @returns true if blending is enable
  91517. */
  91518. BackgroundMaterial.prototype.needAlphaBlending = function () {
  91519. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  91520. };
  91521. /**
  91522. * Checks wether the material is ready to be rendered for a given mesh.
  91523. * @param mesh The mesh to render
  91524. * @param subMesh The submesh to check against
  91525. * @param useInstances Specify wether or not the material is used with instances
  91526. * @returns true if all the dependencies are ready (Textures, Effects...)
  91527. */
  91528. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  91529. var _this = this;
  91530. if (useInstances === void 0) { useInstances = false; }
  91531. if (subMesh.effect && this.isFrozen) {
  91532. if (this._wasPreviouslyReady) {
  91533. return true;
  91534. }
  91535. }
  91536. if (!subMesh._materialDefines) {
  91537. subMesh._materialDefines = new BackgroundMaterialDefines();
  91538. }
  91539. var scene = this.getScene();
  91540. var defines = subMesh._materialDefines;
  91541. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  91542. if (defines._renderId === scene.getRenderId()) {
  91543. return true;
  91544. }
  91545. }
  91546. var engine = scene.getEngine();
  91547. // Lights
  91548. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  91549. defines._needNormals = true;
  91550. // Textures
  91551. if (defines._areTexturesDirty) {
  91552. defines._needUVs = false;
  91553. if (scene.texturesEnabled) {
  91554. if (scene.getEngine().getCaps().textureLOD) {
  91555. defines.TEXTURELODSUPPORT = true;
  91556. }
  91557. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91558. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  91559. return false;
  91560. }
  91561. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  91562. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  91563. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  91564. defines.OPACITYFRESNEL = this._opacityFresnel;
  91565. }
  91566. else {
  91567. defines.DIFFUSE = false;
  91568. defines.DIFFUSEHASALPHA = false;
  91569. defines.GAMMADIFFUSE = false;
  91570. defines.OPACITYFRESNEL = false;
  91571. }
  91572. var reflectionTexture = this._reflectionTexture;
  91573. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91574. if (!reflectionTexture.isReadyOrNotBlocking()) {
  91575. return false;
  91576. }
  91577. defines.REFLECTION = true;
  91578. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  91579. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  91580. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  91581. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  91582. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  91583. defines.REFLECTIONBGR = this.switchToBGR;
  91584. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  91585. defines.INVERTCUBICMAP = true;
  91586. }
  91587. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  91588. switch (reflectionTexture.coordinatesMode) {
  91589. case BABYLON.Texture.CUBIC_MODE:
  91590. case BABYLON.Texture.INVCUBIC_MODE:
  91591. defines.REFLECTIONMAP_CUBIC = true;
  91592. break;
  91593. case BABYLON.Texture.EXPLICIT_MODE:
  91594. defines.REFLECTIONMAP_EXPLICIT = true;
  91595. break;
  91596. case BABYLON.Texture.PLANAR_MODE:
  91597. defines.REFLECTIONMAP_PLANAR = true;
  91598. break;
  91599. case BABYLON.Texture.PROJECTION_MODE:
  91600. defines.REFLECTIONMAP_PROJECTION = true;
  91601. break;
  91602. case BABYLON.Texture.SKYBOX_MODE:
  91603. defines.REFLECTIONMAP_SKYBOX = true;
  91604. break;
  91605. case BABYLON.Texture.SPHERICAL_MODE:
  91606. defines.REFLECTIONMAP_SPHERICAL = true;
  91607. break;
  91608. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  91609. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  91610. break;
  91611. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  91612. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  91613. break;
  91614. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  91615. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  91616. break;
  91617. }
  91618. if (this.reflectionFresnel) {
  91619. defines.REFLECTIONFRESNEL = true;
  91620. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  91621. this._reflectionControls.x = this.reflectionAmount;
  91622. this._reflectionControls.y = this.reflectionReflectance0;
  91623. this._reflectionControls.z = this.reflectionReflectance90;
  91624. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  91625. }
  91626. else {
  91627. defines.REFLECTIONFRESNEL = false;
  91628. defines.REFLECTIONFALLOFF = false;
  91629. }
  91630. }
  91631. else {
  91632. defines.REFLECTION = false;
  91633. defines.REFLECTIONFALLOFF = false;
  91634. defines.REFLECTIONBLUR = false;
  91635. defines.REFLECTIONMAP_3D = false;
  91636. defines.REFLECTIONMAP_SPHERICAL = false;
  91637. defines.REFLECTIONMAP_PLANAR = false;
  91638. defines.REFLECTIONMAP_CUBIC = false;
  91639. defines.REFLECTIONMAP_PROJECTION = false;
  91640. defines.REFLECTIONMAP_SKYBOX = false;
  91641. defines.REFLECTIONMAP_EXPLICIT = false;
  91642. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91643. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91644. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91645. defines.INVERTCUBICMAP = false;
  91646. defines.REFLECTIONMAP_OPPOSITEZ = false;
  91647. defines.LODINREFLECTIONALPHA = false;
  91648. defines.GAMMAREFLECTION = false;
  91649. }
  91650. }
  91651. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  91652. defines.USERGBCOLOR = this._useRGBColor;
  91653. defines.NOISE = this._enableNoise;
  91654. }
  91655. if (defines._areImageProcessingDirty) {
  91656. if (!this._imageProcessingConfiguration.isReady()) {
  91657. return false;
  91658. }
  91659. this._imageProcessingConfiguration.prepareDefines(defines);
  91660. }
  91661. // Misc.
  91662. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  91663. // Values that need to be evaluated on every frame
  91664. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  91665. // Attribs
  91666. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  91667. if (mesh) {
  91668. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91669. mesh.createNormals(true);
  91670. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  91671. }
  91672. }
  91673. }
  91674. // Get correct effect
  91675. if (defines.isDirty) {
  91676. defines.markAsProcessed();
  91677. scene.resetCachedMaterial();
  91678. // Fallbacks
  91679. var fallbacks = new BABYLON.EffectFallbacks();
  91680. if (defines.FOG) {
  91681. fallbacks.addFallback(0, "FOG");
  91682. }
  91683. if (defines.POINTSIZE) {
  91684. fallbacks.addFallback(1, "POINTSIZE");
  91685. }
  91686. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  91687. if (defines.NUM_BONE_INFLUENCERS > 0) {
  91688. fallbacks.addCPUSkinningFallback(0, mesh);
  91689. }
  91690. //Attributes
  91691. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91692. if (defines.NORMAL) {
  91693. attribs.push(BABYLON.VertexBuffer.NormalKind);
  91694. }
  91695. if (defines.UV1) {
  91696. attribs.push(BABYLON.VertexBuffer.UVKind);
  91697. }
  91698. if (defines.UV2) {
  91699. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91700. }
  91701. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  91702. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  91703. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  91704. "vFogInfos", "vFogColor", "pointSize",
  91705. "vClipPlane", "mBones",
  91706. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  91707. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  91708. "shadowLevel", "alpha",
  91709. "vBackgroundCenter", "vReflectionControl",
  91710. "vDiffuseInfos", "diffuseMatrix",
  91711. ];
  91712. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  91713. var uniformBuffers = ["Material", "Scene"];
  91714. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  91715. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  91716. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  91717. uniformsNames: uniforms,
  91718. uniformBuffersNames: uniformBuffers,
  91719. samplers: samplers,
  91720. defines: defines,
  91721. maxSimultaneousLights: this._maxSimultaneousLights
  91722. });
  91723. var onCompiled = function (effect) {
  91724. if (_this.onCompiled) {
  91725. _this.onCompiled(effect);
  91726. }
  91727. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  91728. };
  91729. var join = defines.toString();
  91730. subMesh.setEffect(scene.getEngine().createEffect("background", {
  91731. attributes: attribs,
  91732. uniformsNames: uniforms,
  91733. uniformBuffersNames: uniformBuffers,
  91734. samplers: samplers,
  91735. defines: join,
  91736. fallbacks: fallbacks,
  91737. onCompiled: onCompiled,
  91738. onError: this.onError,
  91739. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  91740. }, engine), defines);
  91741. this.buildUniformLayout();
  91742. }
  91743. if (!subMesh.effect || !subMesh.effect.isReady()) {
  91744. return false;
  91745. }
  91746. defines._renderId = scene.getRenderId();
  91747. this._wasPreviouslyReady = true;
  91748. return true;
  91749. };
  91750. /**
  91751. * Build the uniform buffer used in the material.
  91752. */
  91753. BackgroundMaterial.prototype.buildUniformLayout = function () {
  91754. // Order is important !
  91755. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  91756. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  91757. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  91758. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  91759. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  91760. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  91761. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  91762. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  91763. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  91764. this._uniformBuffer.addUniform("pointSize", 1);
  91765. this._uniformBuffer.addUniform("shadowLevel", 1);
  91766. this._uniformBuffer.addUniform("alpha", 1);
  91767. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  91768. this._uniformBuffer.addUniform("vReflectionControl", 4);
  91769. this._uniformBuffer.create();
  91770. };
  91771. /**
  91772. * Unbind the material.
  91773. */
  91774. BackgroundMaterial.prototype.unbind = function () {
  91775. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  91776. this._uniformBuffer.setTexture("diffuseSampler", null);
  91777. }
  91778. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  91779. this._uniformBuffer.setTexture("reflectionSampler", null);
  91780. }
  91781. _super.prototype.unbind.call(this);
  91782. };
  91783. /**
  91784. * Bind only the world matrix to the material.
  91785. * @param world The world matrix to bind.
  91786. */
  91787. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  91788. this._activeEffect.setMatrix("world", world);
  91789. };
  91790. /**
  91791. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  91792. * @param world The world matrix to bind.
  91793. * @param subMesh The submesh to bind for.
  91794. */
  91795. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  91796. var scene = this.getScene();
  91797. var defines = subMesh._materialDefines;
  91798. if (!defines) {
  91799. return;
  91800. }
  91801. var effect = subMesh.effect;
  91802. if (!effect) {
  91803. return;
  91804. }
  91805. this._activeEffect = effect;
  91806. // Matrices
  91807. this.bindOnlyWorldMatrix(world);
  91808. // Bones
  91809. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  91810. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  91811. if (mustRebind) {
  91812. this._uniformBuffer.bindToEffect(effect, "Material");
  91813. this.bindViewProjection(effect);
  91814. var reflectionTexture = this._reflectionTexture;
  91815. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  91816. // Texture uniforms
  91817. if (scene.texturesEnabled) {
  91818. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91819. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  91820. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  91821. }
  91822. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91823. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  91824. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  91825. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  91826. }
  91827. }
  91828. if (this.shadowLevel > 0) {
  91829. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  91830. }
  91831. this._uniformBuffer.updateFloat("alpha", this.alpha);
  91832. // Point size
  91833. if (this.pointsCloud) {
  91834. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  91835. }
  91836. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  91837. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  91838. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  91839. }
  91840. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  91841. // Textures
  91842. if (scene.texturesEnabled) {
  91843. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91844. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  91845. }
  91846. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91847. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  91848. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91849. }
  91850. else if (!defines.REFLECTIONBLUR) {
  91851. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91852. }
  91853. else {
  91854. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  91855. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  91856. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  91857. }
  91858. if (defines.REFLECTIONFRESNEL) {
  91859. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  91860. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  91861. }
  91862. }
  91863. }
  91864. // Clip plane
  91865. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  91866. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  91867. }
  91868. if (mustRebind || !this.isFrozen) {
  91869. if (scene.lightsEnabled) {
  91870. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  91871. }
  91872. // View
  91873. this.bindView(effect);
  91874. // Fog
  91875. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  91876. // image processing
  91877. this._imageProcessingConfiguration.bind(this._activeEffect);
  91878. }
  91879. this._uniformBuffer.update();
  91880. this._afterBind(mesh);
  91881. };
  91882. /**
  91883. * Dispose the material.
  91884. * @param forceDisposeEffect Force disposal of the associated effect.
  91885. * @param forceDisposeTextures Force disposal of the associated textures.
  91886. */
  91887. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  91888. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  91889. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  91890. if (forceDisposeTextures) {
  91891. if (this.diffuseTexture) {
  91892. this.diffuseTexture.dispose();
  91893. }
  91894. if (this.reflectionTexture) {
  91895. this.reflectionTexture.dispose();
  91896. }
  91897. }
  91898. this._renderTargets.dispose();
  91899. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91900. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91901. }
  91902. _super.prototype.dispose.call(this, forceDisposeEffect);
  91903. };
  91904. /**
  91905. * Clones the material.
  91906. * @param name The cloned name.
  91907. * @returns The cloned material.
  91908. */
  91909. BackgroundMaterial.prototype.clone = function (name) {
  91910. var _this = this;
  91911. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  91912. };
  91913. /**
  91914. * Serializes the current material to its JSON representation.
  91915. * @returns The JSON representation.
  91916. */
  91917. BackgroundMaterial.prototype.serialize = function () {
  91918. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91919. serializationObject.customType = "BABYLON.BackgroundMaterial";
  91920. return serializationObject;
  91921. };
  91922. /**
  91923. * Gets the class name of the material
  91924. * @returns "BackgroundMaterial"
  91925. */
  91926. BackgroundMaterial.prototype.getClassName = function () {
  91927. return "BackgroundMaterial";
  91928. };
  91929. /**
  91930. * Parse a JSON input to create back a background material.
  91931. * @param source The JSON data to parse
  91932. * @param scene The scene to create the parsed material in
  91933. * @param rootUrl The root url of the assets the material depends upon
  91934. * @returns the instantiated BackgroundMaterial.
  91935. */
  91936. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  91937. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  91938. };
  91939. /**
  91940. * Standard reflectance value at parallel view angle.
  91941. */
  91942. BackgroundMaterial.StandardReflectance0 = 0.05;
  91943. /**
  91944. * Standard reflectance value at grazing angle.
  91945. */
  91946. BackgroundMaterial.StandardReflectance90 = 0.5;
  91947. __decorate([
  91948. BABYLON.serializeAsColor3()
  91949. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  91950. __decorate([
  91951. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91952. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  91953. __decorate([
  91954. BABYLON.serialize()
  91955. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  91956. __decorate([
  91957. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91958. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  91959. __decorate([
  91960. BABYLON.serializeAsColor3()
  91961. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  91962. __decorate([
  91963. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91964. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  91965. __decorate([
  91966. BABYLON.serialize()
  91967. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  91968. __decorate([
  91969. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91970. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  91971. __decorate([
  91972. BABYLON.serializeAsColor3()
  91973. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  91974. __decorate([
  91975. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91976. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  91977. __decorate([
  91978. BABYLON.serialize()
  91979. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  91980. __decorate([
  91981. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91982. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  91983. __decorate([
  91984. BABYLON.serializeAsTexture()
  91985. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  91986. __decorate([
  91987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91988. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  91989. __decorate([
  91990. BABYLON.serialize()
  91991. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  91992. __decorate([
  91993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91994. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  91995. __decorate([
  91996. BABYLON.serializeAsTexture()
  91997. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  91998. __decorate([
  91999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92000. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  92001. __decorate([
  92002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92003. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  92004. __decorate([
  92005. BABYLON.serialize()
  92006. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  92007. __decorate([
  92008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92009. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  92010. __decorate([
  92011. BABYLON.serialize()
  92012. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  92013. __decorate([
  92014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92015. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  92016. __decorate([
  92017. BABYLON.serializeAsVector3()
  92018. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  92019. __decorate([
  92020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92021. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  92022. __decorate([
  92023. BABYLON.serialize()
  92024. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  92025. __decorate([
  92026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92027. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  92028. __decorate([
  92029. BABYLON.serialize()
  92030. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  92031. __decorate([
  92032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92033. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  92034. __decorate([
  92035. BABYLON.serialize()
  92036. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  92037. __decorate([
  92038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92039. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  92040. __decorate([
  92041. BABYLON.serialize()
  92042. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  92043. __decorate([
  92044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92045. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  92046. __decorate([
  92047. BABYLON.serialize()
  92048. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  92049. __decorate([
  92050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92051. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  92052. __decorate([
  92053. BABYLON.serialize()
  92054. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  92055. __decorate([
  92056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92057. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  92058. __decorate([
  92059. BABYLON.serialize()
  92060. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  92061. __decorate([
  92062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92063. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  92064. __decorate([
  92065. BABYLON.serialize()
  92066. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  92067. __decorate([
  92068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92069. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  92070. __decorate([
  92071. BABYLON.serialize()
  92072. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  92073. __decorate([
  92074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92075. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  92076. __decorate([
  92077. BABYLON.serializeAsImageProcessingConfiguration()
  92078. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  92079. return BackgroundMaterial;
  92080. }(BABYLON.PushMaterial));
  92081. BABYLON.BackgroundMaterial = BackgroundMaterial;
  92082. })(BABYLON || (BABYLON = {}));
  92083. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  92084. "use strict";
  92085. var __assign = (this && this.__assign) || Object.assign || function(t) {
  92086. for (var s, i = 1, n = arguments.length; i < n; i++) {
  92087. s = arguments[i];
  92088. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  92089. t[p] = s[p];
  92090. }
  92091. return t;
  92092. };
  92093. var BABYLON;
  92094. (function (BABYLON) {
  92095. /**
  92096. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  92097. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  92098. * It also helps with the default setup of your imageProcessing configuration.
  92099. */
  92100. var EnvironmentHelper = /** @class */ (function () {
  92101. /**
  92102. * constructor
  92103. * @param options
  92104. * @param scene The scene to add the material to
  92105. */
  92106. function EnvironmentHelper(options, scene) {
  92107. var _this = this;
  92108. this._errorHandler = function (message, exception) {
  92109. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  92110. };
  92111. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  92112. this._scene = scene;
  92113. this.onErrorObservable = new BABYLON.Observable();
  92114. this._setupBackground();
  92115. this._setupImageProcessing();
  92116. }
  92117. /**
  92118. * Creates the default options for the helper.
  92119. */
  92120. EnvironmentHelper._getDefaultOptions = function () {
  92121. return {
  92122. createGround: true,
  92123. groundSize: 15,
  92124. groundTexture: this._groundTextureCDNUrl,
  92125. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  92126. groundOpacity: 0.9,
  92127. enableGroundShadow: true,
  92128. groundShadowLevel: 0.5,
  92129. enableGroundMirror: false,
  92130. groundMirrorSizeRatio: 0.3,
  92131. groundMirrorBlurKernel: 64,
  92132. groundMirrorAmount: 1,
  92133. groundMirrorFresnelWeight: 1,
  92134. groundMirrorFallOffDistance: 0,
  92135. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  92136. groundYBias: 0.00001,
  92137. createSkybox: true,
  92138. skyboxSize: 20,
  92139. skyboxTexture: this._skyboxTextureCDNUrl,
  92140. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  92141. backgroundYRotation: 0,
  92142. sizeAuto: true,
  92143. rootPosition: BABYLON.Vector3.Zero(),
  92144. setupImageProcessing: true,
  92145. environmentTexture: this._environmentTextureCDNUrl,
  92146. cameraExposure: 0.8,
  92147. cameraContrast: 1.2,
  92148. toneMappingEnabled: true,
  92149. };
  92150. };
  92151. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  92152. /**
  92153. * Gets the root mesh created by the helper.
  92154. */
  92155. get: function () {
  92156. return this._rootMesh;
  92157. },
  92158. enumerable: true,
  92159. configurable: true
  92160. });
  92161. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  92162. /**
  92163. * Gets the skybox created by the helper.
  92164. */
  92165. get: function () {
  92166. return this._skybox;
  92167. },
  92168. enumerable: true,
  92169. configurable: true
  92170. });
  92171. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  92172. /**
  92173. * Gets the skybox texture created by the helper.
  92174. */
  92175. get: function () {
  92176. return this._skyboxTexture;
  92177. },
  92178. enumerable: true,
  92179. configurable: true
  92180. });
  92181. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  92182. /**
  92183. * Gets the skybox material created by the helper.
  92184. */
  92185. get: function () {
  92186. return this._skyboxMaterial;
  92187. },
  92188. enumerable: true,
  92189. configurable: true
  92190. });
  92191. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  92192. /**
  92193. * Gets the ground mesh created by the helper.
  92194. */
  92195. get: function () {
  92196. return this._ground;
  92197. },
  92198. enumerable: true,
  92199. configurable: true
  92200. });
  92201. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  92202. /**
  92203. * Gets the ground texture created by the helper.
  92204. */
  92205. get: function () {
  92206. return this._groundTexture;
  92207. },
  92208. enumerable: true,
  92209. configurable: true
  92210. });
  92211. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  92212. /**
  92213. * Gets the ground mirror created by the helper.
  92214. */
  92215. get: function () {
  92216. return this._groundMirror;
  92217. },
  92218. enumerable: true,
  92219. configurable: true
  92220. });
  92221. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  92222. /**
  92223. * Gets the ground mirror render list to helps pushing the meshes
  92224. * you wish in the ground reflection.
  92225. */
  92226. get: function () {
  92227. if (this._groundMirror) {
  92228. return this._groundMirror.renderList;
  92229. }
  92230. return null;
  92231. },
  92232. enumerable: true,
  92233. configurable: true
  92234. });
  92235. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  92236. /**
  92237. * Gets the ground material created by the helper.
  92238. */
  92239. get: function () {
  92240. return this._groundMaterial;
  92241. },
  92242. enumerable: true,
  92243. configurable: true
  92244. });
  92245. /**
  92246. * Updates the background according to the new options
  92247. * @param options
  92248. */
  92249. EnvironmentHelper.prototype.updateOptions = function (options) {
  92250. var newOptions = __assign({}, this._options, options);
  92251. if (this._ground && !newOptions.createGround) {
  92252. this._ground.dispose();
  92253. this._ground = null;
  92254. }
  92255. if (this._groundMaterial && !newOptions.createGround) {
  92256. this._groundMaterial.dispose();
  92257. this._groundMaterial = null;
  92258. }
  92259. if (this._groundTexture) {
  92260. if (this._options.groundTexture != newOptions.groundTexture) {
  92261. this._groundTexture.dispose();
  92262. this._groundTexture = null;
  92263. }
  92264. }
  92265. if (this._skybox && !newOptions.createSkybox) {
  92266. this._skybox.dispose();
  92267. this._skybox = null;
  92268. }
  92269. if (this._skyboxMaterial && !newOptions.createSkybox) {
  92270. this._skyboxMaterial.dispose();
  92271. this._skyboxMaterial = null;
  92272. }
  92273. if (this._skyboxTexture) {
  92274. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  92275. this._skyboxTexture.dispose();
  92276. this._skyboxTexture = null;
  92277. }
  92278. }
  92279. if (this._groundMirror && !newOptions.enableGroundMirror) {
  92280. this._groundMirror.dispose();
  92281. this._groundMirror = null;
  92282. }
  92283. if (this._scene.environmentTexture) {
  92284. if (this._options.environmentTexture != newOptions.environmentTexture) {
  92285. this._scene.environmentTexture.dispose();
  92286. }
  92287. }
  92288. this._options = newOptions;
  92289. this._setupBackground();
  92290. this._setupImageProcessing();
  92291. };
  92292. /**
  92293. * Sets the primary color of all the available elements.
  92294. * @param color
  92295. */
  92296. EnvironmentHelper.prototype.setMainColor = function (color) {
  92297. if (this.groundMaterial) {
  92298. this.groundMaterial.primaryColor = color;
  92299. }
  92300. if (this.skyboxMaterial) {
  92301. this.skyboxMaterial.primaryColor = color;
  92302. }
  92303. if (this.groundMirror) {
  92304. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  92305. }
  92306. };
  92307. /**
  92308. * Setup the image processing according to the specified options.
  92309. */
  92310. EnvironmentHelper.prototype._setupImageProcessing = function () {
  92311. if (this._options.setupImageProcessing) {
  92312. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  92313. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  92314. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  92315. this._setupEnvironmentTexture();
  92316. }
  92317. };
  92318. /**
  92319. * Setup the environment texture according to the specified options.
  92320. */
  92321. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  92322. if (this._scene.environmentTexture) {
  92323. return;
  92324. }
  92325. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  92326. this._scene.environmentTexture = this._options.environmentTexture;
  92327. return;
  92328. }
  92329. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  92330. this._scene.environmentTexture = environmentTexture;
  92331. };
  92332. /**
  92333. * Setup the background according to the specified options.
  92334. */
  92335. EnvironmentHelper.prototype._setupBackground = function () {
  92336. if (!this._rootMesh) {
  92337. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  92338. }
  92339. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  92340. var sceneSize = this._getSceneSize();
  92341. if (this._options.createGround) {
  92342. this._setupGround(sceneSize);
  92343. this._setupGroundMaterial();
  92344. this._setupGroundDiffuseTexture();
  92345. if (this._options.enableGroundMirror) {
  92346. this._setupGroundMirrorTexture(sceneSize);
  92347. }
  92348. this._setupMirrorInGroundMaterial();
  92349. }
  92350. if (this._options.createSkybox) {
  92351. this._setupSkybox(sceneSize);
  92352. this._setupSkyboxMaterial();
  92353. this._setupSkyboxReflectionTexture();
  92354. }
  92355. this._rootMesh.position.x = sceneSize.rootPosition.x;
  92356. this._rootMesh.position.z = sceneSize.rootPosition.z;
  92357. this._rootMesh.position.y = sceneSize.rootPosition.y;
  92358. };
  92359. /**
  92360. * Get the scene sizes according to the setup.
  92361. */
  92362. EnvironmentHelper.prototype._getSceneSize = function () {
  92363. var _this = this;
  92364. var groundSize = this._options.groundSize;
  92365. var skyboxSize = this._options.skyboxSize;
  92366. var rootPosition = this._options.rootPosition;
  92367. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  92368. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92369. }
  92370. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  92371. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  92372. });
  92373. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  92374. if (this._options.sizeAuto) {
  92375. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  92376. this._scene.activeCamera.upperRadiusLimit) {
  92377. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  92378. skyboxSize = groundSize;
  92379. }
  92380. var sceneDiagonalLenght = sceneDiagonal.length();
  92381. if (sceneDiagonalLenght > groundSize) {
  92382. groundSize = sceneDiagonalLenght * 2;
  92383. skyboxSize = groundSize;
  92384. }
  92385. // 10 % bigger.
  92386. groundSize *= 1.1;
  92387. skyboxSize *= 1.5;
  92388. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  92389. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  92390. }
  92391. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92392. };
  92393. /**
  92394. * Setup the ground according to the specified options.
  92395. */
  92396. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  92397. var _this = this;
  92398. if (!this._ground) {
  92399. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  92400. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  92401. this._ground.parent = this._rootMesh;
  92402. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  92403. }
  92404. this._ground.receiveShadows = this._options.enableGroundShadow;
  92405. };
  92406. /**
  92407. * Setup the ground material according to the specified options.
  92408. */
  92409. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  92410. if (!this._groundMaterial) {
  92411. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  92412. }
  92413. this._groundMaterial.alpha = this._options.groundOpacity;
  92414. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  92415. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  92416. this._groundMaterial.primaryLevel = 1;
  92417. this._groundMaterial.primaryColor = this._options.groundColor;
  92418. this._groundMaterial.secondaryLevel = 0;
  92419. this._groundMaterial.tertiaryLevel = 0;
  92420. this._groundMaterial.useRGBColor = false;
  92421. this._groundMaterial.enableNoise = true;
  92422. if (this._ground) {
  92423. this._ground.material = this._groundMaterial;
  92424. }
  92425. };
  92426. /**
  92427. * Setup the ground diffuse texture according to the specified options.
  92428. */
  92429. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  92430. if (!this._groundMaterial) {
  92431. return;
  92432. }
  92433. if (this._groundTexture) {
  92434. return;
  92435. }
  92436. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  92437. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  92438. return;
  92439. }
  92440. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92441. diffuseTexture.gammaSpace = false;
  92442. diffuseTexture.hasAlpha = true;
  92443. this._groundMaterial.diffuseTexture = diffuseTexture;
  92444. };
  92445. /**
  92446. * Setup the ground mirror texture according to the specified options.
  92447. */
  92448. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  92449. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92450. if (!this._groundMirror) {
  92451. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  92452. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  92453. this._groundMirror.anisotropicFilteringLevel = 1;
  92454. this._groundMirror.wrapU = wrapping;
  92455. this._groundMirror.wrapV = wrapping;
  92456. this._groundMirror.gammaSpace = false;
  92457. if (this._groundMirror.renderList) {
  92458. for (var i = 0; i < this._scene.meshes.length; i++) {
  92459. var mesh = this._scene.meshes[i];
  92460. if (mesh !== this._ground &&
  92461. mesh !== this._skybox &&
  92462. mesh !== this._rootMesh) {
  92463. this._groundMirror.renderList.push(mesh);
  92464. }
  92465. }
  92466. }
  92467. }
  92468. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  92469. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  92470. };
  92471. /**
  92472. * Setup the ground to receive the mirror texture.
  92473. */
  92474. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  92475. if (this._groundMaterial) {
  92476. this._groundMaterial.reflectionTexture = this._groundMirror;
  92477. this._groundMaterial.reflectionFresnel = true;
  92478. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  92479. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  92480. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  92481. }
  92482. };
  92483. /**
  92484. * Setup the skybox according to the specified options.
  92485. */
  92486. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  92487. var _this = this;
  92488. if (!this._skybox) {
  92489. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  92490. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  92491. }
  92492. this._skybox.parent = this._rootMesh;
  92493. };
  92494. /**
  92495. * Setup the skybox material according to the specified options.
  92496. */
  92497. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  92498. if (!this._skybox) {
  92499. return;
  92500. }
  92501. if (!this._skyboxMaterial) {
  92502. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  92503. }
  92504. this._skyboxMaterial.useRGBColor = false;
  92505. this._skyboxMaterial.primaryLevel = 1;
  92506. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  92507. this._skyboxMaterial.secondaryLevel = 0;
  92508. this._skyboxMaterial.tertiaryLevel = 0;
  92509. this._skyboxMaterial.enableNoise = true;
  92510. this._skybox.material = this._skyboxMaterial;
  92511. };
  92512. /**
  92513. * Setup the skybox reflection texture according to the specified options.
  92514. */
  92515. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  92516. if (!this._skyboxMaterial) {
  92517. return;
  92518. }
  92519. if (this._skyboxTexture) {
  92520. return;
  92521. }
  92522. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  92523. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92524. return;
  92525. }
  92526. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92527. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  92528. this._skyboxTexture.gammaSpace = false;
  92529. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92530. };
  92531. /**
  92532. * Dispose all the elements created by the Helper.
  92533. */
  92534. EnvironmentHelper.prototype.dispose = function () {
  92535. if (this._groundMaterial) {
  92536. this._groundMaterial.dispose(true, true);
  92537. }
  92538. if (this._skyboxMaterial) {
  92539. this._skyboxMaterial.dispose(true, true);
  92540. }
  92541. this._rootMesh.dispose(false);
  92542. };
  92543. /**
  92544. * Default ground texture URL.
  92545. */
  92546. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  92547. /**
  92548. * Default skybox texture URL.
  92549. */
  92550. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  92551. /**
  92552. * Default environment texture URL.
  92553. */
  92554. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  92555. return EnvironmentHelper;
  92556. }());
  92557. BABYLON.EnvironmentHelper = EnvironmentHelper;
  92558. })(BABYLON || (BABYLON = {}));
  92559. //# sourceMappingURL=babylon.environmentHelper.js.map
  92560. "use strict";
  92561. var BABYLON;
  92562. (function (BABYLON) {
  92563. /**
  92564. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  92565. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  92566. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  92567. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  92568. */
  92569. var VideoDome = /** @class */ (function (_super) {
  92570. __extends(VideoDome, _super);
  92571. /**
  92572. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  92573. * @param name Element's name, child elements will append suffixes for their own names.
  92574. * @param urlsOrVideo
  92575. * @param options An object containing optional or exposed sub element properties:
  92576. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  92577. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  92578. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  92579. * @param options **loop=true** Automatically loop video on end.
  92580. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  92581. */
  92582. function VideoDome(name, urlsOrVideo, options, scene) {
  92583. var _this = _super.call(this, name, scene) || this;
  92584. // set defaults and manage values
  92585. name = name || "videoDome";
  92586. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  92587. options.clickToPlay = Boolean(options.clickToPlay);
  92588. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  92589. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  92590. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  92591. // create
  92592. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  92593. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  92594. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  92595. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  92596. flat: false,
  92597. radius: options.size,
  92598. subdivisions: options.resolution,
  92599. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  92600. }, scene);
  92601. // configure material
  92602. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  92603. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  92604. material.reflectionTexture = _this._videoTexture;
  92605. material.useEquirectangularFOV = true;
  92606. material.fovMultiplier = 1.0;
  92607. // configure mesh
  92608. _this._mesh.material = material;
  92609. _this._mesh.parent = _this;
  92610. // optional configuration
  92611. if (options.clickToPlay) {
  92612. scene.onPointerUp = function () {
  92613. _this._videoTexture.video.play();
  92614. };
  92615. }
  92616. return _this;
  92617. }
  92618. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  92619. /**
  92620. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  92621. * Also see the options.resolution property.
  92622. */
  92623. get: function () {
  92624. return this._material.fovMultiplier;
  92625. },
  92626. set: function (value) {
  92627. this._material.fovMultiplier = value;
  92628. },
  92629. enumerable: true,
  92630. configurable: true
  92631. });
  92632. /**
  92633. * Releases resources associated with this node.
  92634. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  92635. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  92636. */
  92637. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  92638. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  92639. this._videoTexture.dispose();
  92640. this._mesh.dispose();
  92641. this._material.dispose();
  92642. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  92643. };
  92644. return VideoDome;
  92645. }(BABYLON.Node));
  92646. BABYLON.VideoDome = VideoDome;
  92647. })(BABYLON || (BABYLON = {}));
  92648. //# sourceMappingURL=babylon.videoDome.js.map
  92649. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(textureSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#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#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  92650. 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\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92651. globalObject["BABYLON"] = BABYLON;
  92652. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var WorkerPool = BABYLON.WorkerPool;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var DepthTextureCreationOptions = BABYLON.DepthTextureCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationPropertiesOverride = BABYLON.AnimationPropertiesOverride;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var GPUParticleSystem = BABYLON.GPUParticleSystem;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var DracoCompression = BABYLON.DracoCompression;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var DaydreamController = BABYLON.DaydreamController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var ChromaticAberrationPostProcess = BABYLON.ChromaticAberrationPostProcess;var SharpenPostProcess = BABYLON.SharpenPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var NullEngineOptions = BABYLON.NullEngineOptions;var NullEngine = BABYLON.NullEngine;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var VideoDome = BABYLON.VideoDome;var Space = BABYLON.Space ;var Orientation = BABYLON.Orientation ;var AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation ;var WorkerTaskType = BABYLON.WorkerTaskType ;var WorkerReplyType = BABYLON.WorkerReplyType ;var Xbox360Button = BABYLON.Xbox360Button ;var Xbox360Dpad = BABYLON.Xbox360Dpad ;var PoseEnabledControllerType = BABYLON.PoseEnabledControllerType ;var DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel ;var TonemappingOperator = BABYLON.TonemappingOperator ;var PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff ;var PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode ;var JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;
  92653. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,WorkerPool,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,DepthTextureCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationPropertiesOverride,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,GPUParticleSystem,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,DracoCompression,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,DaydreamController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,ChromaticAberrationPostProcess,SharpenPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,DepthOfFieldMergePostProcess,CircleOfConfusionPostProcess,DepthOfFieldEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,VideoDome,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,JoystickAxis ,SimplificationType ,AssetTaskState };